1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief Custom DAG lowering for SI
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifdef _MSC_VER
16 // Provide M_PI.
17 #define _USE_MATH_DEFINES
18 #endif
19 
20 #include "AMDGPU.h"
21 #include "AMDGPUIntrinsicInfo.h"
22 #include "AMDGPUTargetMachine.h"
23 #include "AMDGPUSubtarget.h"
24 #include "SIDefines.h"
25 #include "SIISelLowering.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "Utils/AMDGPUBaseInfo.h"
30 #include "llvm/ADT/APFloat.h"
31 #include "llvm/ADT/APInt.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/CallingConvLower.h"
40 #include "llvm/CodeGen/DAGCombine.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/MachineValueType.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/ValueTypes.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/DiagnosticInfo.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GlobalValue.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Target/TargetCallingConv.h"
73 #include "llvm/Target/TargetOptions.h"
74 #include "llvm/Target/TargetRegisterInfo.h"
75 #include <cassert>
76 #include <cmath>
77 #include <cstdint>
78 #include <iterator>
79 #include <tuple>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 static cl::opt<bool> EnableVGPRIndexMode(
86   "amdgpu-vgpr-index-mode",
87   cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
88   cl::init(false));
89 
90 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
91   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
92   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
93     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
94       return AMDGPU::SGPR0 + Reg;
95     }
96   }
97   llvm_unreachable("Cannot allocate sgpr");
98 }
99 
100 SITargetLowering::SITargetLowering(const TargetMachine &TM,
101                                    const SISubtarget &STI)
102     : AMDGPUTargetLowering(TM, STI) {
103   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
104   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
105 
106   addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
107   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
108 
109   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
110   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
111   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
112 
113   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
114   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
115 
116   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
117   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
118 
119   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
120   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
121 
122   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
123   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
124 
125   if (Subtarget->has16BitInsts()) {
126     addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
127     addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
128   }
129 
130   if (Subtarget->hasVOP3PInsts()) {
131     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
132     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
133   }
134 
135   computeRegisterProperties(STI.getRegisterInfo());
136 
137   // We need to custom lower vector stores from local memory
138   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
139   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
140   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
141   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
142   setOperationAction(ISD::LOAD, MVT::i1, Custom);
143 
144   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
145   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
146   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
147   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
148   setOperationAction(ISD::STORE, MVT::i1, Custom);
149 
150   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
151   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
152   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
153   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
154   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
155   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
156   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
157   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
158   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
159   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
160 
161   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
162   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
163   setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
164 
165   setOperationAction(ISD::SELECT, MVT::i1, Promote);
166   setOperationAction(ISD::SELECT, MVT::i64, Custom);
167   setOperationAction(ISD::SELECT, MVT::f64, Promote);
168   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
169 
170   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
171   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
172   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
173   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
174   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
175 
176   setOperationAction(ISD::SETCC, MVT::i1, Promote);
177   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
178   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
179   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
180 
181   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
182   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
183 
184   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
185   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
186   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
187   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
188   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
189   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
190   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
191 
192   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
193   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
194   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
195   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
196 
197   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
198 
199   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
200   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
201   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
202 
203   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
204   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
205   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
206   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
207   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
208   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
209 
210   setOperationAction(ISD::UADDO, MVT::i32, Legal);
211   setOperationAction(ISD::USUBO, MVT::i32, Legal);
212 
213   // We only support LOAD/STORE and vector manipulation ops for vectors
214   // with > 4 elements.
215   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
216         MVT::v2i64, MVT::v2f64}) {
217     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
218       switch (Op) {
219       case ISD::LOAD:
220       case ISD::STORE:
221       case ISD::BUILD_VECTOR:
222       case ISD::BITCAST:
223       case ISD::EXTRACT_VECTOR_ELT:
224       case ISD::INSERT_VECTOR_ELT:
225       case ISD::INSERT_SUBVECTOR:
226       case ISD::EXTRACT_SUBVECTOR:
227       case ISD::SCALAR_TO_VECTOR:
228         break;
229       case ISD::CONCAT_VECTORS:
230         setOperationAction(Op, VT, Custom);
231         break;
232       default:
233         setOperationAction(Op, VT, Expand);
234         break;
235       }
236     }
237   }
238 
239   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
240   // is expanded to avoid having two separate loops in case the index is a VGPR.
241 
242   // Most operations are naturally 32-bit vector operations. We only support
243   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
244   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
245     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
246     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
247 
248     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
249     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
250 
251     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
252     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
253 
254     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
255     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
256   }
257 
258   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
259   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
260   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
261   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
262 
263   // Avoid stack access for these.
264   // TODO: Generalize to more vector types.
265   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
266   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
267   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
268   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
269 
270   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
271   // and output demarshalling
272   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
273   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
274 
275   // We can't return success/failure, only the old value,
276   // let LLVM add the comparison
277   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
278   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
279 
280   if (getSubtarget()->hasFlatAddressSpace()) {
281     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
282     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
283   }
284 
285   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
286   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
287 
288   // On SI this is s_memtime and s_memrealtime on VI.
289   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
290   setOperationAction(ISD::TRAP, MVT::Other, Legal);
291   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
292 
293   setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
294   setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
295 
296   if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
297     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
298     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
299     setOperationAction(ISD::FRINT, MVT::f64, Legal);
300   }
301 
302   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
303 
304   setOperationAction(ISD::FSIN, MVT::f32, Custom);
305   setOperationAction(ISD::FCOS, MVT::f32, Custom);
306   setOperationAction(ISD::FDIV, MVT::f32, Custom);
307   setOperationAction(ISD::FDIV, MVT::f64, Custom);
308 
309   if (Subtarget->has16BitInsts()) {
310     setOperationAction(ISD::Constant, MVT::i16, Legal);
311 
312     setOperationAction(ISD::SMIN, MVT::i16, Legal);
313     setOperationAction(ISD::SMAX, MVT::i16, Legal);
314 
315     setOperationAction(ISD::UMIN, MVT::i16, Legal);
316     setOperationAction(ISD::UMAX, MVT::i16, Legal);
317 
318     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
319     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
320 
321     setOperationAction(ISD::ROTR, MVT::i16, Promote);
322     setOperationAction(ISD::ROTL, MVT::i16, Promote);
323 
324     setOperationAction(ISD::SDIV, MVT::i16, Promote);
325     setOperationAction(ISD::UDIV, MVT::i16, Promote);
326     setOperationAction(ISD::SREM, MVT::i16, Promote);
327     setOperationAction(ISD::UREM, MVT::i16, Promote);
328 
329     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
330     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
331 
332     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
334     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
335     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
336 
337     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
338 
339     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
340 
341     setOperationAction(ISD::LOAD, MVT::i16, Custom);
342 
343     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
344 
345     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
346     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
347     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
348     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
349 
350     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
351     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
352     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
353     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
354 
355     // F16 - Constant Actions.
356     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
357 
358     // F16 - Load/Store Actions.
359     setOperationAction(ISD::LOAD, MVT::f16, Promote);
360     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
361     setOperationAction(ISD::STORE, MVT::f16, Promote);
362     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
363 
364     // F16 - VOP1 Actions.
365     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
366     setOperationAction(ISD::FCOS, MVT::f16, Promote);
367     setOperationAction(ISD::FSIN, MVT::f16, Promote);
368     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
369     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
370     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
371     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
372     setOperationAction(ISD::FROUND, MVT::f16, Custom);
373 
374     // F16 - VOP2 Actions.
375     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
376     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
377     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
378     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
379     setOperationAction(ISD::FDIV, MVT::f16, Custom);
380 
381     // F16 - VOP3 Actions.
382     setOperationAction(ISD::FMA, MVT::f16, Legal);
383     if (!Subtarget->hasFP16Denormals())
384       setOperationAction(ISD::FMAD, MVT::f16, Legal);
385   }
386 
387   if (Subtarget->hasVOP3PInsts()) {
388     for (MVT VT : {MVT::v2i16, MVT::v2f16}) {
389       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
390         switch (Op) {
391         case ISD::LOAD:
392         case ISD::STORE:
393         case ISD::BUILD_VECTOR:
394         case ISD::BITCAST:
395         case ISD::EXTRACT_VECTOR_ELT:
396         case ISD::INSERT_VECTOR_ELT:
397         case ISD::INSERT_SUBVECTOR:
398         case ISD::EXTRACT_SUBVECTOR:
399         case ISD::SCALAR_TO_VECTOR:
400           break;
401         case ISD::CONCAT_VECTORS:
402           setOperationAction(Op, VT, Custom);
403           break;
404         default:
405           setOperationAction(Op, VT, Expand);
406           break;
407         }
408       }
409     }
410 
411     // XXX - Do these do anything? Vector constants turn into build_vector.
412     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
413     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
414 
415     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
416     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
417     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
418     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
419 
420     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
421     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
422     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
423     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
424 
425     setOperationAction(ISD::AND, MVT::v2i16, Promote);
426     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
427     setOperationAction(ISD::OR, MVT::v2i16, Promote);
428     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
429     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
430     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
431     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
432     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
433     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
434     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
435 
436     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
437     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
438     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
439     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
440     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
441     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
442     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
443     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
444     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
445     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
446 
447     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
448     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
449     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
450     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
451     setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
452     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
453 
454     // This isn't really legal, but this avoids the legalizer unrolling it (and
455     // allows matching fneg (fabs x) patterns)
456     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
457 
458     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
459     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
460 
461     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
462     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
463     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
464   }
465 
466   setTargetDAGCombine(ISD::FADD);
467   setTargetDAGCombine(ISD::FSUB);
468   setTargetDAGCombine(ISD::FMINNUM);
469   setTargetDAGCombine(ISD::FMAXNUM);
470   setTargetDAGCombine(ISD::SMIN);
471   setTargetDAGCombine(ISD::SMAX);
472   setTargetDAGCombine(ISD::UMIN);
473   setTargetDAGCombine(ISD::UMAX);
474   setTargetDAGCombine(ISD::SETCC);
475   setTargetDAGCombine(ISD::AND);
476   setTargetDAGCombine(ISD::OR);
477   setTargetDAGCombine(ISD::XOR);
478   setTargetDAGCombine(ISD::SINT_TO_FP);
479   setTargetDAGCombine(ISD::UINT_TO_FP);
480   setTargetDAGCombine(ISD::FCANONICALIZE);
481   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
482   setTargetDAGCombine(ISD::ZERO_EXTEND);
483 
484   // All memory operations. Some folding on the pointer operand is done to help
485   // matching the constant offsets in the addressing modes.
486   setTargetDAGCombine(ISD::LOAD);
487   setTargetDAGCombine(ISD::STORE);
488   setTargetDAGCombine(ISD::ATOMIC_LOAD);
489   setTargetDAGCombine(ISD::ATOMIC_STORE);
490   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
491   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
492   setTargetDAGCombine(ISD::ATOMIC_SWAP);
493   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
494   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
495   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
496   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
497   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
498   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
499   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
500   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
501   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
502   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
503 
504   setSchedulingPreference(Sched::RegPressure);
505 }
506 
507 const SISubtarget *SITargetLowering::getSubtarget() const {
508   return static_cast<const SISubtarget *>(Subtarget);
509 }
510 
511 //===----------------------------------------------------------------------===//
512 // TargetLowering queries
513 //===----------------------------------------------------------------------===//
514 
515 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
516                                           EVT) const {
517   // SI has some legal vector types, but no legal vector operations. Say no
518   // shuffles are legal in order to prefer scalarizing some vector operations.
519   return false;
520 }
521 
522 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
523                                           const CallInst &CI,
524                                           unsigned IntrID) const {
525   switch (IntrID) {
526   case Intrinsic::amdgcn_atomic_inc:
527   case Intrinsic::amdgcn_atomic_dec: {
528     Info.opc = ISD::INTRINSIC_W_CHAIN;
529     Info.memVT = MVT::getVT(CI.getType());
530     Info.ptrVal = CI.getOperand(0);
531     Info.align = 0;
532 
533     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
534     Info.vol = !Vol || !Vol->isNullValue();
535     Info.readMem = true;
536     Info.writeMem = true;
537     return true;
538   }
539   default:
540     return false;
541   }
542 }
543 
544 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
545                                             SmallVectorImpl<Value*> &Ops,
546                                             Type *&AccessTy) const {
547   switch (II->getIntrinsicID()) {
548   case Intrinsic::amdgcn_atomic_inc:
549   case Intrinsic::amdgcn_atomic_dec: {
550     Value *Ptr = II->getArgOperand(0);
551     AccessTy = II->getType();
552     Ops.push_back(Ptr);
553     return true;
554   }
555   default:
556     return false;
557   }
558 }
559 
560 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
561   // Flat instructions do not have offsets, and only have the register
562   // address.
563   return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
564 }
565 
566 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
567   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
568   // additionally can do r + r + i with addr64. 32-bit has more addressing
569   // mode options. Depending on the resource constant, it can also do
570   // (i64 r0) + (i32 r1) * (i14 i).
571   //
572   // Private arrays end up using a scratch buffer most of the time, so also
573   // assume those use MUBUF instructions. Scratch loads / stores are currently
574   // implemented as mubuf instructions with offen bit set, so slightly
575   // different than the normal addr64.
576   if (!isUInt<12>(AM.BaseOffs))
577     return false;
578 
579   // FIXME: Since we can split immediate into soffset and immediate offset,
580   // would it make sense to allow any immediate?
581 
582   switch (AM.Scale) {
583   case 0: // r + i or just i, depending on HasBaseReg.
584     return true;
585   case 1:
586     return true; // We have r + r or r + i.
587   case 2:
588     if (AM.HasBaseReg) {
589       // Reject 2 * r + r.
590       return false;
591     }
592 
593     // Allow 2 * r as r + r
594     // Or  2 * r + i is allowed as r + r + i.
595     return true;
596   default: // Don't allow n * r
597     return false;
598   }
599 }
600 
601 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
602                                              const AddrMode &AM, Type *Ty,
603                                              unsigned AS) const {
604   // No global is ever allowed as a base.
605   if (AM.BaseGV)
606     return false;
607 
608   if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
609     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
610       // Assume the we will use FLAT for all global memory accesses
611       // on VI.
612       // FIXME: This assumption is currently wrong.  On VI we still use
613       // MUBUF instructions for the r + i addressing mode.  As currently
614       // implemented, the MUBUF instructions only work on buffer < 4GB.
615       // It may be possible to support > 4GB buffers with MUBUF instructions,
616       // by setting the stride value in the resource descriptor which would
617       // increase the size limit to (stride * 4GB).  However, this is risky,
618       // because it has never been validated.
619       return isLegalFlatAddressingMode(AM);
620     }
621 
622     return isLegalMUBUFAddressingMode(AM);
623   } else if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
624     // If the offset isn't a multiple of 4, it probably isn't going to be
625     // correctly aligned.
626     // FIXME: Can we get the real alignment here?
627     if (AM.BaseOffs % 4 != 0)
628       return isLegalMUBUFAddressingMode(AM);
629 
630     // There are no SMRD extloads, so if we have to do a small type access we
631     // will use a MUBUF load.
632     // FIXME?: We also need to do this if unaligned, but we don't know the
633     // alignment here.
634     if (DL.getTypeStoreSize(Ty) < 4)
635       return isLegalMUBUFAddressingMode(AM);
636 
637     if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
638       // SMRD instructions have an 8-bit, dword offset on SI.
639       if (!isUInt<8>(AM.BaseOffs / 4))
640         return false;
641     } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
642       // On CI+, this can also be a 32-bit literal constant offset. If it fits
643       // in 8-bits, it can use a smaller encoding.
644       if (!isUInt<32>(AM.BaseOffs / 4))
645         return false;
646     } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
647       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
648       if (!isUInt<20>(AM.BaseOffs))
649         return false;
650     } else
651       llvm_unreachable("unhandled generation");
652 
653     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
654       return true;
655 
656     if (AM.Scale == 1 && AM.HasBaseReg)
657       return true;
658 
659     return false;
660 
661   } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
662     return isLegalMUBUFAddressingMode(AM);
663   } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
664              AS == AMDGPUASI.REGION_ADDRESS) {
665     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
666     // field.
667     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
668     // an 8-bit dword offset but we don't know the alignment here.
669     if (!isUInt<16>(AM.BaseOffs))
670       return false;
671 
672     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
673       return true;
674 
675     if (AM.Scale == 1 && AM.HasBaseReg)
676       return true;
677 
678     return false;
679   } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
680              AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
681     // For an unknown address space, this usually means that this is for some
682     // reason being used for pure arithmetic, and not based on some addressing
683     // computation. We don't have instructions that compute pointers with any
684     // addressing modes, so treat them as having no offset like flat
685     // instructions.
686     return isLegalFlatAddressingMode(AM);
687   } else {
688     llvm_unreachable("unhandled address space");
689   }
690 }
691 
692 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
693                                                       unsigned AddrSpace,
694                                                       unsigned Align,
695                                                       bool *IsFast) const {
696   if (IsFast)
697     *IsFast = false;
698 
699   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
700   // which isn't a simple VT.
701   // Until MVT is extended to handle this, simply check for the size and
702   // rely on the condition below: allow accesses if the size is a multiple of 4.
703   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
704                            VT.getStoreSize() > 16)) {
705     return false;
706   }
707 
708   if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
709       AddrSpace == AMDGPUASI.REGION_ADDRESS) {
710     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
711     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
712     // with adjacent offsets.
713     bool AlignedBy4 = (Align % 4 == 0);
714     if (IsFast)
715       *IsFast = AlignedBy4;
716 
717     return AlignedBy4;
718   }
719 
720   // FIXME: We have to be conservative here and assume that flat operations
721   // will access scratch.  If we had access to the IR function, then we
722   // could determine if any private memory was used in the function.
723   if (!Subtarget->hasUnalignedScratchAccess() &&
724       (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
725        AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
726     return false;
727   }
728 
729   if (Subtarget->hasUnalignedBufferAccess()) {
730     // If we have an uniform constant load, it still requires using a slow
731     // buffer instruction if unaligned.
732     if (IsFast) {
733       *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ?
734         (Align % 4 == 0) : true;
735     }
736 
737     return true;
738   }
739 
740   // Smaller than dword value must be aligned.
741   if (VT.bitsLT(MVT::i32))
742     return false;
743 
744   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
745   // byte-address are ignored, thus forcing Dword alignment.
746   // This applies to private, global, and constant memory.
747   if (IsFast)
748     *IsFast = true;
749 
750   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
751 }
752 
753 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
754                                           unsigned SrcAlign, bool IsMemset,
755                                           bool ZeroMemset,
756                                           bool MemcpyStrSrc,
757                                           MachineFunction &MF) const {
758   // FIXME: Should account for address space here.
759 
760   // The default fallback uses the private pointer size as a guess for a type to
761   // use. Make sure we switch these to 64-bit accesses.
762 
763   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
764     return MVT::v4i32;
765 
766   if (Size >= 8 && DstAlign >= 4)
767     return MVT::v2i32;
768 
769   // Use the default.
770   return MVT::Other;
771 }
772 
773 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
774   return AS == AMDGPUASI.GLOBAL_ADDRESS ||
775          AS == AMDGPUASI.FLAT_ADDRESS ||
776          AS == AMDGPUASI.CONSTANT_ADDRESS;
777 }
778 
779 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
780                                            unsigned DestAS) const {
781   return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
782          isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
783 }
784 
785 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
786   const MemSDNode *MemNode = cast<MemSDNode>(N);
787   const Value *Ptr = MemNode->getMemOperand()->getValue();
788   const Instruction *I = dyn_cast<Instruction>(Ptr);
789   return I && I->getMetadata("amdgpu.noclobber");
790 }
791 
792 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
793                                             unsigned DestAS) const {
794   // Flat -> private/local is a simple truncate.
795   // Flat -> global is no-op
796   if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
797     return true;
798 
799   return isNoopAddrSpaceCast(SrcAS, DestAS);
800 }
801 
802 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
803   const MemSDNode *MemNode = cast<MemSDNode>(N);
804 
805   return AMDGPU::isUniformMMO(MemNode->getMemOperand());
806 }
807 
808 TargetLoweringBase::LegalizeTypeAction
809 SITargetLowering::getPreferredVectorAction(EVT VT) const {
810   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
811     return TypeSplitVector;
812 
813   return TargetLoweringBase::getPreferredVectorAction(VT);
814 }
815 
816 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
817                                                          Type *Ty) const {
818   // FIXME: Could be smarter if called for vector constants.
819   return true;
820 }
821 
822 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
823   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
824     switch (Op) {
825     case ISD::LOAD:
826     case ISD::STORE:
827 
828     // These operations are done with 32-bit instructions anyway.
829     case ISD::AND:
830     case ISD::OR:
831     case ISD::XOR:
832     case ISD::SELECT:
833       // TODO: Extensions?
834       return true;
835     default:
836       return false;
837     }
838   }
839 
840   // SimplifySetCC uses this function to determine whether or not it should
841   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
842   if (VT == MVT::i1 && Op == ISD::SETCC)
843     return false;
844 
845   return TargetLowering::isTypeDesirableForOp(Op, VT);
846 }
847 
848 SDValue SITargetLowering::LowerParameterPtr(SelectionDAG &DAG,
849                                             const SDLoc &SL, SDValue Chain,
850                                             unsigned Offset) const {
851   const DataLayout &DL = DAG.getDataLayout();
852   MachineFunction &MF = DAG.getMachineFunction();
853   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
854   unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
855 
856   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
857   MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
858   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
859                                        MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
860   return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
861                      DAG.getConstant(Offset, SL, PtrVT));
862 }
863 
864 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
865                                          const SDLoc &SL, SDValue Chain,
866                                          unsigned Offset, bool Signed,
867                                          const ISD::InputArg *Arg) const {
868   const DataLayout &DL = DAG.getDataLayout();
869   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
870   PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
871   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
872 
873   unsigned Align = DL.getABITypeAlignment(Ty);
874 
875   SDValue Ptr = LowerParameterPtr(DAG, SL, Chain, Offset);
876   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
877                              MachineMemOperand::MONonTemporal |
878                              MachineMemOperand::MODereferenceable |
879                              MachineMemOperand::MOInvariant);
880 
881   SDValue Val = Load;
882   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
883       VT.bitsLT(MemVT)) {
884     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
885     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
886   }
887 
888   if (MemVT.isFloatingPoint())
889     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
890   else if (Signed)
891     Val = DAG.getSExtOrTrunc(Val, SL, VT);
892   else
893     Val = DAG.getZExtOrTrunc(Val, SL, VT);
894 
895   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
896 }
897 
898 SDValue SITargetLowering::LowerFormalArguments(
899     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
900     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
901     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
902   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
903 
904   MachineFunction &MF = DAG.getMachineFunction();
905   FunctionType *FType = MF.getFunction()->getFunctionType();
906   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
907   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
908 
909   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
910     const Function *Fn = MF.getFunction();
911     DiagnosticInfoUnsupported NoGraphicsHSA(
912         *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
913     DAG.getContext()->diagnose(NoGraphicsHSA);
914     return DAG.getEntryNode();
915   }
916 
917   // Create stack objects that are used for emitting debugger prologue if
918   // "amdgpu-debugger-emit-prologue" attribute was specified.
919   if (ST.debuggerEmitPrologue())
920     createDebuggerPrologueStackObjects(MF);
921 
922   SmallVector<ISD::InputArg, 16> Splits;
923   BitVector Skipped(Ins.size());
924 
925   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
926     const ISD::InputArg &Arg = Ins[i];
927 
928     // First check if it's a PS input addr
929     if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
930         !Arg.Flags.isByVal() && PSInputNum <= 15) {
931 
932       if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
933         // We can safely skip PS inputs
934         Skipped.set(i);
935         ++PSInputNum;
936         continue;
937       }
938 
939       Info->markPSInputAllocated(PSInputNum);
940       if (Arg.Used)
941         Info->PSInputEna |= 1 << PSInputNum;
942 
943       ++PSInputNum;
944     }
945 
946     if (AMDGPU::isShader(CallConv)) {
947       // Second split vertices into their elements
948       if (Arg.VT.isVector()) {
949         ISD::InputArg NewArg = Arg;
950         NewArg.Flags.setSplit();
951         NewArg.VT = Arg.VT.getVectorElementType();
952 
953         // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
954         // three or five element vertex only needs three or five registers,
955         // NOT four or eight.
956         Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
957         unsigned NumElements = ParamType->getVectorNumElements();
958 
959         for (unsigned j = 0; j != NumElements; ++j) {
960           Splits.push_back(NewArg);
961           NewArg.PartOffset += NewArg.VT.getStoreSize();
962         }
963       } else {
964         Splits.push_back(Arg);
965       }
966     }
967   }
968 
969   SmallVector<CCValAssign, 16> ArgLocs;
970   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
971                  *DAG.getContext());
972 
973   // At least one interpolation mode must be enabled or else the GPU will hang.
974   //
975   // Check PSInputAddr instead of PSInputEna. The idea is that if the user set
976   // PSInputAddr, the user wants to enable some bits after the compilation
977   // based on run-time states. Since we can't know what the final PSInputEna
978   // will look like, so we shouldn't do anything here and the user should take
979   // responsibility for the correct programming.
980   //
981   // Otherwise, the following restrictions apply:
982   // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
983   // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
984   //   enabled too.
985   if (CallConv == CallingConv::AMDGPU_PS &&
986       ((Info->getPSInputAddr() & 0x7F) == 0 ||
987        ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11)))) {
988     CCInfo.AllocateReg(AMDGPU::VGPR0);
989     CCInfo.AllocateReg(AMDGPU::VGPR1);
990     Info->markPSInputAllocated(0);
991     Info->PSInputEna |= 1;
992   }
993 
994   if (!AMDGPU::isShader(CallConv)) {
995     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
996   } else {
997     assert(!Info->hasDispatchPtr() &&
998            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
999            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1000            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1001            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1002            !Info->hasWorkItemIDZ());
1003   }
1004 
1005   if (Info->hasPrivateMemoryInputPtr()) {
1006     unsigned PrivateMemoryPtrReg = Info->addPrivateMemoryPtr(*TRI);
1007     MF.addLiveIn(PrivateMemoryPtrReg, &AMDGPU::SReg_64RegClass);
1008     CCInfo.AllocateReg(PrivateMemoryPtrReg);
1009   }
1010 
1011   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1012   if (Info->hasPrivateSegmentBuffer()) {
1013     unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI);
1014     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass);
1015     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1016   }
1017 
1018   if (Info->hasDispatchPtr()) {
1019     unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI);
1020     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1021     CCInfo.AllocateReg(DispatchPtrReg);
1022   }
1023 
1024   if (Info->hasQueuePtr()) {
1025     unsigned QueuePtrReg = Info->addQueuePtr(*TRI);
1026     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1027     CCInfo.AllocateReg(QueuePtrReg);
1028   }
1029 
1030   if (Info->hasKernargSegmentPtr()) {
1031     unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI);
1032     MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1033     CCInfo.AllocateReg(InputPtrReg);
1034   }
1035 
1036   if (Info->hasDispatchID()) {
1037     unsigned DispatchIDReg = Info->addDispatchID(*TRI);
1038     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1039     CCInfo.AllocateReg(DispatchIDReg);
1040   }
1041 
1042   if (Info->hasFlatScratchInit()) {
1043     unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI);
1044     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1045     CCInfo.AllocateReg(FlatScratchInitReg);
1046   }
1047 
1048   if (!AMDGPU::isShader(CallConv))
1049     analyzeFormalArgumentsCompute(CCInfo, Ins);
1050   else
1051     AnalyzeFormalArguments(CCInfo, Splits);
1052 
1053   SmallVector<SDValue, 16> Chains;
1054 
1055   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1056     const ISD::InputArg &Arg = Ins[i];
1057     if (Skipped[i]) {
1058       InVals.push_back(DAG.getUNDEF(Arg.VT));
1059       continue;
1060     }
1061 
1062     CCValAssign &VA = ArgLocs[ArgIdx++];
1063     MVT VT = VA.getLocVT();
1064 
1065     if (VA.isMemLoc()) {
1066       VT = Ins[i].VT;
1067       EVT MemVT = VA.getLocVT();
1068       const unsigned Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1069                               VA.getLocMemOffset();
1070       // The first 36 bytes of the input buffer contains information about
1071       // thread group and global sizes.
1072       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, Chain,
1073                                    Offset, Ins[i].Flags.isSExt(),
1074                                    &Ins[i]);
1075       Chains.push_back(Arg.getValue(1));
1076 
1077       auto *ParamTy =
1078         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1079       if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1080           ParamTy && ParamTy->getAddressSpace() == AMDGPUASI.LOCAL_ADDRESS) {
1081         // On SI local pointers are just offsets into LDS, so they are always
1082         // less than 16-bits.  On CI and newer they could potentially be
1083         // real pointers, so we can't guarantee their size.
1084         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1085                           DAG.getValueType(MVT::i16));
1086       }
1087 
1088       InVals.push_back(Arg);
1089       Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1090       continue;
1091     }
1092     assert(VA.isRegLoc() && "Parameter must be in a register!");
1093 
1094     unsigned Reg = VA.getLocReg();
1095 
1096     if (VT == MVT::i64) {
1097       // For now assume it is a pointer
1098       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
1099                                      &AMDGPU::SGPR_64RegClass);
1100       Reg = MF.addLiveIn(Reg, &AMDGPU::SGPR_64RegClass);
1101       SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1102       InVals.push_back(Copy);
1103       continue;
1104     }
1105 
1106     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1107 
1108     Reg = MF.addLiveIn(Reg, RC);
1109     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1110 
1111     if (Arg.VT.isVector()) {
1112       // Build a vector from the registers
1113       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1114       unsigned NumElements = ParamType->getVectorNumElements();
1115 
1116       SmallVector<SDValue, 4> Regs;
1117       Regs.push_back(Val);
1118       for (unsigned j = 1; j != NumElements; ++j) {
1119         Reg = ArgLocs[ArgIdx++].getLocReg();
1120         Reg = MF.addLiveIn(Reg, RC);
1121 
1122         SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1123         Regs.push_back(Copy);
1124       }
1125 
1126       // Fill up the missing vector elements
1127       NumElements = Arg.VT.getVectorNumElements() - NumElements;
1128       Regs.append(NumElements, DAG.getUNDEF(VT));
1129 
1130       InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1131       continue;
1132     }
1133 
1134     InVals.push_back(Val);
1135   }
1136 
1137   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1138   // these from the dispatch pointer.
1139 
1140   // Start adding system SGPRs.
1141   if (Info->hasWorkGroupIDX()) {
1142     unsigned Reg = Info->addWorkGroupIDX();
1143     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1144     CCInfo.AllocateReg(Reg);
1145   }
1146 
1147   if (Info->hasWorkGroupIDY()) {
1148     unsigned Reg = Info->addWorkGroupIDY();
1149     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1150     CCInfo.AllocateReg(Reg);
1151   }
1152 
1153   if (Info->hasWorkGroupIDZ()) {
1154     unsigned Reg = Info->addWorkGroupIDZ();
1155     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1156     CCInfo.AllocateReg(Reg);
1157   }
1158 
1159   if (Info->hasWorkGroupInfo()) {
1160     unsigned Reg = Info->addWorkGroupInfo();
1161     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1162     CCInfo.AllocateReg(Reg);
1163   }
1164 
1165   if (Info->hasPrivateSegmentWaveByteOffset()) {
1166     // Scratch wave offset passed in system SGPR.
1167     unsigned PrivateSegmentWaveByteOffsetReg;
1168 
1169     if (AMDGPU::isShader(CallConv)) {
1170       PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1171       Info->setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1172     } else
1173       PrivateSegmentWaveByteOffsetReg = Info->addPrivateSegmentWaveByteOffset();
1174 
1175     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1176     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1177   }
1178 
1179   // Now that we've figured out where the scratch register inputs are, see if
1180   // should reserve the arguments and use them directly.
1181   bool HasStackObjects = MF.getFrameInfo().hasStackObjects();
1182   // Record that we know we have non-spill stack objects so we don't need to
1183   // check all stack objects later.
1184   if (HasStackObjects)
1185     Info->setHasNonSpillStackObjects(true);
1186 
1187   // Everything live out of a block is spilled with fast regalloc, so it's
1188   // almost certain that spilling will be required.
1189   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
1190     HasStackObjects = true;
1191 
1192   if (ST.isAmdCodeObjectV2(MF)) {
1193     if (HasStackObjects) {
1194       // If we have stack objects, we unquestionably need the private buffer
1195       // resource. For the Code Object V2 ABI, this will be the first 4 user
1196       // SGPR inputs. We can reserve those and use them directly.
1197 
1198       unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue(
1199         MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
1200       Info->setScratchRSrcReg(PrivateSegmentBufferReg);
1201 
1202       unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue(
1203         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1204       Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1205     } else {
1206       unsigned ReservedBufferReg
1207         = TRI->reservedPrivateSegmentBufferReg(MF);
1208       unsigned ReservedOffsetReg
1209         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
1210 
1211       // We tentatively reserve the last registers (skipping the last two
1212       // which may contain VCC). After register allocation, we'll replace
1213       // these with the ones immediately after those which were really
1214       // allocated. In the prologue copies will be inserted from the argument
1215       // to these reserved registers.
1216       Info->setScratchRSrcReg(ReservedBufferReg);
1217       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
1218     }
1219   } else {
1220     unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF);
1221 
1222     // Without HSA, relocations are used for the scratch pointer and the
1223     // buffer resource setup is always inserted in the prologue. Scratch wave
1224     // offset is still in an input SGPR.
1225     Info->setScratchRSrcReg(ReservedBufferReg);
1226 
1227     if (HasStackObjects) {
1228       unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue(
1229         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1230       Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1231     } else {
1232       unsigned ReservedOffsetReg
1233         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
1234       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
1235     }
1236   }
1237 
1238   if (Info->hasWorkItemIDX()) {
1239     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
1240     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1241     CCInfo.AllocateReg(Reg);
1242   }
1243 
1244   if (Info->hasWorkItemIDY()) {
1245     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
1246     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1247     CCInfo.AllocateReg(Reg);
1248   }
1249 
1250   if (Info->hasWorkItemIDZ()) {
1251     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
1252     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1253     CCInfo.AllocateReg(Reg);
1254   }
1255 
1256   if (Chains.empty())
1257     return Chain;
1258 
1259   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1260 }
1261 
1262 SDValue
1263 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1264                               bool isVarArg,
1265                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1266                               const SmallVectorImpl<SDValue> &OutVals,
1267                               const SDLoc &DL, SelectionDAG &DAG) const {
1268   MachineFunction &MF = DAG.getMachineFunction();
1269   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1270 
1271   if (!AMDGPU::isShader(CallConv))
1272     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1273                                              OutVals, DL, DAG);
1274 
1275   Info->setIfReturnsVoid(Outs.size() == 0);
1276 
1277   SmallVector<ISD::OutputArg, 48> Splits;
1278   SmallVector<SDValue, 48> SplitVals;
1279 
1280   // Split vectors into their elements.
1281   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1282     const ISD::OutputArg &Out = Outs[i];
1283 
1284     if (Out.VT.isVector()) {
1285       MVT VT = Out.VT.getVectorElementType();
1286       ISD::OutputArg NewOut = Out;
1287       NewOut.Flags.setSplit();
1288       NewOut.VT = VT;
1289 
1290       // We want the original number of vector elements here, e.g.
1291       // three or five, not four or eight.
1292       unsigned NumElements = Out.ArgVT.getVectorNumElements();
1293 
1294       for (unsigned j = 0; j != NumElements; ++j) {
1295         SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1296                                    DAG.getConstant(j, DL, MVT::i32));
1297         SplitVals.push_back(Elem);
1298         Splits.push_back(NewOut);
1299         NewOut.PartOffset += NewOut.VT.getStoreSize();
1300       }
1301     } else {
1302       SplitVals.push_back(OutVals[i]);
1303       Splits.push_back(Out);
1304     }
1305   }
1306 
1307   // CCValAssign - represent the assignment of the return value to a location.
1308   SmallVector<CCValAssign, 48> RVLocs;
1309 
1310   // CCState - Info about the registers and stack slots.
1311   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1312                  *DAG.getContext());
1313 
1314   // Analyze outgoing return values.
1315   AnalyzeReturn(CCInfo, Splits);
1316 
1317   SDValue Flag;
1318   SmallVector<SDValue, 48> RetOps;
1319   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1320 
1321   // Copy the result values into the output registers.
1322   for (unsigned i = 0, realRVLocIdx = 0;
1323        i != RVLocs.size();
1324        ++i, ++realRVLocIdx) {
1325     CCValAssign &VA = RVLocs[i];
1326     assert(VA.isRegLoc() && "Can only return in registers!");
1327 
1328     SDValue Arg = SplitVals[realRVLocIdx];
1329 
1330     // Copied from other backends.
1331     switch (VA.getLocInfo()) {
1332     default: llvm_unreachable("Unknown loc info!");
1333     case CCValAssign::Full:
1334       break;
1335     case CCValAssign::BCvt:
1336       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1337       break;
1338     }
1339 
1340     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1341     Flag = Chain.getValue(1);
1342     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1343   }
1344 
1345   // Update chain and glue.
1346   RetOps[0] = Chain;
1347   if (Flag.getNode())
1348     RetOps.push_back(Flag);
1349 
1350   unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN_TO_EPILOG;
1351   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1352 }
1353 
1354 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1355                                              SelectionDAG &DAG) const {
1356   unsigned Reg = StringSwitch<unsigned>(RegName)
1357     .Case("m0", AMDGPU::M0)
1358     .Case("exec", AMDGPU::EXEC)
1359     .Case("exec_lo", AMDGPU::EXEC_LO)
1360     .Case("exec_hi", AMDGPU::EXEC_HI)
1361     .Case("flat_scratch", AMDGPU::FLAT_SCR)
1362     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1363     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1364     .Default(AMDGPU::NoRegister);
1365 
1366   if (Reg == AMDGPU::NoRegister) {
1367     report_fatal_error(Twine("invalid register name \""
1368                              + StringRef(RegName)  + "\"."));
1369 
1370   }
1371 
1372   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1373       Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1374     report_fatal_error(Twine("invalid register \""
1375                              + StringRef(RegName)  + "\" for subtarget."));
1376   }
1377 
1378   switch (Reg) {
1379   case AMDGPU::M0:
1380   case AMDGPU::EXEC_LO:
1381   case AMDGPU::EXEC_HI:
1382   case AMDGPU::FLAT_SCR_LO:
1383   case AMDGPU::FLAT_SCR_HI:
1384     if (VT.getSizeInBits() == 32)
1385       return Reg;
1386     break;
1387   case AMDGPU::EXEC:
1388   case AMDGPU::FLAT_SCR:
1389     if (VT.getSizeInBits() == 64)
1390       return Reg;
1391     break;
1392   default:
1393     llvm_unreachable("missing register type checking");
1394   }
1395 
1396   report_fatal_error(Twine("invalid type for register \""
1397                            + StringRef(RegName) + "\"."));
1398 }
1399 
1400 // If kill is not the last instruction, split the block so kill is always a
1401 // proper terminator.
1402 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
1403                                                     MachineBasicBlock *BB) const {
1404   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1405 
1406   MachineBasicBlock::iterator SplitPoint(&MI);
1407   ++SplitPoint;
1408 
1409   if (SplitPoint == BB->end()) {
1410     // Don't bother with a new block.
1411     MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1412     return BB;
1413   }
1414 
1415   MachineFunction *MF = BB->getParent();
1416   MachineBasicBlock *SplitBB
1417     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
1418 
1419   MF->insert(++MachineFunction::iterator(BB), SplitBB);
1420   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
1421 
1422   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
1423   BB->addSuccessor(SplitBB);
1424 
1425   MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1426   return SplitBB;
1427 }
1428 
1429 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
1430 // wavefront. If the value is uniform and just happens to be in a VGPR, this
1431 // will only do one iteration. In the worst case, this will loop 64 times.
1432 //
1433 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
1434 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
1435   const SIInstrInfo *TII,
1436   MachineRegisterInfo &MRI,
1437   MachineBasicBlock &OrigBB,
1438   MachineBasicBlock &LoopBB,
1439   const DebugLoc &DL,
1440   const MachineOperand &IdxReg,
1441   unsigned InitReg,
1442   unsigned ResultReg,
1443   unsigned PhiReg,
1444   unsigned InitSaveExecReg,
1445   int Offset,
1446   bool UseGPRIdxMode) {
1447   MachineBasicBlock::iterator I = LoopBB.begin();
1448 
1449   unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1450   unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1451   unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1452   unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1453 
1454   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
1455     .addReg(InitReg)
1456     .addMBB(&OrigBB)
1457     .addReg(ResultReg)
1458     .addMBB(&LoopBB);
1459 
1460   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
1461     .addReg(InitSaveExecReg)
1462     .addMBB(&OrigBB)
1463     .addReg(NewExec)
1464     .addMBB(&LoopBB);
1465 
1466   // Read the next variant <- also loop target.
1467   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
1468     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
1469 
1470   // Compare the just read M0 value to all possible Idx values.
1471   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
1472     .addReg(CurrentIdxReg)
1473     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
1474 
1475   if (UseGPRIdxMode) {
1476     unsigned IdxReg;
1477     if (Offset == 0) {
1478       IdxReg = CurrentIdxReg;
1479     } else {
1480       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1481       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
1482         .addReg(CurrentIdxReg, RegState::Kill)
1483         .addImm(Offset);
1484     }
1485 
1486     MachineInstr *SetIdx =
1487       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
1488       .addReg(IdxReg, RegState::Kill);
1489     SetIdx->getOperand(2).setIsUndef();
1490   } else {
1491     // Move index from VCC into M0
1492     if (Offset == 0) {
1493       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1494         .addReg(CurrentIdxReg, RegState::Kill);
1495     } else {
1496       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1497         .addReg(CurrentIdxReg, RegState::Kill)
1498         .addImm(Offset);
1499     }
1500   }
1501 
1502   // Update EXEC, save the original EXEC value to VCC.
1503   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
1504     .addReg(CondReg, RegState::Kill);
1505 
1506   MRI.setSimpleHint(NewExec, CondReg);
1507 
1508   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
1509   MachineInstr *InsertPt =
1510     BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
1511     .addReg(AMDGPU::EXEC)
1512     .addReg(NewExec);
1513 
1514   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
1515   // s_cbranch_scc0?
1516 
1517   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
1518   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
1519     .addMBB(&LoopBB);
1520 
1521   return InsertPt->getIterator();
1522 }
1523 
1524 // This has slightly sub-optimal regalloc when the source vector is killed by
1525 // the read. The register allocator does not understand that the kill is
1526 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
1527 // subregister from it, using 1 more VGPR than necessary. This was saved when
1528 // this was expanded after register allocation.
1529 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
1530                                                   MachineBasicBlock &MBB,
1531                                                   MachineInstr &MI,
1532                                                   unsigned InitResultReg,
1533                                                   unsigned PhiReg,
1534                                                   int Offset,
1535                                                   bool UseGPRIdxMode) {
1536   MachineFunction *MF = MBB.getParent();
1537   MachineRegisterInfo &MRI = MF->getRegInfo();
1538   const DebugLoc &DL = MI.getDebugLoc();
1539   MachineBasicBlock::iterator I(&MI);
1540 
1541   unsigned DstReg = MI.getOperand(0).getReg();
1542   unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1543   unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1544 
1545   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
1546 
1547   // Save the EXEC mask
1548   BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
1549     .addReg(AMDGPU::EXEC);
1550 
1551   // To insert the loop we need to split the block. Move everything after this
1552   // point to a new block, and insert a new empty block between the two.
1553   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
1554   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
1555   MachineFunction::iterator MBBI(MBB);
1556   ++MBBI;
1557 
1558   MF->insert(MBBI, LoopBB);
1559   MF->insert(MBBI, RemainderBB);
1560 
1561   LoopBB->addSuccessor(LoopBB);
1562   LoopBB->addSuccessor(RemainderBB);
1563 
1564   // Move the rest of the block into a new block.
1565   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
1566   RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
1567 
1568   MBB.addSuccessor(LoopBB);
1569 
1570   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1571 
1572   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
1573                                       InitResultReg, DstReg, PhiReg, TmpExec,
1574                                       Offset, UseGPRIdxMode);
1575 
1576   MachineBasicBlock::iterator First = RemainderBB->begin();
1577   BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
1578     .addReg(SaveExec);
1579 
1580   return InsPt;
1581 }
1582 
1583 // Returns subreg index, offset
1584 static std::pair<unsigned, int>
1585 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
1586                             const TargetRegisterClass *SuperRC,
1587                             unsigned VecReg,
1588                             int Offset) {
1589   int NumElts = SuperRC->getSize() / 4;
1590 
1591   // Skip out of bounds offsets, or else we would end up using an undefined
1592   // register.
1593   if (Offset >= NumElts || Offset < 0)
1594     return std::make_pair(AMDGPU::sub0, Offset);
1595 
1596   return std::make_pair(AMDGPU::sub0 + Offset, 0);
1597 }
1598 
1599 // Return true if the index is an SGPR and was set.
1600 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
1601                                  MachineRegisterInfo &MRI,
1602                                  MachineInstr &MI,
1603                                  int Offset,
1604                                  bool UseGPRIdxMode,
1605                                  bool IsIndirectSrc) {
1606   MachineBasicBlock *MBB = MI.getParent();
1607   const DebugLoc &DL = MI.getDebugLoc();
1608   MachineBasicBlock::iterator I(&MI);
1609 
1610   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1611   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
1612 
1613   assert(Idx->getReg() != AMDGPU::NoRegister);
1614 
1615   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
1616     return false;
1617 
1618   if (UseGPRIdxMode) {
1619     unsigned IdxMode = IsIndirectSrc ?
1620       VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
1621     if (Offset == 0) {
1622       MachineInstr *SetOn =
1623           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1624               .add(*Idx)
1625               .addImm(IdxMode);
1626 
1627       SetOn->getOperand(3).setIsUndef();
1628     } else {
1629       unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1630       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
1631           .add(*Idx)
1632           .addImm(Offset);
1633       MachineInstr *SetOn =
1634         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1635         .addReg(Tmp, RegState::Kill)
1636         .addImm(IdxMode);
1637 
1638       SetOn->getOperand(3).setIsUndef();
1639     }
1640 
1641     return true;
1642   }
1643 
1644   if (Offset == 0) {
1645     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1646       .add(*Idx);
1647   } else {
1648     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1649       .add(*Idx)
1650       .addImm(Offset);
1651   }
1652 
1653   return true;
1654 }
1655 
1656 // Control flow needs to be inserted if indexing with a VGPR.
1657 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
1658                                           MachineBasicBlock &MBB,
1659                                           const SISubtarget &ST) {
1660   const SIInstrInfo *TII = ST.getInstrInfo();
1661   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1662   MachineFunction *MF = MBB.getParent();
1663   MachineRegisterInfo &MRI = MF->getRegInfo();
1664 
1665   unsigned Dst = MI.getOperand(0).getReg();
1666   unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
1667   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1668 
1669   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
1670 
1671   unsigned SubReg;
1672   std::tie(SubReg, Offset)
1673     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
1674 
1675   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1676 
1677   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
1678     MachineBasicBlock::iterator I(&MI);
1679     const DebugLoc &DL = MI.getDebugLoc();
1680 
1681     if (UseGPRIdxMode) {
1682       // TODO: Look at the uses to avoid the copy. This may require rescheduling
1683       // to avoid interfering with other uses, so probably requires a new
1684       // optimization pass.
1685       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1686         .addReg(SrcReg, RegState::Undef, SubReg)
1687         .addReg(SrcReg, RegState::Implicit)
1688         .addReg(AMDGPU::M0, RegState::Implicit);
1689       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1690     } else {
1691       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1692         .addReg(SrcReg, RegState::Undef, SubReg)
1693         .addReg(SrcReg, RegState::Implicit);
1694     }
1695 
1696     MI.eraseFromParent();
1697 
1698     return &MBB;
1699   }
1700 
1701   const DebugLoc &DL = MI.getDebugLoc();
1702   MachineBasicBlock::iterator I(&MI);
1703 
1704   unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1705   unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1706 
1707   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
1708 
1709   if (UseGPRIdxMode) {
1710     MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1711       .addImm(0) // Reset inside loop.
1712       .addImm(VGPRIndexMode::SRC0_ENABLE);
1713     SetOn->getOperand(3).setIsUndef();
1714 
1715     // Disable again after the loop.
1716     BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1717   }
1718 
1719   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
1720   MachineBasicBlock *LoopBB = InsPt->getParent();
1721 
1722   if (UseGPRIdxMode) {
1723     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1724       .addReg(SrcReg, RegState::Undef, SubReg)
1725       .addReg(SrcReg, RegState::Implicit)
1726       .addReg(AMDGPU::M0, RegState::Implicit);
1727   } else {
1728     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1729       .addReg(SrcReg, RegState::Undef, SubReg)
1730       .addReg(SrcReg, RegState::Implicit);
1731   }
1732 
1733   MI.eraseFromParent();
1734 
1735   return LoopBB;
1736 }
1737 
1738 static unsigned getMOVRELDPseudo(const TargetRegisterClass *VecRC) {
1739   switch (VecRC->getSize()) {
1740   case 4:
1741     return AMDGPU::V_MOVRELD_B32_V1;
1742   case 8:
1743     return AMDGPU::V_MOVRELD_B32_V2;
1744   case 16:
1745     return AMDGPU::V_MOVRELD_B32_V4;
1746   case 32:
1747     return AMDGPU::V_MOVRELD_B32_V8;
1748   case 64:
1749     return AMDGPU::V_MOVRELD_B32_V16;
1750   default:
1751     llvm_unreachable("unsupported size for MOVRELD pseudos");
1752   }
1753 }
1754 
1755 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
1756                                           MachineBasicBlock &MBB,
1757                                           const SISubtarget &ST) {
1758   const SIInstrInfo *TII = ST.getInstrInfo();
1759   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1760   MachineFunction *MF = MBB.getParent();
1761   MachineRegisterInfo &MRI = MF->getRegInfo();
1762 
1763   unsigned Dst = MI.getOperand(0).getReg();
1764   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
1765   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1766   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
1767   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1768   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
1769 
1770   // This can be an immediate, but will be folded later.
1771   assert(Val->getReg());
1772 
1773   unsigned SubReg;
1774   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
1775                                                          SrcVec->getReg(),
1776                                                          Offset);
1777   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1778 
1779   if (Idx->getReg() == AMDGPU::NoRegister) {
1780     MachineBasicBlock::iterator I(&MI);
1781     const DebugLoc &DL = MI.getDebugLoc();
1782 
1783     assert(Offset == 0);
1784 
1785     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
1786         .add(*SrcVec)
1787         .add(*Val)
1788         .addImm(SubReg);
1789 
1790     MI.eraseFromParent();
1791     return &MBB;
1792   }
1793 
1794   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
1795     MachineBasicBlock::iterator I(&MI);
1796     const DebugLoc &DL = MI.getDebugLoc();
1797 
1798     if (UseGPRIdxMode) {
1799       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1800           .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
1801           .add(*Val)
1802           .addReg(Dst, RegState::ImplicitDefine)
1803           .addReg(SrcVec->getReg(), RegState::Implicit)
1804           .addReg(AMDGPU::M0, RegState::Implicit);
1805 
1806       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1807     } else {
1808       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1809 
1810       BuildMI(MBB, I, DL, MovRelDesc)
1811           .addReg(Dst, RegState::Define)
1812           .addReg(SrcVec->getReg())
1813           .add(*Val)
1814           .addImm(SubReg - AMDGPU::sub0);
1815     }
1816 
1817     MI.eraseFromParent();
1818     return &MBB;
1819   }
1820 
1821   if (Val->isReg())
1822     MRI.clearKillFlags(Val->getReg());
1823 
1824   const DebugLoc &DL = MI.getDebugLoc();
1825 
1826   if (UseGPRIdxMode) {
1827     MachineBasicBlock::iterator I(&MI);
1828 
1829     MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1830       .addImm(0) // Reset inside loop.
1831       .addImm(VGPRIndexMode::DST_ENABLE);
1832     SetOn->getOperand(3).setIsUndef();
1833 
1834     // Disable again after the loop.
1835     BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1836   }
1837 
1838   unsigned PhiReg = MRI.createVirtualRegister(VecRC);
1839 
1840   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
1841                               Offset, UseGPRIdxMode);
1842   MachineBasicBlock *LoopBB = InsPt->getParent();
1843 
1844   if (UseGPRIdxMode) {
1845     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1846         .addReg(PhiReg, RegState::Undef, SubReg) // vdst
1847         .add(*Val)                               // src0
1848         .addReg(Dst, RegState::ImplicitDefine)
1849         .addReg(PhiReg, RegState::Implicit)
1850         .addReg(AMDGPU::M0, RegState::Implicit);
1851   } else {
1852     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1853 
1854     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
1855         .addReg(Dst, RegState::Define)
1856         .addReg(PhiReg)
1857         .add(*Val)
1858         .addImm(SubReg - AMDGPU::sub0);
1859   }
1860 
1861   MI.eraseFromParent();
1862 
1863   return LoopBB;
1864 }
1865 
1866 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
1867   MachineInstr &MI, MachineBasicBlock *BB) const {
1868 
1869   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1870   MachineFunction *MF = BB->getParent();
1871   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1872 
1873   if (TII->isMIMG(MI)) {
1874       if (!MI.memoperands_empty())
1875         return BB;
1876     // Add a memoperand for mimg instructions so that they aren't assumed to
1877     // be ordered memory instuctions.
1878 
1879     MachinePointerInfo PtrInfo(MFI->getImagePSV());
1880     MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable;
1881     if (MI.mayStore())
1882       Flags |= MachineMemOperand::MOStore;
1883 
1884     if (MI.mayLoad())
1885       Flags |= MachineMemOperand::MOLoad;
1886 
1887     auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0);
1888     MI.addMemOperand(*MF, MMO);
1889     return BB;
1890   }
1891 
1892   switch (MI.getOpcode()) {
1893   case AMDGPU::S_TRAP_PSEUDO: {
1894     const DebugLoc &DL = MI.getDebugLoc();
1895     const int TrapType = MI.getOperand(0).getImm();
1896 
1897     if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
1898         Subtarget->isTrapHandlerEnabled()) {
1899 
1900       MachineFunction *MF = BB->getParent();
1901       SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1902       unsigned UserSGPR = Info->getQueuePtrUserSGPR();
1903       assert(UserSGPR != AMDGPU::NoRegister);
1904 
1905       if (!BB->isLiveIn(UserSGPR))
1906         BB->addLiveIn(UserSGPR);
1907 
1908       BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), AMDGPU::SGPR0_SGPR1)
1909         .addReg(UserSGPR);
1910       BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_TRAP))
1911         .addImm(TrapType)
1912         .addReg(AMDGPU::SGPR0_SGPR1, RegState::Implicit);
1913     } else {
1914       switch (TrapType) {
1915       case SISubtarget::TrapIDLLVMTrap:
1916         BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_ENDPGM));
1917         break;
1918       case SISubtarget::TrapIDLLVMDebugTrap: {
1919         DiagnosticInfoUnsupported NoTrap(*MF->getFunction(),
1920                                          "debugtrap handler not supported",
1921                                          DL,
1922                                          DS_Warning);
1923         LLVMContext &C = MF->getFunction()->getContext();
1924         C.diagnose(NoTrap);
1925         BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_NOP))
1926           .addImm(0);
1927         break;
1928       }
1929       default:
1930         llvm_unreachable("unsupported trap handler type!");
1931       }
1932     }
1933 
1934     MI.eraseFromParent();
1935     return BB;
1936   }
1937   case AMDGPU::SI_INIT_M0:
1938     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
1939             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1940         .add(MI.getOperand(0));
1941     MI.eraseFromParent();
1942     return BB;
1943 
1944   case AMDGPU::GET_GROUPSTATICSIZE: {
1945     DebugLoc DL = MI.getDebugLoc();
1946     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
1947         .add(MI.getOperand(0))
1948         .addImm(MFI->getLDSSize());
1949     MI.eraseFromParent();
1950     return BB;
1951   }
1952   case AMDGPU::SI_INDIRECT_SRC_V1:
1953   case AMDGPU::SI_INDIRECT_SRC_V2:
1954   case AMDGPU::SI_INDIRECT_SRC_V4:
1955   case AMDGPU::SI_INDIRECT_SRC_V8:
1956   case AMDGPU::SI_INDIRECT_SRC_V16:
1957     return emitIndirectSrc(MI, *BB, *getSubtarget());
1958   case AMDGPU::SI_INDIRECT_DST_V1:
1959   case AMDGPU::SI_INDIRECT_DST_V2:
1960   case AMDGPU::SI_INDIRECT_DST_V4:
1961   case AMDGPU::SI_INDIRECT_DST_V8:
1962   case AMDGPU::SI_INDIRECT_DST_V16:
1963     return emitIndirectDst(MI, *BB, *getSubtarget());
1964   case AMDGPU::SI_KILL:
1965     return splitKillBlock(MI, BB);
1966   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
1967     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
1968 
1969     unsigned Dst = MI.getOperand(0).getReg();
1970     unsigned Src0 = MI.getOperand(1).getReg();
1971     unsigned Src1 = MI.getOperand(2).getReg();
1972     const DebugLoc &DL = MI.getDebugLoc();
1973     unsigned SrcCond = MI.getOperand(3).getReg();
1974 
1975     unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1976     unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1977 
1978     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
1979       .addReg(Src0, 0, AMDGPU::sub0)
1980       .addReg(Src1, 0, AMDGPU::sub0)
1981       .addReg(SrcCond);
1982     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
1983       .addReg(Src0, 0, AMDGPU::sub1)
1984       .addReg(Src1, 0, AMDGPU::sub1)
1985       .addReg(SrcCond);
1986 
1987     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
1988       .addReg(DstLo)
1989       .addImm(AMDGPU::sub0)
1990       .addReg(DstHi)
1991       .addImm(AMDGPU::sub1);
1992     MI.eraseFromParent();
1993     return BB;
1994   }
1995   case AMDGPU::SI_BR_UNDEF: {
1996     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1997     const DebugLoc &DL = MI.getDebugLoc();
1998     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
1999                            .add(MI.getOperand(0));
2000     Br->getOperand(1).setIsUndef(true); // read undef SCC
2001     MI.eraseFromParent();
2002     return BB;
2003   }
2004   default:
2005     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
2006   }
2007 }
2008 
2009 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
2010   // This currently forces unfolding various combinations of fsub into fma with
2011   // free fneg'd operands. As long as we have fast FMA (controlled by
2012   // isFMAFasterThanFMulAndFAdd), we should perform these.
2013 
2014   // When fma is quarter rate, for f64 where add / sub are at best half rate,
2015   // most of these combines appear to be cycle neutral but save on instruction
2016   // count / code size.
2017   return true;
2018 }
2019 
2020 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
2021                                          EVT VT) const {
2022   if (!VT.isVector()) {
2023     return MVT::i1;
2024   }
2025   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
2026 }
2027 
2028 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
2029   // TODO: Should i16 be used always if legal? For now it would force VALU
2030   // shifts.
2031   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
2032 }
2033 
2034 // Answering this is somewhat tricky and depends on the specific device which
2035 // have different rates for fma or all f64 operations.
2036 //
2037 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
2038 // regardless of which device (although the number of cycles differs between
2039 // devices), so it is always profitable for f64.
2040 //
2041 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
2042 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
2043 // which we can always do even without fused FP ops since it returns the same
2044 // result as the separate operations and since it is always full
2045 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
2046 // however does not support denormals, so we do report fma as faster if we have
2047 // a fast fma device and require denormals.
2048 //
2049 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
2050   VT = VT.getScalarType();
2051 
2052   switch (VT.getSimpleVT().SimpleTy) {
2053   case MVT::f32:
2054     // This is as fast on some subtargets. However, we always have full rate f32
2055     // mad available which returns the same result as the separate operations
2056     // which we should prefer over fma. We can't use this if we want to support
2057     // denormals, so only report this in these cases.
2058     return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
2059   case MVT::f64:
2060     return true;
2061   case MVT::f16:
2062     return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
2063   default:
2064     break;
2065   }
2066 
2067   return false;
2068 }
2069 
2070 //===----------------------------------------------------------------------===//
2071 // Custom DAG Lowering Operations
2072 //===----------------------------------------------------------------------===//
2073 
2074 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2075   switch (Op.getOpcode()) {
2076   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2077   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2078   case ISD::LOAD: {
2079     SDValue Result = LowerLOAD(Op, DAG);
2080     assert((!Result.getNode() ||
2081             Result.getNode()->getNumValues() == 2) &&
2082            "Load should return a value and a chain");
2083     return Result;
2084   }
2085 
2086   case ISD::FSIN:
2087   case ISD::FCOS:
2088     return LowerTrig(Op, DAG);
2089   case ISD::SELECT: return LowerSELECT(Op, DAG);
2090   case ISD::FDIV: return LowerFDIV(Op, DAG);
2091   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
2092   case ISD::STORE: return LowerSTORE(Op, DAG);
2093   case ISD::GlobalAddress: {
2094     MachineFunction &MF = DAG.getMachineFunction();
2095     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2096     return LowerGlobalAddress(MFI, Op, DAG);
2097   }
2098   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2099   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2100   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
2101   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
2102   case ISD::INSERT_VECTOR_ELT:
2103     return lowerINSERT_VECTOR_ELT(Op, DAG);
2104   case ISD::EXTRACT_VECTOR_ELT:
2105     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2106   case ISD::FP_ROUND:
2107     return lowerFP_ROUND(Op, DAG);
2108   }
2109   return SDValue();
2110 }
2111 
2112 void SITargetLowering::ReplaceNodeResults(SDNode *N,
2113                                           SmallVectorImpl<SDValue> &Results,
2114                                           SelectionDAG &DAG) const {
2115   switch (N->getOpcode()) {
2116   case ISD::INSERT_VECTOR_ELT: {
2117     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
2118       Results.push_back(Res);
2119     return;
2120   }
2121   case ISD::EXTRACT_VECTOR_ELT: {
2122     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
2123       Results.push_back(Res);
2124     return;
2125   }
2126   case ISD::INTRINSIC_WO_CHAIN: {
2127     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2128     switch (IID) {
2129     case Intrinsic::amdgcn_cvt_pkrtz: {
2130       SDValue Src0 = N->getOperand(1);
2131       SDValue Src1 = N->getOperand(2);
2132       SDLoc SL(N);
2133       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
2134                                 Src0, Src1);
2135 
2136       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
2137       return;
2138     }
2139     default:
2140       break;
2141     }
2142   }
2143   default:
2144     break;
2145   }
2146 }
2147 
2148 /// \brief Helper function for LowerBRCOND
2149 static SDNode *findUser(SDValue Value, unsigned Opcode) {
2150 
2151   SDNode *Parent = Value.getNode();
2152   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
2153        I != E; ++I) {
2154 
2155     if (I.getUse().get() != Value)
2156       continue;
2157 
2158     if (I->getOpcode() == Opcode)
2159       return *I;
2160   }
2161   return nullptr;
2162 }
2163 
2164 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
2165   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
2166     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
2167     case Intrinsic::amdgcn_if:
2168       return AMDGPUISD::IF;
2169     case Intrinsic::amdgcn_else:
2170       return AMDGPUISD::ELSE;
2171     case Intrinsic::amdgcn_loop:
2172       return AMDGPUISD::LOOP;
2173     case Intrinsic::amdgcn_end_cf:
2174       llvm_unreachable("should not occur");
2175     default:
2176       return 0;
2177     }
2178   }
2179 
2180   // break, if_break, else_break are all only used as inputs to loop, not
2181   // directly as branch conditions.
2182   return 0;
2183 }
2184 
2185 void SITargetLowering::createDebuggerPrologueStackObjects(
2186     MachineFunction &MF) const {
2187   // Create stack objects that are used for emitting debugger prologue.
2188   //
2189   // Debugger prologue writes work group IDs and work item IDs to scratch memory
2190   // at fixed location in the following format:
2191   //   offset 0:  work group ID x
2192   //   offset 4:  work group ID y
2193   //   offset 8:  work group ID z
2194   //   offset 16: work item ID x
2195   //   offset 20: work item ID y
2196   //   offset 24: work item ID z
2197   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2198   int ObjectIdx = 0;
2199 
2200   // For each dimension:
2201   for (unsigned i = 0; i < 3; ++i) {
2202     // Create fixed stack object for work group ID.
2203     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
2204     Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
2205     // Create fixed stack object for work item ID.
2206     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
2207     Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
2208   }
2209 }
2210 
2211 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
2212   const Triple &TT = getTargetMachine().getTargetTriple();
2213   return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS &&
2214          AMDGPU::shouldEmitConstantsToTextSection(TT);
2215 }
2216 
2217 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
2218   return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2219               GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2220          !shouldEmitFixup(GV) &&
2221          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2222 }
2223 
2224 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
2225   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
2226 }
2227 
2228 /// This transforms the control flow intrinsics to get the branch destination as
2229 /// last parameter, also switches branch target with BR if the need arise
2230 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
2231                                       SelectionDAG &DAG) const {
2232   SDLoc DL(BRCOND);
2233 
2234   SDNode *Intr = BRCOND.getOperand(1).getNode();
2235   SDValue Target = BRCOND.getOperand(2);
2236   SDNode *BR = nullptr;
2237   SDNode *SetCC = nullptr;
2238 
2239   if (Intr->getOpcode() == ISD::SETCC) {
2240     // As long as we negate the condition everything is fine
2241     SetCC = Intr;
2242     Intr = SetCC->getOperand(0).getNode();
2243 
2244   } else {
2245     // Get the target from BR if we don't negate the condition
2246     BR = findUser(BRCOND, ISD::BR);
2247     Target = BR->getOperand(1);
2248   }
2249 
2250   // FIXME: This changes the types of the intrinsics instead of introducing new
2251   // nodes with the correct types.
2252   // e.g. llvm.amdgcn.loop
2253 
2254   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
2255   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
2256 
2257   unsigned CFNode = isCFIntrinsic(Intr);
2258   if (CFNode == 0) {
2259     // This is a uniform branch so we don't need to legalize.
2260     return BRCOND;
2261   }
2262 
2263   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
2264                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
2265 
2266   assert(!SetCC ||
2267         (SetCC->getConstantOperandVal(1) == 1 &&
2268          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
2269                                                              ISD::SETNE));
2270 
2271   // operands of the new intrinsic call
2272   SmallVector<SDValue, 4> Ops;
2273   if (HaveChain)
2274     Ops.push_back(BRCOND.getOperand(0));
2275 
2276   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
2277   Ops.push_back(Target);
2278 
2279   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
2280 
2281   // build the new intrinsic call
2282   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
2283 
2284   if (!HaveChain) {
2285     SDValue Ops[] =  {
2286       SDValue(Result, 0),
2287       BRCOND.getOperand(0)
2288     };
2289 
2290     Result = DAG.getMergeValues(Ops, DL).getNode();
2291   }
2292 
2293   if (BR) {
2294     // Give the branch instruction our target
2295     SDValue Ops[] = {
2296       BR->getOperand(0),
2297       BRCOND.getOperand(2)
2298     };
2299     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2300     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2301     BR = NewBR.getNode();
2302   }
2303 
2304   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2305 
2306   // Copy the intrinsic results to registers
2307   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2308     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2309     if (!CopyToReg)
2310       continue;
2311 
2312     Chain = DAG.getCopyToReg(
2313       Chain, DL,
2314       CopyToReg->getOperand(1),
2315       SDValue(Result, i - 1),
2316       SDValue());
2317 
2318     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2319   }
2320 
2321   // Remove the old intrinsic from the chain
2322   DAG.ReplaceAllUsesOfValueWith(
2323     SDValue(Intr, Intr->getNumValues() - 1),
2324     Intr->getOperand(0));
2325 
2326   return Chain;
2327 }
2328 
2329 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2330                                             SDValue Op,
2331                                             const SDLoc &DL,
2332                                             EVT VT) const {
2333   return Op.getValueType().bitsLE(VT) ?
2334       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2335       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2336 }
2337 
2338 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2339   assert(Op.getValueType() == MVT::f16 &&
2340          "Do not know how to custom lower FP_ROUND for non-f16 type");
2341 
2342   SDValue Src = Op.getOperand(0);
2343   EVT SrcVT = Src.getValueType();
2344   if (SrcVT != MVT::f64)
2345     return Op;
2346 
2347   SDLoc DL(Op);
2348 
2349   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2350   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2351   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);;
2352 }
2353 
2354 SDValue SITargetLowering::getSegmentAperture(unsigned AS,
2355                                              SelectionDAG &DAG) const {
2356 
2357   if (Subtarget->hasApertureRegs()) { // Read from Aperture Registers directly.
2358     unsigned RegNo = (AS == AMDGPUASI.LOCAL_ADDRESS) ? AMDGPU::SRC_SHARED_BASE :
2359                                                        AMDGPU::SRC_PRIVATE_BASE;
2360     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, RegNo, MVT::i32);
2361   }
2362 
2363   SDLoc SL;
2364   MachineFunction &MF = DAG.getMachineFunction();
2365   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2366   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2367   assert(UserSGPR != AMDGPU::NoRegister);
2368 
2369   SDValue QueuePtr = CreateLiveInRegister(
2370     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2371 
2372   // Offset into amd_queue_t for group_segment_aperture_base_hi /
2373   // private_segment_aperture_base_hi.
2374   uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
2375 
2376   SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, QueuePtr,
2377                             DAG.getConstant(StructOffset, SL, MVT::i64));
2378 
2379   // TODO: Use custom target PseudoSourceValue.
2380   // TODO: We should use the value from the IR intrinsic call, but it might not
2381   // be available and how do we get it?
2382   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2383                                               AMDGPUASI.CONSTANT_ADDRESS));
2384 
2385   MachinePointerInfo PtrInfo(V, StructOffset);
2386   return DAG.getLoad(MVT::i32, SL, QueuePtr.getValue(1), Ptr, PtrInfo,
2387                      MinAlign(64, StructOffset),
2388                      MachineMemOperand::MODereferenceable |
2389                          MachineMemOperand::MOInvariant);
2390 }
2391 
2392 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2393                                              SelectionDAG &DAG) const {
2394   SDLoc SL(Op);
2395   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2396 
2397   SDValue Src = ASC->getOperand(0);
2398   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2399 
2400   const AMDGPUTargetMachine &TM =
2401     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
2402 
2403   // flat -> local/private
2404   if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2405     unsigned DestAS = ASC->getDestAddressSpace();
2406 
2407     if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
2408         DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
2409       unsigned NullVal = TM.getNullPointerValue(DestAS);
2410       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2411       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2412       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2413 
2414       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2415                          NonNull, Ptr, SegmentNullPtr);
2416     }
2417   }
2418 
2419   // local/private -> flat
2420   if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2421     unsigned SrcAS = ASC->getSrcAddressSpace();
2422 
2423     if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
2424         SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
2425       unsigned NullVal = TM.getNullPointerValue(SrcAS);
2426       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2427 
2428       SDValue NonNull
2429         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2430 
2431       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), DAG);
2432       SDValue CvtPtr
2433         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2434 
2435       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2436                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2437                          FlatNullPtr);
2438     }
2439   }
2440 
2441   // global <-> flat are no-ops and never emitted.
2442 
2443   const MachineFunction &MF = DAG.getMachineFunction();
2444   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2445     *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2446   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2447 
2448   return DAG.getUNDEF(ASC->getValueType(0));
2449 }
2450 
2451 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2452                                                  SelectionDAG &DAG) const {
2453   SDValue Idx = Op.getOperand(2);
2454   if (isa<ConstantSDNode>(Idx))
2455     return SDValue();
2456 
2457   // Avoid stack access for dynamic indexing.
2458   SDLoc SL(Op);
2459   SDValue Vec = Op.getOperand(0);
2460   SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
2461 
2462   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
2463   SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
2464 
2465   // Convert vector index to bit-index.
2466   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
2467                                   DAG.getConstant(16, SL, MVT::i32));
2468 
2469   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2470 
2471   SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
2472                             DAG.getConstant(0xffff, SL, MVT::i32),
2473                             ScaledIdx);
2474 
2475   SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
2476   SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
2477                             DAG.getNOT(SL, BFM, MVT::i32), BCVec);
2478 
2479   SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
2480   return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
2481 }
2482 
2483 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2484                                                   SelectionDAG &DAG) const {
2485   SDLoc SL(Op);
2486 
2487   EVT ResultVT = Op.getValueType();
2488   SDValue Vec = Op.getOperand(0);
2489   SDValue Idx = Op.getOperand(1);
2490 
2491   if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
2492     SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2493 
2494     if (CIdx->getZExtValue() == 1) {
2495       Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
2496                            DAG.getConstant(16, SL, MVT::i32));
2497     } else {
2498       assert(CIdx->getZExtValue() == 0);
2499     }
2500 
2501     if (ResultVT.bitsLT(MVT::i32))
2502       Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2503     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2504   }
2505 
2506   SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
2507 
2508   // Convert vector index to bit-index.
2509   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
2510 
2511   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2512   SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
2513 
2514   SDValue Result = Elt;
2515   if (ResultVT.bitsLT(MVT::i32))
2516     Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2517 
2518   return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2519 }
2520 
2521 bool
2522 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2523   // We can fold offsets for anything that doesn't require a GOT relocation.
2524   return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2525               GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2526          !shouldEmitGOTReloc(GA->getGlobal());
2527 }
2528 
2529 static SDValue
2530 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2531                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
2532                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
2533   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2534   // lowered to the following code sequence:
2535   //
2536   // For constant address space:
2537   //   s_getpc_b64 s[0:1]
2538   //   s_add_u32 s0, s0, $symbol
2539   //   s_addc_u32 s1, s1, 0
2540   //
2541   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
2542   //   a fixup or relocation is emitted to replace $symbol with a literal
2543   //   constant, which is a pc-relative offset from the encoding of the $symbol
2544   //   operand to the global variable.
2545   //
2546   // For global address space:
2547   //   s_getpc_b64 s[0:1]
2548   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2549   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2550   //
2551   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
2552   //   fixups or relocations are emitted to replace $symbol@*@lo and
2553   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2554   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
2555   //   operand to the global variable.
2556   //
2557   // What we want here is an offset from the value returned by s_getpc
2558   // (which is the address of the s_add_u32 instruction) to the global
2559   // variable, but since the encoding of $symbol starts 4 bytes after the start
2560   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2561   // small. This requires us to add 4 to the global variable offset in order to
2562   // compute the correct address.
2563   SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2564                                              GAFlags);
2565   SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2566                                              GAFlags == SIInstrInfo::MO_NONE ?
2567                                              GAFlags : GAFlags + 1);
2568   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2569 }
2570 
2571 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2572                                              SDValue Op,
2573                                              SelectionDAG &DAG) const {
2574   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2575 
2576   if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
2577       GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS)
2578     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2579 
2580   SDLoc DL(GSD);
2581   const GlobalValue *GV = GSD->getGlobal();
2582   EVT PtrVT = Op.getValueType();
2583 
2584   if (shouldEmitFixup(GV))
2585     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2586   else if (shouldEmitPCReloc(GV))
2587     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2588                                    SIInstrInfo::MO_REL32);
2589 
2590   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2591                                             SIInstrInfo::MO_GOTPCREL32);
2592 
2593   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2594   PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
2595   const DataLayout &DataLayout = DAG.getDataLayout();
2596   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2597   // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2598   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2599 
2600   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2601                      MachineMemOperand::MODereferenceable |
2602                          MachineMemOperand::MOInvariant);
2603 }
2604 
2605 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2606                                    const SDLoc &DL, SDValue V) const {
2607   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2608   // the destination register.
2609   //
2610   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2611   // so we will end up with redundant moves to m0.
2612   //
2613   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2614 
2615   // A Null SDValue creates a glue result.
2616   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2617                                   V, Chain);
2618   return SDValue(M0, 0);
2619 }
2620 
2621 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2622                                                  SDValue Op,
2623                                                  MVT VT,
2624                                                  unsigned Offset) const {
2625   SDLoc SL(Op);
2626   SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
2627                                  DAG.getEntryNode(), Offset, false);
2628   // The local size values will have the hi 16-bits as zero.
2629   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2630                      DAG.getValueType(VT));
2631 }
2632 
2633 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2634                                         EVT VT) {
2635   DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2636                                       "non-hsa intrinsic with hsa target",
2637                                       DL.getDebugLoc());
2638   DAG.getContext()->diagnose(BadIntrin);
2639   return DAG.getUNDEF(VT);
2640 }
2641 
2642 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2643                                          EVT VT) {
2644   DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2645                                       "intrinsic not supported on subtarget",
2646                                       DL.getDebugLoc());
2647   DAG.getContext()->diagnose(BadIntrin);
2648   return DAG.getUNDEF(VT);
2649 }
2650 
2651 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2652                                                   SelectionDAG &DAG) const {
2653   MachineFunction &MF = DAG.getMachineFunction();
2654   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2655   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2656 
2657   EVT VT = Op.getValueType();
2658   SDLoc DL(Op);
2659   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2660 
2661   // TODO: Should this propagate fast-math-flags?
2662 
2663   switch (IntrinsicID) {
2664   case Intrinsic::amdgcn_implicit_buffer_ptr: {
2665     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
2666     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2667   }
2668   case Intrinsic::amdgcn_dispatch_ptr:
2669   case Intrinsic::amdgcn_queue_ptr: {
2670     if (!Subtarget->isAmdCodeObjectV2(MF)) {
2671       DiagnosticInfoUnsupported BadIntrin(
2672           *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
2673           DL.getDebugLoc());
2674       DAG.getContext()->diagnose(BadIntrin);
2675       return DAG.getUNDEF(VT);
2676     }
2677 
2678     auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
2679       SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
2680     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
2681                                 TRI->getPreloadedValue(MF, Reg), VT);
2682   }
2683   case Intrinsic::amdgcn_implicitarg_ptr: {
2684     unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
2685     return LowerParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
2686   }
2687   case Intrinsic::amdgcn_kernarg_segment_ptr: {
2688     unsigned Reg
2689       = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
2690     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2691   }
2692   case Intrinsic::amdgcn_dispatch_id: {
2693     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
2694     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2695   }
2696   case Intrinsic::amdgcn_rcp:
2697     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
2698   case Intrinsic::amdgcn_rsq:
2699     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2700   case Intrinsic::amdgcn_rsq_legacy:
2701     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2702       return emitRemovedIntrinsicError(DAG, DL, VT);
2703 
2704     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
2705   case Intrinsic::amdgcn_rcp_legacy:
2706     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2707       return emitRemovedIntrinsicError(DAG, DL, VT);
2708     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
2709   case Intrinsic::amdgcn_rsq_clamp: {
2710     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2711       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
2712 
2713     Type *Type = VT.getTypeForEVT(*DAG.getContext());
2714     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
2715     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
2716 
2717     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2718     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
2719                               DAG.getConstantFP(Max, DL, VT));
2720     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
2721                        DAG.getConstantFP(Min, DL, VT));
2722   }
2723   case Intrinsic::r600_read_ngroups_x:
2724     if (Subtarget->isAmdHsaOS())
2725       return emitNonHSAIntrinsicError(DAG, DL, VT);
2726 
2727     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2728                           SI::KernelInputOffsets::NGROUPS_X, false);
2729   case Intrinsic::r600_read_ngroups_y:
2730     if (Subtarget->isAmdHsaOS())
2731       return emitNonHSAIntrinsicError(DAG, DL, VT);
2732 
2733     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2734                           SI::KernelInputOffsets::NGROUPS_Y, false);
2735   case Intrinsic::r600_read_ngroups_z:
2736     if (Subtarget->isAmdHsaOS())
2737       return emitNonHSAIntrinsicError(DAG, DL, VT);
2738 
2739     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2740                           SI::KernelInputOffsets::NGROUPS_Z, false);
2741   case Intrinsic::r600_read_global_size_x:
2742     if (Subtarget->isAmdHsaOS())
2743       return emitNonHSAIntrinsicError(DAG, DL, VT);
2744 
2745     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2746                           SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
2747   case Intrinsic::r600_read_global_size_y:
2748     if (Subtarget->isAmdHsaOS())
2749       return emitNonHSAIntrinsicError(DAG, DL, VT);
2750 
2751     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2752                           SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
2753   case Intrinsic::r600_read_global_size_z:
2754     if (Subtarget->isAmdHsaOS())
2755       return emitNonHSAIntrinsicError(DAG, DL, VT);
2756 
2757     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2758                           SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
2759   case Intrinsic::r600_read_local_size_x:
2760     if (Subtarget->isAmdHsaOS())
2761       return emitNonHSAIntrinsicError(DAG, DL, VT);
2762 
2763     return lowerImplicitZextParam(DAG, Op, MVT::i16,
2764                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
2765   case Intrinsic::r600_read_local_size_y:
2766     if (Subtarget->isAmdHsaOS())
2767       return emitNonHSAIntrinsicError(DAG, DL, VT);
2768 
2769     return lowerImplicitZextParam(DAG, Op, MVT::i16,
2770                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
2771   case Intrinsic::r600_read_local_size_z:
2772     if (Subtarget->isAmdHsaOS())
2773       return emitNonHSAIntrinsicError(DAG, DL, VT);
2774 
2775     return lowerImplicitZextParam(DAG, Op, MVT::i16,
2776                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
2777   case Intrinsic::amdgcn_workgroup_id_x:
2778   case Intrinsic::r600_read_tgid_x:
2779     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2780       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
2781   case Intrinsic::amdgcn_workgroup_id_y:
2782   case Intrinsic::r600_read_tgid_y:
2783     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2784       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
2785   case Intrinsic::amdgcn_workgroup_id_z:
2786   case Intrinsic::r600_read_tgid_z:
2787     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2788       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
2789   case Intrinsic::amdgcn_workitem_id_x:
2790   case Intrinsic::r600_read_tidig_x:
2791     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2792       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
2793   case Intrinsic::amdgcn_workitem_id_y:
2794   case Intrinsic::r600_read_tidig_y:
2795     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2796       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
2797   case Intrinsic::amdgcn_workitem_id_z:
2798   case Intrinsic::r600_read_tidig_z:
2799     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2800       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
2801   case AMDGPUIntrinsic::SI_load_const: {
2802     SDValue Ops[] = {
2803       Op.getOperand(1),
2804       Op.getOperand(2)
2805     };
2806 
2807     MachineMemOperand *MMO = MF.getMachineMemOperand(
2808         MachinePointerInfo(),
2809         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
2810             MachineMemOperand::MOInvariant,
2811         VT.getStoreSize(), 4);
2812     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
2813                                    Op->getVTList(), Ops, VT, MMO);
2814   }
2815   case Intrinsic::amdgcn_fdiv_fast:
2816     return lowerFDIV_FAST(Op, DAG);
2817   case Intrinsic::amdgcn_interp_mov: {
2818     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2819     SDValue Glue = M0.getValue(1);
2820     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
2821                        Op.getOperand(2), Op.getOperand(3), Glue);
2822   }
2823   case Intrinsic::amdgcn_interp_p1: {
2824     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2825     SDValue Glue = M0.getValue(1);
2826     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
2827                        Op.getOperand(2), Op.getOperand(3), Glue);
2828   }
2829   case Intrinsic::amdgcn_interp_p2: {
2830     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
2831     SDValue Glue = SDValue(M0.getNode(), 1);
2832     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
2833                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
2834                        Glue);
2835   }
2836   case Intrinsic::amdgcn_sin:
2837     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
2838 
2839   case Intrinsic::amdgcn_cos:
2840     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
2841 
2842   case Intrinsic::amdgcn_log_clamp: {
2843     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2844       return SDValue();
2845 
2846     DiagnosticInfoUnsupported BadIntrin(
2847       *MF.getFunction(), "intrinsic not supported on subtarget",
2848       DL.getDebugLoc());
2849       DAG.getContext()->diagnose(BadIntrin);
2850       return DAG.getUNDEF(VT);
2851   }
2852   case Intrinsic::amdgcn_ldexp:
2853     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
2854                        Op.getOperand(1), Op.getOperand(2));
2855 
2856   case Intrinsic::amdgcn_fract:
2857     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
2858 
2859   case Intrinsic::amdgcn_class:
2860     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
2861                        Op.getOperand(1), Op.getOperand(2));
2862   case Intrinsic::amdgcn_div_fmas:
2863     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
2864                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
2865                        Op.getOperand(4));
2866 
2867   case Intrinsic::amdgcn_div_fixup:
2868     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
2869                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2870 
2871   case Intrinsic::amdgcn_trig_preop:
2872     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
2873                        Op.getOperand(1), Op.getOperand(2));
2874   case Intrinsic::amdgcn_div_scale: {
2875     // 3rd parameter required to be a constant.
2876     const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2877     if (!Param)
2878       return DAG.getUNDEF(VT);
2879 
2880     // Translate to the operands expected by the machine instruction. The
2881     // first parameter must be the same as the first instruction.
2882     SDValue Numerator = Op.getOperand(1);
2883     SDValue Denominator = Op.getOperand(2);
2884 
2885     // Note this order is opposite of the machine instruction's operations,
2886     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
2887     // intrinsic has the numerator as the first operand to match a normal
2888     // division operation.
2889 
2890     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
2891 
2892     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
2893                        Denominator, Numerator);
2894   }
2895   case Intrinsic::amdgcn_icmp: {
2896     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2897     if (!CD)
2898       return DAG.getUNDEF(VT);
2899 
2900     int CondCode = CD->getSExtValue();
2901     if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
2902         CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
2903       return DAG.getUNDEF(VT);
2904 
2905     ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
2906     ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
2907     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2908                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
2909   }
2910   case Intrinsic::amdgcn_fcmp: {
2911     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2912     if (!CD)
2913       return DAG.getUNDEF(VT);
2914 
2915     int CondCode = CD->getSExtValue();
2916     if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
2917         CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
2918       return DAG.getUNDEF(VT);
2919 
2920     FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
2921     ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
2922     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2923                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
2924   }
2925   case Intrinsic::amdgcn_fmed3:
2926     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
2927                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2928   case Intrinsic::amdgcn_fmul_legacy:
2929     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
2930                        Op.getOperand(1), Op.getOperand(2));
2931   case Intrinsic::amdgcn_sffbh:
2932     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
2933   case Intrinsic::amdgcn_sbfe:
2934     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
2935                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2936   case Intrinsic::amdgcn_ubfe:
2937     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
2938                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2939   case Intrinsic::amdgcn_cvt_pkrtz: {
2940     // FIXME: Stop adding cast if v2f16 legal.
2941     EVT VT = Op.getValueType();
2942     SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
2943                                Op.getOperand(1), Op.getOperand(2));
2944     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
2945   }
2946   default:
2947     return Op;
2948   }
2949 }
2950 
2951 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2952                                                  SelectionDAG &DAG) const {
2953   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2954   SDLoc DL(Op);
2955   switch (IntrID) {
2956   case Intrinsic::amdgcn_atomic_inc:
2957   case Intrinsic::amdgcn_atomic_dec: {
2958     MemSDNode *M = cast<MemSDNode>(Op);
2959     unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
2960       AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
2961     SDValue Ops[] = {
2962       M->getOperand(0), // Chain
2963       M->getOperand(2), // Ptr
2964       M->getOperand(3)  // Value
2965     };
2966 
2967     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
2968                                    M->getMemoryVT(), M->getMemOperand());
2969   }
2970   case Intrinsic::amdgcn_buffer_load:
2971   case Intrinsic::amdgcn_buffer_load_format: {
2972     SDValue Ops[] = {
2973       Op.getOperand(0), // Chain
2974       Op.getOperand(2), // rsrc
2975       Op.getOperand(3), // vindex
2976       Op.getOperand(4), // offset
2977       Op.getOperand(5), // glc
2978       Op.getOperand(6)  // slc
2979     };
2980     MachineFunction &MF = DAG.getMachineFunction();
2981     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2982 
2983     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
2984         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
2985     EVT VT = Op.getValueType();
2986     EVT IntVT = VT.changeTypeToInteger();
2987 
2988     MachineMemOperand *MMO = MF.getMachineMemOperand(
2989       MachinePointerInfo(MFI->getBufferPSV()),
2990       MachineMemOperand::MOLoad,
2991       VT.getStoreSize(), VT.getStoreSize());
2992 
2993     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
2994   }
2995   // Basic sample.
2996   case Intrinsic::amdgcn_image_sample:
2997   case Intrinsic::amdgcn_image_sample_cl:
2998   case Intrinsic::amdgcn_image_sample_d:
2999   case Intrinsic::amdgcn_image_sample_d_cl:
3000   case Intrinsic::amdgcn_image_sample_l:
3001   case Intrinsic::amdgcn_image_sample_b:
3002   case Intrinsic::amdgcn_image_sample_b_cl:
3003   case Intrinsic::amdgcn_image_sample_lz:
3004   case Intrinsic::amdgcn_image_sample_cd:
3005   case Intrinsic::amdgcn_image_sample_cd_cl:
3006 
3007   // Sample with comparison.
3008   case Intrinsic::amdgcn_image_sample_c:
3009   case Intrinsic::amdgcn_image_sample_c_cl:
3010   case Intrinsic::amdgcn_image_sample_c_d:
3011   case Intrinsic::amdgcn_image_sample_c_d_cl:
3012   case Intrinsic::amdgcn_image_sample_c_l:
3013   case Intrinsic::amdgcn_image_sample_c_b:
3014   case Intrinsic::amdgcn_image_sample_c_b_cl:
3015   case Intrinsic::amdgcn_image_sample_c_lz:
3016   case Intrinsic::amdgcn_image_sample_c_cd:
3017   case Intrinsic::amdgcn_image_sample_c_cd_cl:
3018 
3019   // Sample with offsets.
3020   case Intrinsic::amdgcn_image_sample_o:
3021   case Intrinsic::amdgcn_image_sample_cl_o:
3022   case Intrinsic::amdgcn_image_sample_d_o:
3023   case Intrinsic::amdgcn_image_sample_d_cl_o:
3024   case Intrinsic::amdgcn_image_sample_l_o:
3025   case Intrinsic::amdgcn_image_sample_b_o:
3026   case Intrinsic::amdgcn_image_sample_b_cl_o:
3027   case Intrinsic::amdgcn_image_sample_lz_o:
3028   case Intrinsic::amdgcn_image_sample_cd_o:
3029   case Intrinsic::amdgcn_image_sample_cd_cl_o:
3030 
3031   // Sample with comparison and offsets.
3032   case Intrinsic::amdgcn_image_sample_c_o:
3033   case Intrinsic::amdgcn_image_sample_c_cl_o:
3034   case Intrinsic::amdgcn_image_sample_c_d_o:
3035   case Intrinsic::amdgcn_image_sample_c_d_cl_o:
3036   case Intrinsic::amdgcn_image_sample_c_l_o:
3037   case Intrinsic::amdgcn_image_sample_c_b_o:
3038   case Intrinsic::amdgcn_image_sample_c_b_cl_o:
3039   case Intrinsic::amdgcn_image_sample_c_lz_o:
3040   case Intrinsic::amdgcn_image_sample_c_cd_o:
3041   case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
3042 
3043   case Intrinsic::amdgcn_image_getlod: {
3044     // Replace dmask with everything disabled with undef.
3045     const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
3046     if (!DMask || DMask->isNullValue()) {
3047       SDValue Undef = DAG.getUNDEF(Op.getValueType());
3048       return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
3049     }
3050 
3051     return SDValue();
3052   }
3053   default:
3054     return SDValue();
3055   }
3056 }
3057 
3058 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
3059                                               SelectionDAG &DAG) const {
3060   MachineFunction &MF = DAG.getMachineFunction();
3061   SDLoc DL(Op);
3062   SDValue Chain = Op.getOperand(0);
3063   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3064 
3065   switch (IntrinsicID) {
3066   case Intrinsic::amdgcn_exp: {
3067     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3068     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3069     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
3070     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
3071 
3072     const SDValue Ops[] = {
3073       Chain,
3074       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3075       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
3076       Op.getOperand(4), // src0
3077       Op.getOperand(5), // src1
3078       Op.getOperand(6), // src2
3079       Op.getOperand(7), // src3
3080       DAG.getTargetConstant(0, DL, MVT::i1), // compr
3081       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3082     };
3083 
3084     unsigned Opc = Done->isNullValue() ?
3085       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3086     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3087   }
3088   case Intrinsic::amdgcn_exp_compr: {
3089     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3090     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3091     SDValue Src0 = Op.getOperand(4);
3092     SDValue Src1 = Op.getOperand(5);
3093     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
3094     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
3095 
3096     SDValue Undef = DAG.getUNDEF(MVT::f32);
3097     const SDValue Ops[] = {
3098       Chain,
3099       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3100       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
3101       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
3102       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
3103       Undef, // src2
3104       Undef, // src3
3105       DAG.getTargetConstant(1, DL, MVT::i1), // compr
3106       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3107     };
3108 
3109     unsigned Opc = Done->isNullValue() ?
3110       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3111     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3112   }
3113   case Intrinsic::amdgcn_s_sendmsg:
3114   case Intrinsic::amdgcn_s_sendmsghalt: {
3115     unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
3116       AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
3117     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
3118     SDValue Glue = Chain.getValue(1);
3119     return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
3120                        Op.getOperand(2), Glue);
3121   }
3122   case AMDGPUIntrinsic::SI_tbuffer_store: {
3123     SDValue Ops[] = {
3124       Chain,
3125       Op.getOperand(2),
3126       Op.getOperand(3),
3127       Op.getOperand(4),
3128       Op.getOperand(5),
3129       Op.getOperand(6),
3130       Op.getOperand(7),
3131       Op.getOperand(8),
3132       Op.getOperand(9),
3133       Op.getOperand(10),
3134       Op.getOperand(11),
3135       Op.getOperand(12),
3136       Op.getOperand(13),
3137       Op.getOperand(14)
3138     };
3139 
3140     EVT VT = Op.getOperand(3).getValueType();
3141 
3142     MachineMemOperand *MMO = MF.getMachineMemOperand(
3143       MachinePointerInfo(),
3144       MachineMemOperand::MOStore,
3145       VT.getStoreSize(), 4);
3146     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
3147                                    Op->getVTList(), Ops, VT, MMO);
3148   }
3149   case AMDGPUIntrinsic::AMDGPU_kill: {
3150     SDValue Src = Op.getOperand(2);
3151     if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
3152       if (!K->isNegative())
3153         return Chain;
3154 
3155       SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
3156       return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
3157     }
3158 
3159     SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
3160     return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
3161   }
3162   case AMDGPUIntrinsic::SI_export: { // Legacy intrinsic.
3163     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(2));
3164     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(3));
3165     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(4));
3166     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(5));
3167     const ConstantSDNode *Compr = cast<ConstantSDNode>(Op.getOperand(6));
3168 
3169     const SDValue Ops[] = {
3170       Chain,
3171       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8),
3172       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),
3173       Op.getOperand(7),  // src0
3174       Op.getOperand(8),  // src1
3175       Op.getOperand(9),  // src2
3176       Op.getOperand(10), // src3
3177       DAG.getTargetConstant(Compr->getZExtValue(), DL, MVT::i1),
3178       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3179     };
3180 
3181     unsigned Opc = Done->isNullValue() ?
3182       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3183     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3184   }
3185   default:
3186     return Op;
3187   }
3188 }
3189 
3190 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3191   SDLoc DL(Op);
3192   LoadSDNode *Load = cast<LoadSDNode>(Op);
3193   ISD::LoadExtType ExtType = Load->getExtensionType();
3194   EVT MemVT = Load->getMemoryVT();
3195 
3196   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
3197     // FIXME: Copied from PPC
3198     // First, load into 32 bits, then truncate to 1 bit.
3199 
3200     SDValue Chain = Load->getChain();
3201     SDValue BasePtr = Load->getBasePtr();
3202     MachineMemOperand *MMO = Load->getMemOperand();
3203 
3204     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
3205 
3206     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
3207                                    BasePtr, RealMemVT, MMO);
3208 
3209     SDValue Ops[] = {
3210       DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
3211       NewLD.getValue(1)
3212     };
3213 
3214     return DAG.getMergeValues(Ops, DL);
3215   }
3216 
3217   if (!MemVT.isVector())
3218     return SDValue();
3219 
3220   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
3221          "Custom lowering for non-i32 vectors hasn't been implemented.");
3222 
3223   unsigned AS = Load->getAddressSpace();
3224   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
3225                           AS, Load->getAlignment())) {
3226     SDValue Ops[2];
3227     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
3228     return DAG.getMergeValues(Ops, DL);
3229   }
3230 
3231   MachineFunction &MF = DAG.getMachineFunction();
3232   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3233   // If there is a possibilty that flat instruction access scratch memory
3234   // then we need to use the same legalization rules we use for private.
3235   if (AS == AMDGPUASI.FLAT_ADDRESS)
3236     AS = MFI->hasFlatScratchInit() ?
3237          AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3238 
3239   unsigned NumElements = MemVT.getVectorNumElements();
3240   if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3241     if (isMemOpUniform(Load))
3242       return SDValue();
3243     // Non-uniform loads will be selected to MUBUF instructions, so they
3244     // have the same legalization requirements as global and private
3245     // loads.
3246     //
3247   }
3248   if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) {
3249     if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
3250                   isMemOpHasNoClobberedMemOperand(Load))
3251       return SDValue();
3252     // Non-uniform loads will be selected to MUBUF instructions, so they
3253     // have the same legalization requirements as global and private
3254     // loads.
3255     //
3256   }
3257   if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS ||
3258       AS == AMDGPUASI.FLAT_ADDRESS) {
3259     if (NumElements > 4)
3260       return SplitVectorLoad(Op, DAG);
3261     // v4 loads are supported for private and global memory.
3262     return SDValue();
3263   }
3264   if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3265     // Depending on the setting of the private_element_size field in the
3266     // resource descriptor, we can only make private accesses up to a certain
3267     // size.
3268     switch (Subtarget->getMaxPrivateElementSize()) {
3269     case 4:
3270       return scalarizeVectorLoad(Load, DAG);
3271     case 8:
3272       if (NumElements > 2)
3273         return SplitVectorLoad(Op, DAG);
3274       return SDValue();
3275     case 16:
3276       // Same as global/flat
3277       if (NumElements > 4)
3278         return SplitVectorLoad(Op, DAG);
3279       return SDValue();
3280     default:
3281       llvm_unreachable("unsupported private_element_size");
3282     }
3283   } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3284     if (NumElements > 2)
3285       return SplitVectorLoad(Op, DAG);
3286 
3287     if (NumElements == 2)
3288       return SDValue();
3289 
3290     // If properly aligned, if we split we might be able to use ds_read_b64.
3291     return SplitVectorLoad(Op, DAG);
3292   }
3293   return SDValue();
3294 }
3295 
3296 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3297   if (Op.getValueType() != MVT::i64)
3298     return SDValue();
3299 
3300   SDLoc DL(Op);
3301   SDValue Cond = Op.getOperand(0);
3302 
3303   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
3304   SDValue One = DAG.getConstant(1, DL, MVT::i32);
3305 
3306   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
3307   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
3308 
3309   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
3310   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
3311 
3312   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
3313 
3314   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
3315   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
3316 
3317   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
3318 
3319   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
3320   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
3321 }
3322 
3323 // Catch division cases where we can use shortcuts with rcp and rsq
3324 // instructions.
3325 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
3326                                               SelectionDAG &DAG) const {
3327   SDLoc SL(Op);
3328   SDValue LHS = Op.getOperand(0);
3329   SDValue RHS = Op.getOperand(1);
3330   EVT VT = Op.getValueType();
3331   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
3332 
3333   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
3334     if (Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
3335         VT == MVT::f16) {
3336       if (CLHS->isExactlyValue(1.0)) {
3337         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
3338         // the CI documentation has a worst case error of 1 ulp.
3339         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
3340         // use it as long as we aren't trying to use denormals.
3341         //
3342         // v_rcp_f16 and v_rsq_f16 DO support denormals.
3343 
3344         // 1.0 / sqrt(x) -> rsq(x)
3345 
3346         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
3347         // error seems really high at 2^29 ULP.
3348         if (RHS.getOpcode() == ISD::FSQRT)
3349           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
3350 
3351         // 1.0 / x -> rcp(x)
3352         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3353       }
3354 
3355       // Same as for 1.0, but expand the sign out of the constant.
3356       if (CLHS->isExactlyValue(-1.0)) {
3357         // -1.0 / x -> rcp (fneg x)
3358         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3359         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
3360       }
3361     }
3362   }
3363 
3364   const SDNodeFlags *Flags = Op->getFlags();
3365 
3366   if (Unsafe || Flags->hasAllowReciprocal()) {
3367     // Turn into multiply by the reciprocal.
3368     // x / y -> x * (1.0 / y)
3369     SDNodeFlags Flags;
3370     Flags.setUnsafeAlgebra(true);
3371     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3372     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
3373   }
3374 
3375   return SDValue();
3376 }
3377 
3378 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3379                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
3380   if (GlueChain->getNumValues() <= 1) {
3381     return DAG.getNode(Opcode, SL, VT, A, B);
3382   }
3383 
3384   assert(GlueChain->getNumValues() == 3);
3385 
3386   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3387   switch (Opcode) {
3388   default: llvm_unreachable("no chain equivalent for opcode");
3389   case ISD::FMUL:
3390     Opcode = AMDGPUISD::FMUL_W_CHAIN;
3391     break;
3392   }
3393 
3394   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
3395                      GlueChain.getValue(2));
3396 }
3397 
3398 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3399                            EVT VT, SDValue A, SDValue B, SDValue C,
3400                            SDValue GlueChain) {
3401   if (GlueChain->getNumValues() <= 1) {
3402     return DAG.getNode(Opcode, SL, VT, A, B, C);
3403   }
3404 
3405   assert(GlueChain->getNumValues() == 3);
3406 
3407   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3408   switch (Opcode) {
3409   default: llvm_unreachable("no chain equivalent for opcode");
3410   case ISD::FMA:
3411     Opcode = AMDGPUISD::FMA_W_CHAIN;
3412     break;
3413   }
3414 
3415   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
3416                      GlueChain.getValue(2));
3417 }
3418 
3419 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
3420   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3421     return FastLowered;
3422 
3423   SDLoc SL(Op);
3424   SDValue Src0 = Op.getOperand(0);
3425   SDValue Src1 = Op.getOperand(1);
3426 
3427   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3428   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3429 
3430   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
3431   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
3432 
3433   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
3434   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
3435 
3436   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
3437 }
3438 
3439 // Faster 2.5 ULP division that does not support denormals.
3440 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
3441   SDLoc SL(Op);
3442   SDValue LHS = Op.getOperand(1);
3443   SDValue RHS = Op.getOperand(2);
3444 
3445   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
3446 
3447   const APFloat K0Val(BitsToFloat(0x6f800000));
3448   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
3449 
3450   const APFloat K1Val(BitsToFloat(0x2f800000));
3451   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
3452 
3453   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3454 
3455   EVT SetCCVT =
3456     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
3457 
3458   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
3459 
3460   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
3461 
3462   // TODO: Should this propagate fast-math-flags?
3463   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
3464 
3465   // rcp does not support denormals.
3466   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
3467 
3468   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
3469 
3470   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
3471 }
3472 
3473 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
3474   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3475     return FastLowered;
3476 
3477   SDLoc SL(Op);
3478   SDValue LHS = Op.getOperand(0);
3479   SDValue RHS = Op.getOperand(1);
3480 
3481   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3482 
3483   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
3484 
3485   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3486                                           RHS, RHS, LHS);
3487   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3488                                         LHS, RHS, LHS);
3489 
3490   // Denominator is scaled to not be denormal, so using rcp is ok.
3491   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
3492                                   DenominatorScaled);
3493   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
3494                                      DenominatorScaled);
3495 
3496   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
3497                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
3498                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
3499 
3500   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
3501 
3502   if (!Subtarget->hasFP32Denormals()) {
3503     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
3504     const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
3505                                                       SL, MVT::i32);
3506     SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
3507                                        DAG.getEntryNode(),
3508                                        EnableDenormValue, BitField);
3509     SDValue Ops[3] = {
3510       NegDivScale0,
3511       EnableDenorm.getValue(0),
3512       EnableDenorm.getValue(1)
3513     };
3514 
3515     NegDivScale0 = DAG.getMergeValues(Ops, SL);
3516   }
3517 
3518   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
3519                              ApproxRcp, One, NegDivScale0);
3520 
3521   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
3522                              ApproxRcp, Fma0);
3523 
3524   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
3525                            Fma1, Fma1);
3526 
3527   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
3528                              NumeratorScaled, Mul);
3529 
3530   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
3531 
3532   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
3533                              NumeratorScaled, Fma3);
3534 
3535   if (!Subtarget->hasFP32Denormals()) {
3536     const SDValue DisableDenormValue =
3537         DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
3538     SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
3539                                         Fma4.getValue(1),
3540                                         DisableDenormValue,
3541                                         BitField,
3542                                         Fma4.getValue(2));
3543 
3544     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
3545                                       DisableDenorm, DAG.getRoot());
3546     DAG.setRoot(OutputChain);
3547   }
3548 
3549   SDValue Scale = NumeratorScaled.getValue(1);
3550   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
3551                              Fma4, Fma1, Fma3, Scale);
3552 
3553   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
3554 }
3555 
3556 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
3557   if (DAG.getTarget().Options.UnsafeFPMath)
3558     return lowerFastUnsafeFDIV(Op, DAG);
3559 
3560   SDLoc SL(Op);
3561   SDValue X = Op.getOperand(0);
3562   SDValue Y = Op.getOperand(1);
3563 
3564   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
3565 
3566   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
3567 
3568   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
3569 
3570   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
3571 
3572   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
3573 
3574   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
3575 
3576   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
3577 
3578   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
3579 
3580   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
3581 
3582   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
3583   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
3584 
3585   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
3586                              NegDivScale0, Mul, DivScale1);
3587 
3588   SDValue Scale;
3589 
3590   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
3591     // Workaround a hardware bug on SI where the condition output from div_scale
3592     // is not usable.
3593 
3594     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
3595 
3596     // Figure out if the scale to use for div_fmas.
3597     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
3598     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
3599     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
3600     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
3601 
3602     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
3603     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
3604 
3605     SDValue Scale0Hi
3606       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
3607     SDValue Scale1Hi
3608       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
3609 
3610     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
3611     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
3612     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
3613   } else {
3614     Scale = DivScale1.getValue(1);
3615   }
3616 
3617   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
3618                              Fma4, Fma3, Mul, Scale);
3619 
3620   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
3621 }
3622 
3623 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
3624   EVT VT = Op.getValueType();
3625 
3626   if (VT == MVT::f32)
3627     return LowerFDIV32(Op, DAG);
3628 
3629   if (VT == MVT::f64)
3630     return LowerFDIV64(Op, DAG);
3631 
3632   if (VT == MVT::f16)
3633     return LowerFDIV16(Op, DAG);
3634 
3635   llvm_unreachable("Unexpected type for fdiv");
3636 }
3637 
3638 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3639   SDLoc DL(Op);
3640   StoreSDNode *Store = cast<StoreSDNode>(Op);
3641   EVT VT = Store->getMemoryVT();
3642 
3643   if (VT == MVT::i1) {
3644     return DAG.getTruncStore(Store->getChain(), DL,
3645        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3646        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3647   }
3648 
3649   assert(VT.isVector() &&
3650          Store->getValue().getValueType().getScalarType() == MVT::i32);
3651 
3652   unsigned AS = Store->getAddressSpace();
3653   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3654                           AS, Store->getAlignment())) {
3655     return expandUnalignedStore(Store, DAG);
3656   }
3657 
3658   MachineFunction &MF = DAG.getMachineFunction();
3659   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3660   // If there is a possibilty that flat instruction access scratch memory
3661   // then we need to use the same legalization rules we use for private.
3662   if (AS == AMDGPUASI.FLAT_ADDRESS)
3663     AS = MFI->hasFlatScratchInit() ?
3664          AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3665 
3666   unsigned NumElements = VT.getVectorNumElements();
3667   if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
3668       AS == AMDGPUASI.FLAT_ADDRESS) {
3669     if (NumElements > 4)
3670       return SplitVectorStore(Op, DAG);
3671     return SDValue();
3672   } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3673     switch (Subtarget->getMaxPrivateElementSize()) {
3674     case 4:
3675       return scalarizeVectorStore(Store, DAG);
3676     case 8:
3677       if (NumElements > 2)
3678         return SplitVectorStore(Op, DAG);
3679       return SDValue();
3680     case 16:
3681       if (NumElements > 4)
3682         return SplitVectorStore(Op, DAG);
3683       return SDValue();
3684     default:
3685       llvm_unreachable("unsupported private_element_size");
3686     }
3687   } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3688     if (NumElements > 2)
3689       return SplitVectorStore(Op, DAG);
3690 
3691     if (NumElements == 2)
3692       return Op;
3693 
3694     // If properly aligned, if we split we might be able to use ds_write_b64.
3695     return SplitVectorStore(Op, DAG);
3696   } else {
3697     llvm_unreachable("unhandled address space");
3698   }
3699 }
3700 
3701 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
3702   SDLoc DL(Op);
3703   EVT VT = Op.getValueType();
3704   SDValue Arg = Op.getOperand(0);
3705   // TODO: Should this propagate fast-math-flags?
3706   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
3707                                   DAG.getNode(ISD::FMUL, DL, VT, Arg,
3708                                               DAG.getConstantFP(0.5/M_PI, DL,
3709                                                                 VT)));
3710 
3711   switch (Op.getOpcode()) {
3712   case ISD::FCOS:
3713     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
3714   case ISD::FSIN:
3715     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
3716   default:
3717     llvm_unreachable("Wrong trig opcode");
3718   }
3719 }
3720 
3721 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
3722   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
3723   assert(AtomicNode->isCompareAndSwap());
3724   unsigned AS = AtomicNode->getAddressSpace();
3725 
3726   // No custom lowering required for local address space
3727   if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
3728     return Op;
3729 
3730   // Non-local address space requires custom lowering for atomic compare
3731   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
3732   SDLoc DL(Op);
3733   SDValue ChainIn = Op.getOperand(0);
3734   SDValue Addr = Op.getOperand(1);
3735   SDValue Old = Op.getOperand(2);
3736   SDValue New = Op.getOperand(3);
3737   EVT VT = Op.getValueType();
3738   MVT SimpleVT = VT.getSimpleVT();
3739   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
3740 
3741   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
3742   SDValue Ops[] = { ChainIn, Addr, NewOld };
3743 
3744   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
3745                                  Ops, VT, AtomicNode->getMemOperand());
3746 }
3747 
3748 //===----------------------------------------------------------------------===//
3749 // Custom DAG optimizations
3750 //===----------------------------------------------------------------------===//
3751 
3752 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
3753                                                      DAGCombinerInfo &DCI) const {
3754   EVT VT = N->getValueType(0);
3755   EVT ScalarVT = VT.getScalarType();
3756   if (ScalarVT != MVT::f32)
3757     return SDValue();
3758 
3759   SelectionDAG &DAG = DCI.DAG;
3760   SDLoc DL(N);
3761 
3762   SDValue Src = N->getOperand(0);
3763   EVT SrcVT = Src.getValueType();
3764 
3765   // TODO: We could try to match extracting the higher bytes, which would be
3766   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
3767   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
3768   // about in practice.
3769   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
3770     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
3771       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
3772       DCI.AddToWorklist(Cvt.getNode());
3773       return Cvt;
3774     }
3775   }
3776 
3777   return SDValue();
3778 }
3779 
3780 /// \brief Return true if the given offset Size in bytes can be folded into
3781 /// the immediate offsets of a memory instruction for the given address space.
3782 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
3783                           const SISubtarget &STI) {
3784   auto AMDGPUASI = STI.getAMDGPUAS();
3785   if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
3786     // MUBUF instructions a 12-bit offset in bytes.
3787     return isUInt<12>(OffsetSize);
3788   }
3789   if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3790     // SMRD instructions have an 8-bit offset in dwords on SI and
3791     // a 20-bit offset in bytes on VI.
3792     if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3793       return isUInt<20>(OffsetSize);
3794     else
3795       return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
3796   }
3797   if (AS == AMDGPUASI.LOCAL_ADDRESS ||
3798       AS == AMDGPUASI.REGION_ADDRESS) {
3799     // The single offset versions have a 16-bit offset in bytes.
3800     return isUInt<16>(OffsetSize);
3801   }
3802   // Indirect register addressing does not use any offsets.
3803   return false;
3804 }
3805 
3806 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
3807 
3808 // This is a variant of
3809 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
3810 //
3811 // The normal DAG combiner will do this, but only if the add has one use since
3812 // that would increase the number of instructions.
3813 //
3814 // This prevents us from seeing a constant offset that can be folded into a
3815 // memory instruction's addressing mode. If we know the resulting add offset of
3816 // a pointer can be folded into an addressing offset, we can replace the pointer
3817 // operand with the add of new constant offset. This eliminates one of the uses,
3818 // and may allow the remaining use to also be simplified.
3819 //
3820 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
3821                                                unsigned AddrSpace,
3822                                                DAGCombinerInfo &DCI) const {
3823   SDValue N0 = N->getOperand(0);
3824   SDValue N1 = N->getOperand(1);
3825 
3826   if (N0.getOpcode() != ISD::ADD)
3827     return SDValue();
3828 
3829   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
3830   if (!CN1)
3831     return SDValue();
3832 
3833   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3834   if (!CAdd)
3835     return SDValue();
3836 
3837   // If the resulting offset is too large, we can't fold it into the addressing
3838   // mode offset.
3839   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
3840   if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
3841     return SDValue();
3842 
3843   SelectionDAG &DAG = DCI.DAG;
3844   SDLoc SL(N);
3845   EVT VT = N->getValueType(0);
3846 
3847   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
3848   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
3849 
3850   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
3851 }
3852 
3853 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
3854                                                   DAGCombinerInfo &DCI) const {
3855   SDValue Ptr = N->getBasePtr();
3856   SelectionDAG &DAG = DCI.DAG;
3857   SDLoc SL(N);
3858 
3859   // TODO: We could also do this for multiplies.
3860   unsigned AS = N->getAddressSpace();
3861   if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) {
3862     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
3863     if (NewPtr) {
3864       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
3865 
3866       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
3867       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
3868     }
3869   }
3870 
3871   return SDValue();
3872 }
3873 
3874 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
3875   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
3876          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
3877          (Opc == ISD::XOR && Val == 0);
3878 }
3879 
3880 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
3881 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
3882 // integer combine opportunities since most 64-bit operations are decomposed
3883 // this way.  TODO: We won't want this for SALU especially if it is an inline
3884 // immediate.
3885 SDValue SITargetLowering::splitBinaryBitConstantOp(
3886   DAGCombinerInfo &DCI,
3887   const SDLoc &SL,
3888   unsigned Opc, SDValue LHS,
3889   const ConstantSDNode *CRHS) const {
3890   uint64_t Val = CRHS->getZExtValue();
3891   uint32_t ValLo = Lo_32(Val);
3892   uint32_t ValHi = Hi_32(Val);
3893   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3894 
3895     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
3896          bitOpWithConstantIsReducible(Opc, ValHi)) ||
3897         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
3898     // If we need to materialize a 64-bit immediate, it will be split up later
3899     // anyway. Avoid creating the harder to understand 64-bit immediate
3900     // materialization.
3901     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
3902   }
3903 
3904   return SDValue();
3905 }
3906 
3907 SDValue SITargetLowering::performAndCombine(SDNode *N,
3908                                             DAGCombinerInfo &DCI) const {
3909   if (DCI.isBeforeLegalize())
3910     return SDValue();
3911 
3912   SelectionDAG &DAG = DCI.DAG;
3913   EVT VT = N->getValueType(0);
3914   SDValue LHS = N->getOperand(0);
3915   SDValue RHS = N->getOperand(1);
3916 
3917 
3918   if (VT == MVT::i64) {
3919     const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
3920     if (CRHS) {
3921       if (SDValue Split
3922           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
3923         return Split;
3924     }
3925   }
3926 
3927   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
3928   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
3929   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
3930     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
3931     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
3932 
3933     SDValue X = LHS.getOperand(0);
3934     SDValue Y = RHS.getOperand(0);
3935     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
3936       return SDValue();
3937 
3938     if (LCC == ISD::SETO) {
3939       if (X != LHS.getOperand(1))
3940         return SDValue();
3941 
3942       if (RCC == ISD::SETUNE) {
3943         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
3944         if (!C1 || !C1->isInfinity() || C1->isNegative())
3945           return SDValue();
3946 
3947         const uint32_t Mask = SIInstrFlags::N_NORMAL |
3948                               SIInstrFlags::N_SUBNORMAL |
3949                               SIInstrFlags::N_ZERO |
3950                               SIInstrFlags::P_ZERO |
3951                               SIInstrFlags::P_SUBNORMAL |
3952                               SIInstrFlags::P_NORMAL;
3953 
3954         static_assert(((~(SIInstrFlags::S_NAN |
3955                           SIInstrFlags::Q_NAN |
3956                           SIInstrFlags::N_INFINITY |
3957                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
3958                       "mask not equal");
3959 
3960         SDLoc DL(N);
3961         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3962                            X, DAG.getConstant(Mask, DL, MVT::i32));
3963       }
3964     }
3965   }
3966 
3967   return SDValue();
3968 }
3969 
3970 SDValue SITargetLowering::performOrCombine(SDNode *N,
3971                                            DAGCombinerInfo &DCI) const {
3972   SelectionDAG &DAG = DCI.DAG;
3973   SDValue LHS = N->getOperand(0);
3974   SDValue RHS = N->getOperand(1);
3975 
3976   EVT VT = N->getValueType(0);
3977   if (VT == MVT::i1) {
3978     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
3979     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
3980         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
3981       SDValue Src = LHS.getOperand(0);
3982       if (Src != RHS.getOperand(0))
3983         return SDValue();
3984 
3985       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
3986       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
3987       if (!CLHS || !CRHS)
3988         return SDValue();
3989 
3990       // Only 10 bits are used.
3991       static const uint32_t MaxMask = 0x3ff;
3992 
3993       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
3994       SDLoc DL(N);
3995       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3996                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
3997     }
3998 
3999     return SDValue();
4000   }
4001 
4002   if (VT != MVT::i64)
4003     return SDValue();
4004 
4005   // TODO: This could be a generic combine with a predicate for extracting the
4006   // high half of an integer being free.
4007 
4008   // (or i64:x, (zero_extend i32:y)) ->
4009   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
4010   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
4011       RHS.getOpcode() != ISD::ZERO_EXTEND)
4012     std::swap(LHS, RHS);
4013 
4014   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
4015     SDValue ExtSrc = RHS.getOperand(0);
4016     EVT SrcVT = ExtSrc.getValueType();
4017     if (SrcVT == MVT::i32) {
4018       SDLoc SL(N);
4019       SDValue LowLHS, HiBits;
4020       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
4021       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
4022 
4023       DCI.AddToWorklist(LowOr.getNode());
4024       DCI.AddToWorklist(HiBits.getNode());
4025 
4026       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
4027                                 LowOr, HiBits);
4028       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
4029     }
4030   }
4031 
4032   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
4033   if (CRHS) {
4034     if (SDValue Split
4035           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
4036       return Split;
4037   }
4038 
4039   return SDValue();
4040 }
4041 
4042 SDValue SITargetLowering::performXorCombine(SDNode *N,
4043                                             DAGCombinerInfo &DCI) const {
4044   EVT VT = N->getValueType(0);
4045   if (VT != MVT::i64)
4046     return SDValue();
4047 
4048   SDValue LHS = N->getOperand(0);
4049   SDValue RHS = N->getOperand(1);
4050 
4051   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4052   if (CRHS) {
4053     if (SDValue Split
4054           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
4055       return Split;
4056   }
4057 
4058   return SDValue();
4059 }
4060 
4061 static bool fp16SrcZerosHighBits(unsigned Opc) {
4062   switch (Opc) {
4063   case ISD::SELECT:
4064   case ISD::EXTRACT_VECTOR_ELT:
4065     return false;
4066   default:
4067     return true;
4068   }
4069 }
4070 
4071 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
4072                                                    DAGCombinerInfo &DCI) const {
4073   if (!Subtarget->has16BitInsts() ||
4074       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4075     return SDValue();
4076 
4077   EVT VT = N->getValueType(0);
4078   if (VT != MVT::i32)
4079     return SDValue();
4080 
4081   SDValue Src = N->getOperand(0);
4082   if (Src.getValueType() != MVT::i16)
4083     return SDValue();
4084 
4085   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
4086   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
4087   if (Src.getOpcode() == ISD::BITCAST) {
4088     SDValue BCSrc = Src.getOperand(0);
4089     if (BCSrc.getValueType() == MVT::f16 &&
4090         fp16SrcZerosHighBits(BCSrc.getOpcode()))
4091       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
4092   }
4093 
4094   return SDValue();
4095 }
4096 
4097 SDValue SITargetLowering::performClassCombine(SDNode *N,
4098                                               DAGCombinerInfo &DCI) const {
4099   SelectionDAG &DAG = DCI.DAG;
4100   SDValue Mask = N->getOperand(1);
4101 
4102   // fp_class x, 0 -> false
4103   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
4104     if (CMask->isNullValue())
4105       return DAG.getConstant(0, SDLoc(N), MVT::i1);
4106   }
4107 
4108   if (N->getOperand(0).isUndef())
4109     return DAG.getUNDEF(MVT::i1);
4110 
4111   return SDValue();
4112 }
4113 
4114 // Constant fold canonicalize.
4115 SDValue SITargetLowering::performFCanonicalizeCombine(
4116   SDNode *N,
4117   DAGCombinerInfo &DCI) const {
4118   ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
4119   if (!CFP)
4120     return SDValue();
4121 
4122   SelectionDAG &DAG = DCI.DAG;
4123   const APFloat &C = CFP->getValueAPF();
4124 
4125   // Flush denormals to 0 if not enabled.
4126   if (C.isDenormal()) {
4127     EVT VT = N->getValueType(0);
4128     EVT SVT = VT.getScalarType();
4129     if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
4130       return DAG.getConstantFP(0.0, SDLoc(N), VT);
4131 
4132     if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
4133       return DAG.getConstantFP(0.0, SDLoc(N), VT);
4134 
4135     if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
4136       return DAG.getConstantFP(0.0, SDLoc(N), VT);
4137   }
4138 
4139   if (C.isNaN()) {
4140     EVT VT = N->getValueType(0);
4141     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
4142     if (C.isSignaling()) {
4143       // Quiet a signaling NaN.
4144       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4145     }
4146 
4147     // Make sure it is the canonical NaN bitpattern.
4148     //
4149     // TODO: Can we use -1 as the canonical NaN value since it's an inline
4150     // immediate?
4151     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
4152       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4153   }
4154 
4155   return N->getOperand(0);
4156 }
4157 
4158 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
4159   switch (Opc) {
4160   case ISD::FMAXNUM:
4161     return AMDGPUISD::FMAX3;
4162   case ISD::SMAX:
4163     return AMDGPUISD::SMAX3;
4164   case ISD::UMAX:
4165     return AMDGPUISD::UMAX3;
4166   case ISD::FMINNUM:
4167     return AMDGPUISD::FMIN3;
4168   case ISD::SMIN:
4169     return AMDGPUISD::SMIN3;
4170   case ISD::UMIN:
4171     return AMDGPUISD::UMIN3;
4172   default:
4173     llvm_unreachable("Not a min/max opcode");
4174   }
4175 }
4176 
4177 SDValue SITargetLowering::performIntMed3ImmCombine(
4178   SelectionDAG &DAG, const SDLoc &SL,
4179   SDValue Op0, SDValue Op1, bool Signed) const {
4180   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
4181   if (!K1)
4182     return SDValue();
4183 
4184   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
4185   if (!K0)
4186     return SDValue();
4187 
4188   if (Signed) {
4189     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
4190       return SDValue();
4191   } else {
4192     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
4193       return SDValue();
4194   }
4195 
4196   EVT VT = K0->getValueType(0);
4197   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
4198   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
4199     return DAG.getNode(Med3Opc, SL, VT,
4200                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
4201   }
4202 
4203   // If there isn't a 16-bit med3 operation, convert to 32-bit.
4204   MVT NVT = MVT::i32;
4205   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4206 
4207   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
4208   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
4209   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
4210 
4211   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
4212   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
4213 }
4214 
4215 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
4216   if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
4217     return true;
4218 
4219   return DAG.isKnownNeverNaN(Op);
4220 }
4221 
4222 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
4223                                                   const SDLoc &SL,
4224                                                   SDValue Op0,
4225                                                   SDValue Op1) const {
4226   ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
4227   if (!K1)
4228     return SDValue();
4229 
4230   ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
4231   if (!K0)
4232     return SDValue();
4233 
4234   // Ordered >= (although NaN inputs should have folded away by now).
4235   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
4236   if (Cmp == APFloat::cmpGreaterThan)
4237     return SDValue();
4238 
4239   // TODO: Check IEEE bit enabled?
4240   EVT VT = K0->getValueType(0);
4241   if (Subtarget->enableDX10Clamp()) {
4242     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
4243     // hardware fmed3 behavior converting to a min.
4244     // FIXME: Should this be allowing -0.0?
4245     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
4246       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
4247   }
4248 
4249   // med3 for f16 is only available on gfx9+.
4250   if (VT == MVT::f64 || (VT == MVT::f16 && !Subtarget->hasMed3_16()))
4251     return SDValue();
4252 
4253   // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
4254   // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
4255   // give the other result, which is different from med3 with a NaN input.
4256   SDValue Var = Op0.getOperand(0);
4257   if (!isKnownNeverSNan(DAG, Var))
4258     return SDValue();
4259 
4260   return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
4261                      Var, SDValue(K0, 0), SDValue(K1, 0));
4262 }
4263 
4264 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
4265                                                DAGCombinerInfo &DCI) const {
4266   SelectionDAG &DAG = DCI.DAG;
4267 
4268   EVT VT = N->getValueType(0);
4269   unsigned Opc = N->getOpcode();
4270   SDValue Op0 = N->getOperand(0);
4271   SDValue Op1 = N->getOperand(1);
4272 
4273   // Only do this if the inner op has one use since this will just increases
4274   // register pressure for no benefit.
4275 
4276 
4277   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
4278       VT != MVT::f64) {
4279     // max(max(a, b), c) -> max3(a, b, c)
4280     // min(min(a, b), c) -> min3(a, b, c)
4281     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
4282       SDLoc DL(N);
4283       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4284                          DL,
4285                          N->getValueType(0),
4286                          Op0.getOperand(0),
4287                          Op0.getOperand(1),
4288                          Op1);
4289     }
4290 
4291     // Try commuted.
4292     // max(a, max(b, c)) -> max3(a, b, c)
4293     // min(a, min(b, c)) -> min3(a, b, c)
4294     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
4295       SDLoc DL(N);
4296       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4297                          DL,
4298                          N->getValueType(0),
4299                          Op0,
4300                          Op1.getOperand(0),
4301                          Op1.getOperand(1));
4302     }
4303   }
4304 
4305   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
4306   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
4307     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
4308       return Med3;
4309   }
4310 
4311   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4312     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
4313       return Med3;
4314   }
4315 
4316   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
4317   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
4318        (Opc == AMDGPUISD::FMIN_LEGACY &&
4319         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
4320       (VT == MVT::f32 || VT == MVT::f64 ||
4321        (VT == MVT::f16 && Subtarget->has16BitInsts())) &&
4322       Op0.hasOneUse()) {
4323     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
4324       return Res;
4325   }
4326 
4327   return SDValue();
4328 }
4329 
4330 static bool isClampZeroToOne(SDValue A, SDValue B) {
4331   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
4332     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
4333       // FIXME: Should this be allowing -0.0?
4334       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
4335              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
4336     }
4337   }
4338 
4339   return false;
4340 }
4341 
4342 // FIXME: Should only worry about snans for version with chain.
4343 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
4344                                               DAGCombinerInfo &DCI) const {
4345   EVT VT = N->getValueType(0);
4346   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
4347   // NaNs. With a NaN input, the order of the operands may change the result.
4348 
4349   SelectionDAG &DAG = DCI.DAG;
4350   SDLoc SL(N);
4351 
4352   SDValue Src0 = N->getOperand(0);
4353   SDValue Src1 = N->getOperand(1);
4354   SDValue Src2 = N->getOperand(2);
4355 
4356   if (isClampZeroToOne(Src0, Src1)) {
4357     // const_a, const_b, x -> clamp is safe in all cases including signaling
4358     // nans.
4359     // FIXME: Should this be allowing -0.0?
4360     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
4361   }
4362 
4363   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
4364   // handling no dx10-clamp?
4365   if (Subtarget->enableDX10Clamp()) {
4366     // If NaNs is clamped to 0, we are free to reorder the inputs.
4367 
4368     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4369       std::swap(Src0, Src1);
4370 
4371     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
4372       std::swap(Src1, Src2);
4373 
4374     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4375       std::swap(Src0, Src1);
4376 
4377     if (isClampZeroToOne(Src1, Src2))
4378       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
4379   }
4380 
4381   return SDValue();
4382 }
4383 
4384 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
4385                                                  DAGCombinerInfo &DCI) const {
4386   SDValue Src0 = N->getOperand(0);
4387   SDValue Src1 = N->getOperand(1);
4388   if (Src0.isUndef() && Src1.isUndef())
4389     return DCI.DAG.getUNDEF(N->getValueType(0));
4390   return SDValue();
4391 }
4392 
4393 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
4394                                           const SDNode *N0,
4395                                           const SDNode *N1) const {
4396   EVT VT = N0->getValueType(0);
4397 
4398   // Only do this if we are not trying to support denormals. v_mad_f32 does not
4399   // support denormals ever.
4400   if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
4401       (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
4402     return ISD::FMAD;
4403 
4404   const TargetOptions &Options = DAG.getTarget().Options;
4405   if ((Options.AllowFPOpFusion == FPOpFusion::Fast ||
4406        Options.UnsafeFPMath ||
4407        (cast<BinaryWithFlagsSDNode>(N0)->Flags.hasUnsafeAlgebra() &&
4408         cast<BinaryWithFlagsSDNode>(N1)->Flags.hasUnsafeAlgebra())) &&
4409       isFMAFasterThanFMulAndFAdd(VT)) {
4410     return ISD::FMA;
4411   }
4412 
4413   return 0;
4414 }
4415 
4416 SDValue SITargetLowering::performFAddCombine(SDNode *N,
4417                                              DAGCombinerInfo &DCI) const {
4418   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4419     return SDValue();
4420 
4421   SelectionDAG &DAG = DCI.DAG;
4422   EVT VT = N->getValueType(0);
4423 
4424   SDLoc SL(N);
4425   SDValue LHS = N->getOperand(0);
4426   SDValue RHS = N->getOperand(1);
4427 
4428   // These should really be instruction patterns, but writing patterns with
4429   // source modiifiers is a pain.
4430 
4431   // fadd (fadd (a, a), b) -> mad 2.0, a, b
4432   if (LHS.getOpcode() == ISD::FADD) {
4433     SDValue A = LHS.getOperand(0);
4434     if (A == LHS.getOperand(1)) {
4435       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4436       if (FusedOp != 0) {
4437         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4438         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
4439       }
4440     }
4441   }
4442 
4443   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
4444   if (RHS.getOpcode() == ISD::FADD) {
4445     SDValue A = RHS.getOperand(0);
4446     if (A == RHS.getOperand(1)) {
4447       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4448       if (FusedOp != 0) {
4449         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4450         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
4451       }
4452     }
4453   }
4454 
4455   return SDValue();
4456 }
4457 
4458 SDValue SITargetLowering::performFSubCombine(SDNode *N,
4459                                              DAGCombinerInfo &DCI) const {
4460   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4461     return SDValue();
4462 
4463   SelectionDAG &DAG = DCI.DAG;
4464   SDLoc SL(N);
4465   EVT VT = N->getValueType(0);
4466   assert(!VT.isVector());
4467 
4468   // Try to get the fneg to fold into the source modifier. This undoes generic
4469   // DAG combines and folds them into the mad.
4470   //
4471   // Only do this if we are not trying to support denormals. v_mad_f32 does
4472   // not support denormals ever.
4473   SDValue LHS = N->getOperand(0);
4474   SDValue RHS = N->getOperand(1);
4475   if (LHS.getOpcode() == ISD::FADD) {
4476     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
4477     SDValue A = LHS.getOperand(0);
4478     if (A == LHS.getOperand(1)) {
4479       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4480       if (FusedOp != 0){
4481         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4482         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
4483 
4484         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
4485       }
4486     }
4487   }
4488 
4489   if (RHS.getOpcode() == ISD::FADD) {
4490     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
4491 
4492     SDValue A = RHS.getOperand(0);
4493     if (A == RHS.getOperand(1)) {
4494       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4495       if (FusedOp != 0){
4496         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
4497         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
4498       }
4499     }
4500   }
4501 
4502   return SDValue();
4503 }
4504 
4505 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
4506                                               DAGCombinerInfo &DCI) const {
4507   SelectionDAG &DAG = DCI.DAG;
4508   SDLoc SL(N);
4509 
4510   SDValue LHS = N->getOperand(0);
4511   SDValue RHS = N->getOperand(1);
4512   EVT VT = LHS.getValueType();
4513 
4514   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
4515                                            VT != MVT::f16))
4516     return SDValue();
4517 
4518   // Match isinf pattern
4519   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
4520   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4521   if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
4522     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
4523     if (!CRHS)
4524       return SDValue();
4525 
4526     const APFloat &APF = CRHS->getValueAPF();
4527     if (APF.isInfinity() && !APF.isNegative()) {
4528       unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
4529       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
4530                          DAG.getConstant(Mask, SL, MVT::i32));
4531     }
4532   }
4533 
4534   return SDValue();
4535 }
4536 
4537 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
4538                                                      DAGCombinerInfo &DCI) const {
4539   SelectionDAG &DAG = DCI.DAG;
4540   SDLoc SL(N);
4541   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
4542 
4543   SDValue Src = N->getOperand(0);
4544   SDValue Srl = N->getOperand(0);
4545   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
4546     Srl = Srl.getOperand(0);
4547 
4548   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
4549   if (Srl.getOpcode() == ISD::SRL) {
4550     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
4551     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
4552     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
4553 
4554     if (const ConstantSDNode *C =
4555         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
4556       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
4557                                EVT(MVT::i32));
4558 
4559       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
4560       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
4561         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
4562                            MVT::f32, Srl);
4563       }
4564     }
4565   }
4566 
4567   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
4568 
4569   APInt KnownZero, KnownOne;
4570   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4571                                         !DCI.isBeforeLegalizeOps());
4572   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4573   if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
4574       TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
4575     DCI.CommitTargetLoweringOpt(TLO);
4576   }
4577 
4578   return SDValue();
4579 }
4580 
4581 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
4582                                             DAGCombinerInfo &DCI) const {
4583   switch (N->getOpcode()) {
4584   default:
4585     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4586   case ISD::FADD:
4587     return performFAddCombine(N, DCI);
4588   case ISD::FSUB:
4589     return performFSubCombine(N, DCI);
4590   case ISD::SETCC:
4591     return performSetCCCombine(N, DCI);
4592   case ISD::FMAXNUM:
4593   case ISD::FMINNUM:
4594   case ISD::SMAX:
4595   case ISD::SMIN:
4596   case ISD::UMAX:
4597   case ISD::UMIN:
4598   case AMDGPUISD::FMIN_LEGACY:
4599   case AMDGPUISD::FMAX_LEGACY: {
4600     if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
4601         getTargetMachine().getOptLevel() > CodeGenOpt::None)
4602       return performMinMaxCombine(N, DCI);
4603     break;
4604   }
4605   case ISD::LOAD:
4606   case ISD::STORE:
4607   case ISD::ATOMIC_LOAD:
4608   case ISD::ATOMIC_STORE:
4609   case ISD::ATOMIC_CMP_SWAP:
4610   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4611   case ISD::ATOMIC_SWAP:
4612   case ISD::ATOMIC_LOAD_ADD:
4613   case ISD::ATOMIC_LOAD_SUB:
4614   case ISD::ATOMIC_LOAD_AND:
4615   case ISD::ATOMIC_LOAD_OR:
4616   case ISD::ATOMIC_LOAD_XOR:
4617   case ISD::ATOMIC_LOAD_NAND:
4618   case ISD::ATOMIC_LOAD_MIN:
4619   case ISD::ATOMIC_LOAD_MAX:
4620   case ISD::ATOMIC_LOAD_UMIN:
4621   case ISD::ATOMIC_LOAD_UMAX:
4622   case AMDGPUISD::ATOMIC_INC:
4623   case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
4624     if (DCI.isBeforeLegalize())
4625       break;
4626     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
4627   case ISD::AND:
4628     return performAndCombine(N, DCI);
4629   case ISD::OR:
4630     return performOrCombine(N, DCI);
4631   case ISD::XOR:
4632     return performXorCombine(N, DCI);
4633   case ISD::ZERO_EXTEND:
4634     return performZeroExtendCombine(N, DCI);
4635   case AMDGPUISD::FP_CLASS:
4636     return performClassCombine(N, DCI);
4637   case ISD::FCANONICALIZE:
4638     return performFCanonicalizeCombine(N, DCI);
4639   case AMDGPUISD::FRACT:
4640   case AMDGPUISD::RCP:
4641   case AMDGPUISD::RSQ:
4642   case AMDGPUISD::RCP_LEGACY:
4643   case AMDGPUISD::RSQ_LEGACY:
4644   case AMDGPUISD::RSQ_CLAMP:
4645   case AMDGPUISD::LDEXP: {
4646     SDValue Src = N->getOperand(0);
4647     if (Src.isUndef())
4648       return Src;
4649     break;
4650   }
4651   case ISD::SINT_TO_FP:
4652   case ISD::UINT_TO_FP:
4653     return performUCharToFloatCombine(N, DCI);
4654   case AMDGPUISD::CVT_F32_UBYTE0:
4655   case AMDGPUISD::CVT_F32_UBYTE1:
4656   case AMDGPUISD::CVT_F32_UBYTE2:
4657   case AMDGPUISD::CVT_F32_UBYTE3:
4658     return performCvtF32UByteNCombine(N, DCI);
4659   case AMDGPUISD::FMED3:
4660     return performFMed3Combine(N, DCI);
4661   case AMDGPUISD::CVT_PKRTZ_F16_F32:
4662     return performCvtPkRTZCombine(N, DCI);
4663   case ISD::SCALAR_TO_VECTOR: {
4664     SelectionDAG &DAG = DCI.DAG;
4665     EVT VT = N->getValueType(0);
4666 
4667     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
4668     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
4669       SDLoc SL(N);
4670       SDValue Src = N->getOperand(0);
4671       EVT EltVT = Src.getValueType();
4672       if (EltVT == MVT::f16)
4673         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
4674 
4675       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
4676       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
4677     }
4678 
4679     break;
4680   }
4681   }
4682   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4683 }
4684 
4685 /// \brief Helper function for adjustWritemask
4686 static unsigned SubIdx2Lane(unsigned Idx) {
4687   switch (Idx) {
4688   default: return 0;
4689   case AMDGPU::sub0: return 0;
4690   case AMDGPU::sub1: return 1;
4691   case AMDGPU::sub2: return 2;
4692   case AMDGPU::sub3: return 3;
4693   }
4694 }
4695 
4696 /// \brief Adjust the writemask of MIMG instructions
4697 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
4698                                        SelectionDAG &DAG) const {
4699   SDNode *Users[4] = { };
4700   unsigned Lane = 0;
4701   unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
4702   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
4703   unsigned NewDmask = 0;
4704 
4705   // Try to figure out the used register components
4706   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
4707        I != E; ++I) {
4708 
4709     // Don't look at users of the chain.
4710     if (I.getUse().getResNo() != 0)
4711       continue;
4712 
4713     // Abort if we can't understand the usage
4714     if (!I->isMachineOpcode() ||
4715         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
4716       return;
4717 
4718     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
4719     // Note that subregs are packed, i.e. Lane==0 is the first bit set
4720     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
4721     // set, etc.
4722     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
4723 
4724     // Set which texture component corresponds to the lane.
4725     unsigned Comp;
4726     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
4727       assert(Dmask);
4728       Comp = countTrailingZeros(Dmask);
4729       Dmask &= ~(1 << Comp);
4730     }
4731 
4732     // Abort if we have more than one user per component
4733     if (Users[Lane])
4734       return;
4735 
4736     Users[Lane] = *I;
4737     NewDmask |= 1 << Comp;
4738   }
4739 
4740   // Abort if there's no change
4741   if (NewDmask == OldDmask)
4742     return;
4743 
4744   // Adjust the writemask in the node
4745   std::vector<SDValue> Ops;
4746   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
4747   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
4748   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
4749   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
4750 
4751   // If we only got one lane, replace it with a copy
4752   // (if NewDmask has only one bit set...)
4753   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
4754     SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
4755                                        MVT::i32);
4756     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4757                                       SDLoc(), Users[Lane]->getValueType(0),
4758                                       SDValue(Node, 0), RC);
4759     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
4760     return;
4761   }
4762 
4763   // Update the users of the node with the new indices
4764   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
4765     SDNode *User = Users[i];
4766     if (!User)
4767       continue;
4768 
4769     SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
4770     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
4771 
4772     switch (Idx) {
4773     default: break;
4774     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
4775     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
4776     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
4777     }
4778   }
4779 }
4780 
4781 static bool isFrameIndexOp(SDValue Op) {
4782   if (Op.getOpcode() == ISD::AssertZext)
4783     Op = Op.getOperand(0);
4784 
4785   return isa<FrameIndexSDNode>(Op);
4786 }
4787 
4788 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
4789 /// with frame index operands.
4790 /// LLVM assumes that inputs are to these instructions are registers.
4791 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
4792                                                      SelectionDAG &DAG) const {
4793 
4794   SmallVector<SDValue, 8> Ops;
4795   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
4796     if (!isFrameIndexOp(Node->getOperand(i))) {
4797       Ops.push_back(Node->getOperand(i));
4798       continue;
4799     }
4800 
4801     SDLoc DL(Node);
4802     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
4803                                      Node->getOperand(i).getValueType(),
4804                                      Node->getOperand(i)), 0));
4805   }
4806 
4807   DAG.UpdateNodeOperands(Node, Ops);
4808 }
4809 
4810 /// \brief Fold the instructions after selecting them.
4811 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
4812                                           SelectionDAG &DAG) const {
4813   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4814   unsigned Opcode = Node->getMachineOpcode();
4815 
4816   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
4817       !TII->isGather4(Opcode))
4818     adjustWritemask(Node, DAG);
4819 
4820   if (Opcode == AMDGPU::INSERT_SUBREG ||
4821       Opcode == AMDGPU::REG_SEQUENCE) {
4822     legalizeTargetIndependentNode(Node, DAG);
4823     return Node;
4824   }
4825   return Node;
4826 }
4827 
4828 /// \brief Assign the register class depending on the number of
4829 /// bits set in the writemask
4830 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
4831                                                      SDNode *Node) const {
4832   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4833 
4834   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4835 
4836   if (TII->isVOP3(MI.getOpcode())) {
4837     // Make sure constant bus requirements are respected.
4838     TII->legalizeOperandsVOP3(MRI, MI);
4839     return;
4840   }
4841 
4842   if (TII->isMIMG(MI)) {
4843     unsigned VReg = MI.getOperand(0).getReg();
4844     const TargetRegisterClass *RC = MRI.getRegClass(VReg);
4845     // TODO: Need mapping tables to handle other cases (register classes).
4846     if (RC != &AMDGPU::VReg_128RegClass)
4847       return;
4848 
4849     unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
4850     unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
4851     unsigned BitsSet = 0;
4852     for (unsigned i = 0; i < 4; ++i)
4853       BitsSet += Writemask & (1 << i) ? 1 : 0;
4854     switch (BitsSet) {
4855     default: return;
4856     case 1:  RC = &AMDGPU::VGPR_32RegClass; break;
4857     case 2:  RC = &AMDGPU::VReg_64RegClass; break;
4858     case 3:  RC = &AMDGPU::VReg_96RegClass; break;
4859     }
4860 
4861     unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
4862     MI.setDesc(TII->get(NewOpcode));
4863     MRI.setRegClass(VReg, RC);
4864     return;
4865   }
4866 
4867   // Replace unused atomics with the no return version.
4868   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
4869   if (NoRetAtomicOp != -1) {
4870     if (!Node->hasAnyUseOfValue(0)) {
4871       MI.setDesc(TII->get(NoRetAtomicOp));
4872       MI.RemoveOperand(0);
4873       return;
4874     }
4875 
4876     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
4877     // instruction, because the return type of these instructions is a vec2 of
4878     // the memory type, so it can be tied to the input operand.
4879     // This means these instructions always have a use, so we need to add a
4880     // special case to check if the atomic has only one extract_subreg use,
4881     // which itself has no uses.
4882     if ((Node->hasNUsesOfValue(1, 0) &&
4883          Node->use_begin()->isMachineOpcode() &&
4884          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
4885          !Node->use_begin()->hasAnyUseOfValue(0))) {
4886       unsigned Def = MI.getOperand(0).getReg();
4887 
4888       // Change this into a noret atomic.
4889       MI.setDesc(TII->get(NoRetAtomicOp));
4890       MI.RemoveOperand(0);
4891 
4892       // If we only remove the def operand from the atomic instruction, the
4893       // extract_subreg will be left with a use of a vreg without a def.
4894       // So we need to insert an implicit_def to avoid machine verifier
4895       // errors.
4896       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
4897               TII->get(AMDGPU::IMPLICIT_DEF), Def);
4898     }
4899     return;
4900   }
4901 }
4902 
4903 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
4904                               uint64_t Val) {
4905   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
4906   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
4907 }
4908 
4909 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
4910                                                 const SDLoc &DL,
4911                                                 SDValue Ptr) const {
4912   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4913 
4914   // Build the half of the subregister with the constants before building the
4915   // full 128-bit register. If we are building multiple resource descriptors,
4916   // this will allow CSEing of the 2-component register.
4917   const SDValue Ops0[] = {
4918     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
4919     buildSMovImm32(DAG, DL, 0),
4920     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4921     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
4922     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
4923   };
4924 
4925   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
4926                                                 MVT::v2i32, Ops0), 0);
4927 
4928   // Combine the constants and the pointer.
4929   const SDValue Ops1[] = {
4930     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4931     Ptr,
4932     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
4933     SubRegHi,
4934     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
4935   };
4936 
4937   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
4938 }
4939 
4940 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
4941 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
4942 ///        of the resource descriptor) to create an offset, which is added to
4943 ///        the resource pointer.
4944 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
4945                                            SDValue Ptr, uint32_t RsrcDword1,
4946                                            uint64_t RsrcDword2And3) const {
4947   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
4948   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
4949   if (RsrcDword1) {
4950     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
4951                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
4952                     0);
4953   }
4954 
4955   SDValue DataLo = buildSMovImm32(DAG, DL,
4956                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
4957   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
4958 
4959   const SDValue Ops[] = {
4960     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4961     PtrLo,
4962     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4963     PtrHi,
4964     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
4965     DataLo,
4966     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
4967     DataHi,
4968     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
4969   };
4970 
4971   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
4972 }
4973 
4974 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
4975                                                const TargetRegisterClass *RC,
4976                                                unsigned Reg, EVT VT) const {
4977   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
4978 
4979   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
4980                             cast<RegisterSDNode>(VReg)->getReg(), VT);
4981 }
4982 
4983 //===----------------------------------------------------------------------===//
4984 //                         SI Inline Assembly Support
4985 //===----------------------------------------------------------------------===//
4986 
4987 std::pair<unsigned, const TargetRegisterClass *>
4988 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4989                                                StringRef Constraint,
4990                                                MVT VT) const {
4991   if (!isTypeLegal(VT))
4992     return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4993 
4994   if (Constraint.size() == 1) {
4995     switch (Constraint[0]) {
4996     case 's':
4997     case 'r':
4998       switch (VT.getSizeInBits()) {
4999       default:
5000         return std::make_pair(0U, nullptr);
5001       case 32:
5002       case 16:
5003         return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
5004       case 64:
5005         return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
5006       case 128:
5007         return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
5008       case 256:
5009         return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
5010       case 512:
5011         return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
5012       }
5013 
5014     case 'v':
5015       switch (VT.getSizeInBits()) {
5016       default:
5017         return std::make_pair(0U, nullptr);
5018       case 32:
5019       case 16:
5020         return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
5021       case 64:
5022         return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
5023       case 96:
5024         return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
5025       case 128:
5026         return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
5027       case 256:
5028         return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
5029       case 512:
5030         return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
5031       }
5032     }
5033   }
5034 
5035   if (Constraint.size() > 1) {
5036     const TargetRegisterClass *RC = nullptr;
5037     if (Constraint[1] == 'v') {
5038       RC = &AMDGPU::VGPR_32RegClass;
5039     } else if (Constraint[1] == 's') {
5040       RC = &AMDGPU::SGPR_32RegClass;
5041     }
5042 
5043     if (RC) {
5044       uint32_t Idx;
5045       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
5046       if (!Failed && Idx < RC->getNumRegs())
5047         return std::make_pair(RC->getRegister(Idx), RC);
5048     }
5049   }
5050   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5051 }
5052 
5053 SITargetLowering::ConstraintType
5054 SITargetLowering::getConstraintType(StringRef Constraint) const {
5055   if (Constraint.size() == 1) {
5056     switch (Constraint[0]) {
5057     default: break;
5058     case 's':
5059     case 'v':
5060       return C_RegisterClass;
5061     }
5062   }
5063   return TargetLowering::getConstraintType(Constraint);
5064 }
5065