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