• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "SIDefines.h"
20 #include "SIInstrInfo.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "SIRegisterInfo.h"
23 #include "Utils/AMDGPUBaseInfo.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/DAGCombine.h"
37 #include "llvm/CodeGen/FunctionLoweringInfo.h"
38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/SelectionDAG.h"
51 #include "llvm/CodeGen/SelectionDAGNodes.h"
52 #include "llvm/CodeGen/TargetCallingConv.h"
53 #include "llvm/CodeGen/TargetRegisterInfo.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/IR/Constants.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/DebugLoc.h"
58 #include "llvm/IR/DerivedTypes.h"
59 #include "llvm/IR/DiagnosticInfo.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/GlobalValue.h"
62 #include "llvm/IR/InstrTypes.h"
63 #include "llvm/IR/Instruction.h"
64 #include "llvm/IR/Instructions.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/Type.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/KnownBits.h"
73 #include "llvm/Support/MachineValueType.h"
74 #include "llvm/Support/MathExtras.h"
75 #include "llvm/Target/TargetOptions.h"
76 #include <cassert>
77 #include <cmath>
78 #include <cstdint>
79 #include <iterator>
80 #include <tuple>
81 #include <utility>
82 #include <vector>
83 
84 using namespace llvm;
85 
86 #define DEBUG_TYPE "si-lower"
87 
88 STATISTIC(NumTailCalls, "Number of tail calls");
89 
90 static cl::opt<bool> DisableLoopAlignment(
91   "amdgpu-disable-loop-alignment",
92   cl::desc("Do not align and prefetch loops"),
93   cl::init(false));
94 
95 static cl::opt<bool> VGPRReserveforSGPRSpill(
96     "amdgpu-reserve-vgpr-for-sgpr-spill",
97     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
98 
99 static cl::opt<bool> UseDivergentRegisterIndexing(
100   "amdgpu-use-divergent-register-indexing",
101   cl::Hidden,
102   cl::desc("Use indirect register addressing for divergent indexes"),
103   cl::init(false));
104 
hasFP32Denormals(const MachineFunction & MF)105 static bool hasFP32Denormals(const MachineFunction &MF) {
106   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
107   return Info->getMode().allFP32Denormals();
108 }
109 
hasFP64FP16Denormals(const MachineFunction & MF)110 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
111   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
112   return Info->getMode().allFP64FP16Denormals();
113 }
114 
findFirstFreeSGPR(CCState & CCInfo)115 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
116   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
117   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
118     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
119       return AMDGPU::SGPR0 + Reg;
120     }
121   }
122   llvm_unreachable("Cannot allocate sgpr");
123 }
124 
SITargetLowering(const TargetMachine & TM,const GCNSubtarget & STI)125 SITargetLowering::SITargetLowering(const TargetMachine &TM,
126                                    const GCNSubtarget &STI)
127     : AMDGPUTargetLowering(TM, STI),
128       Subtarget(&STI) {
129   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
130   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
131 
132   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
133   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
134 
135   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
136   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
137   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
138 
139   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
140   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
141 
142   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
143   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
144 
145   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
146   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
147 
148   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
149   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
150 
151   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
152   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
153 
154   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
155   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
156 
157   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
158   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
159 
160   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
161   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
162 
163   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
164   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
165 
166   if (Subtarget->has16BitInsts()) {
167     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
168     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
169 
170     // Unless there are also VOP3P operations, not operations are really legal.
171     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
172     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
173     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
174     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
175   }
176 
177   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
178   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
179 
180   computeRegisterProperties(Subtarget->getRegisterInfo());
181 
182   // The boolean content concept here is too inflexible. Compares only ever
183   // really produce a 1-bit result. Any copy/extend from these will turn into a
184   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
185   // it's what most targets use.
186   setBooleanContents(ZeroOrOneBooleanContent);
187   setBooleanVectorContents(ZeroOrOneBooleanContent);
188 
189   // We need to custom lower vector stores from local memory
190   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
195   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
196   setOperationAction(ISD::LOAD, MVT::i1, Custom);
197   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
198 
199   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
203   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
204   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
205   setOperationAction(ISD::STORE, MVT::i1, Custom);
206   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
207 
208   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
209   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
210   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
211   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
212   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
213   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
214   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
215   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
216   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
217   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
218   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
219   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
220   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
221   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
222   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
223   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
224 
225   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
227   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
228   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
229   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
230 
231   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
232   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
233 
234   setOperationAction(ISD::SELECT, MVT::i1, Promote);
235   setOperationAction(ISD::SELECT, MVT::i64, Custom);
236   setOperationAction(ISD::SELECT, MVT::f64, Promote);
237   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
238 
239   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
242   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
243   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
244 
245   setOperationAction(ISD::SETCC, MVT::i1, Promote);
246   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
247   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
248   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
249 
250   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
251   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
252   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
253   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
254   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
255   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
256   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
257   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
258 
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
267 
268   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
269   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
270   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
271   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
272   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
273   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
274 
275   setOperationAction(ISD::UADDO, MVT::i32, Legal);
276   setOperationAction(ISD::USUBO, MVT::i32, Legal);
277 
278   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
279   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
280 
281   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
282   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
283   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
284 
285 #if 0
286   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
287   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
288 #endif
289 
290   // We only support LOAD/STORE and vector manipulation ops for vectors
291   // with > 4 elements.
292   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
293                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
294                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
295                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
296     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
297       switch (Op) {
298       case ISD::LOAD:
299       case ISD::STORE:
300       case ISD::BUILD_VECTOR:
301       case ISD::BITCAST:
302       case ISD::EXTRACT_VECTOR_ELT:
303       case ISD::INSERT_VECTOR_ELT:
304       case ISD::INSERT_SUBVECTOR:
305       case ISD::EXTRACT_SUBVECTOR:
306       case ISD::SCALAR_TO_VECTOR:
307         break;
308       case ISD::CONCAT_VECTORS:
309         setOperationAction(Op, VT, Custom);
310         break;
311       default:
312         setOperationAction(Op, VT, Expand);
313         break;
314       }
315     }
316   }
317 
318   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
319 
320   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
321   // is expanded to avoid having two separate loops in case the index is a VGPR.
322 
323   // Most operations are naturally 32-bit vector operations. We only support
324   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
325   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
326     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
327     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
328 
329     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
330     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
331 
332     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
333     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
334 
335     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
336     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
337   }
338 
339   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
340     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
341     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
342 
343     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
344     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
345 
346     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
347     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
348 
349     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
350     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
351   }
352 
353   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
354     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
355     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
356 
357     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
358     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
359 
360     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
361     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
362 
363     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
364     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
365   }
366 
367   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
368     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
369     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
370 
371     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
372     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
373 
374     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
375     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
376 
377     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
378     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
379   }
380 
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
383   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
384   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
385 
386   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
387   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
388 
389   // Avoid stack access for these.
390   // TODO: Generalize to more vector types.
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
395 
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
400   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
401 
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
403   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
404   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
405 
406   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
407   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
408   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
409   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
410 
411   // Deal with vec3 vector operations when widened to vec4.
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
416 
417   // Deal with vec5 vector operations when widened to vec8.
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
420   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
421   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
422 
423   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
424   // and output demarshalling
425   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
426   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
427 
428   // We can't return success/failure, only the old value,
429   // let LLVM add the comparison
430   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
431   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
432 
433   if (Subtarget->hasFlatAddressSpace()) {
434     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
435     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
436   }
437 
438   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
439 
440   // FIXME: This should be narrowed to i32, but that only happens if i64 is
441   // illegal.
442   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
443   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
444   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
445 
446   // On SI this is s_memtime and s_memrealtime on VI.
447   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
448   setOperationAction(ISD::TRAP, MVT::Other, Custom);
449   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
450 
451   if (Subtarget->has16BitInsts()) {
452     setOperationAction(ISD::FPOW, MVT::f16, Promote);
453     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
454     setOperationAction(ISD::FLOG, MVT::f16, Custom);
455     setOperationAction(ISD::FEXP, MVT::f16, Custom);
456     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
457   }
458 
459   if (Subtarget->hasMadMacF32Insts())
460     setOperationAction(ISD::FMAD, MVT::f32, Legal);
461 
462   if (!Subtarget->hasBFI()) {
463     // fcopysign can be done in a single instruction with BFI.
464     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
465     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
466   }
467 
468   if (!Subtarget->hasBCNT(32))
469     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
470 
471   if (!Subtarget->hasBCNT(64))
472     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
473 
474   if (Subtarget->hasFFBH())
475     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
476 
477   if (Subtarget->hasFFBL())
478     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
479 
480   // We only really have 32-bit BFE instructions (and 16-bit on VI).
481   //
482   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
483   // effort to match them now. We want this to be false for i64 cases when the
484   // extraction isn't restricted to the upper or lower half. Ideally we would
485   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
486   // span the midpoint are probably relatively rare, so don't worry about them
487   // for now.
488   if (Subtarget->hasBFE())
489     setHasExtractBitsInsn(true);
490 
491   // Clamp modifier on add/sub
492   if (Subtarget->hasIntClamp()) {
493     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
494     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
495   }
496 
497   if (Subtarget->hasAddNoCarry()) {
498     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
501     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
502   }
503 
504   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
507   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
508 
509 
510   // These are really only legal for ieee_mode functions. We should be avoiding
511   // them for functions that don't have ieee_mode enabled, so just say they are
512   // legal.
513   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
516   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
517 
518 
519   if (Subtarget->haveRoundOpsF64()) {
520     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
521     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
522     setOperationAction(ISD::FRINT, MVT::f64, Legal);
523   } else {
524     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
525     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
526     setOperationAction(ISD::FRINT, MVT::f64, Custom);
527     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
528   }
529 
530   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
531 
532   setOperationAction(ISD::FSIN, MVT::f32, Custom);
533   setOperationAction(ISD::FCOS, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f64, Custom);
536 
537   if (Subtarget->has16BitInsts()) {
538     setOperationAction(ISD::Constant, MVT::i16, Legal);
539 
540     setOperationAction(ISD::SMIN, MVT::i16, Legal);
541     setOperationAction(ISD::SMAX, MVT::i16, Legal);
542 
543     setOperationAction(ISD::UMIN, MVT::i16, Legal);
544     setOperationAction(ISD::UMAX, MVT::i16, Legal);
545 
546     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
547     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
548 
549     setOperationAction(ISD::ROTR, MVT::i16, Expand);
550     setOperationAction(ISD::ROTL, MVT::i16, Expand);
551 
552     setOperationAction(ISD::SDIV, MVT::i16, Promote);
553     setOperationAction(ISD::UDIV, MVT::i16, Promote);
554     setOperationAction(ISD::SREM, MVT::i16, Promote);
555     setOperationAction(ISD::UREM, MVT::i16, Promote);
556     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
557     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
558 
559     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
560 
561     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
565     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
566 
567     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
568 
569     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
570 
571     setOperationAction(ISD::LOAD, MVT::i16, Custom);
572 
573     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
574 
575     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
576     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
577     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
578     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
579 
580     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
581     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
582 
583     // F16 - Constant Actions.
584     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
585 
586     // F16 - Load/Store Actions.
587     setOperationAction(ISD::LOAD, MVT::f16, Promote);
588     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
589     setOperationAction(ISD::STORE, MVT::f16, Promote);
590     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
591 
592     // F16 - VOP1 Actions.
593     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
594     setOperationAction(ISD::FCOS, MVT::f16, Custom);
595     setOperationAction(ISD::FSIN, MVT::f16, Custom);
596 
597     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
598     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
599 
600     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
601     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
602     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::FROUND, MVT::f16, Custom);
605 
606     // F16 - VOP2 Actions.
607     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
608     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
609 
610     setOperationAction(ISD::FDIV, MVT::f16, Custom);
611 
612     // F16 - VOP3 Actions.
613     setOperationAction(ISD::FMA, MVT::f16, Legal);
614     if (STI.hasMadF16())
615       setOperationAction(ISD::FMAD, MVT::f16, Legal);
616 
617     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
618       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
619         switch (Op) {
620         case ISD::LOAD:
621         case ISD::STORE:
622         case ISD::BUILD_VECTOR:
623         case ISD::BITCAST:
624         case ISD::EXTRACT_VECTOR_ELT:
625         case ISD::INSERT_VECTOR_ELT:
626         case ISD::INSERT_SUBVECTOR:
627         case ISD::EXTRACT_SUBVECTOR:
628         case ISD::SCALAR_TO_VECTOR:
629           break;
630         case ISD::CONCAT_VECTORS:
631           setOperationAction(Op, VT, Custom);
632           break;
633         default:
634           setOperationAction(Op, VT, Expand);
635           break;
636         }
637       }
638     }
639 
640     // v_perm_b32 can handle either of these.
641     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
642     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
644 
645     // XXX - Do these do anything? Vector constants turn into build_vector.
646     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
647     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
648 
649     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
650     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
651 
652     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
653     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
654     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
655     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
656 
657     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
658     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
659     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
660     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
661 
662     setOperationAction(ISD::AND, MVT::v2i16, Promote);
663     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
664     setOperationAction(ISD::OR, MVT::v2i16, Promote);
665     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
666     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
667     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
668 
669     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
670     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
671     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
672     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
673 
674     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
675     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
676     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
677     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
678 
679     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
680     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
682     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
683 
684     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
685     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
686     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
687 
688     if (!Subtarget->hasVOP3PInsts()) {
689       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
690       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
691     }
692 
693     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
694     // This isn't really legal, but this avoids the legalizer unrolling it (and
695     // allows matching fneg (fabs x) patterns)
696     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
697 
698     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
699     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
700     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
701     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
702 
703     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
704     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
705 
706     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
707     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
708   }
709 
710   if (Subtarget->hasVOP3PInsts()) {
711     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
712     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
713     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
714     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
716     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
717     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
718     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
719     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
720     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
721 
722     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
723     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
725     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
726 
727     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
728     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
729     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
730 
731     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
732     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
733 
734     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
735 
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
737     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
738 
739     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
740     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
741 
742     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
743     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
744     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
745     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
746     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
747     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
748 
749     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
750     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
751     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
752     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
753 
754     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
755     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
757     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
758 
759     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
760     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
761     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
762 
763     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
764     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
765 
766     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
767     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
768     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
769 
770     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
771     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
772     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
773   }
774 
775   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
776   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
777 
778   if (Subtarget->has16BitInsts()) {
779     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
780     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
781     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
782     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
783   } else {
784     // Legalization hack.
785     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
786     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
787 
788     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
789     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
790   }
791 
792   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
793     setOperationAction(ISD::SELECT, VT, Custom);
794   }
795 
796   setOperationAction(ISD::SMULO, MVT::i64, Custom);
797   setOperationAction(ISD::UMULO, MVT::i64, Custom);
798 
799   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
800   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
801   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
802   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
803   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
804   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
805   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
806 
807   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
808   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
809   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
810   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
811   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
812   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
813   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
814   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
815   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
816   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
817   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
818 
819   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
820   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
821   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
822   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
823   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
824   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
825   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
826   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
827   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
828   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
829 
830   setTargetDAGCombine(ISD::ADD);
831   setTargetDAGCombine(ISD::ADDCARRY);
832   setTargetDAGCombine(ISD::SUB);
833   setTargetDAGCombine(ISD::SUBCARRY);
834   setTargetDAGCombine(ISD::FADD);
835   setTargetDAGCombine(ISD::FSUB);
836   setTargetDAGCombine(ISD::FMINNUM);
837   setTargetDAGCombine(ISD::FMAXNUM);
838   setTargetDAGCombine(ISD::FMINNUM_IEEE);
839   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
840   setTargetDAGCombine(ISD::FMA);
841   setTargetDAGCombine(ISD::SMIN);
842   setTargetDAGCombine(ISD::SMAX);
843   setTargetDAGCombine(ISD::UMIN);
844   setTargetDAGCombine(ISD::UMAX);
845   setTargetDAGCombine(ISD::SETCC);
846   setTargetDAGCombine(ISD::AND);
847   setTargetDAGCombine(ISD::OR);
848   setTargetDAGCombine(ISD::XOR);
849   setTargetDAGCombine(ISD::SINT_TO_FP);
850   setTargetDAGCombine(ISD::UINT_TO_FP);
851   setTargetDAGCombine(ISD::FCANONICALIZE);
852   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
853   setTargetDAGCombine(ISD::ZERO_EXTEND);
854   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
855   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
856   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
857 
858   // All memory operations. Some folding on the pointer operand is done to help
859   // matching the constant offsets in the addressing modes.
860   setTargetDAGCombine(ISD::LOAD);
861   setTargetDAGCombine(ISD::STORE);
862   setTargetDAGCombine(ISD::ATOMIC_LOAD);
863   setTargetDAGCombine(ISD::ATOMIC_STORE);
864   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
865   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
866   setTargetDAGCombine(ISD::ATOMIC_SWAP);
867   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
868   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
869   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
870   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
871   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
872   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
873   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
874   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
875   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
876   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
877   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
878   setTargetDAGCombine(ISD::INTRINSIC_VOID);
879   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
880 
881   // FIXME: In other contexts we pretend this is a per-function property.
882   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
883 
884   setSchedulingPreference(Sched::RegPressure);
885 }
886 
getSubtarget() const887 const GCNSubtarget *SITargetLowering::getSubtarget() const {
888   return Subtarget;
889 }
890 
891 //===----------------------------------------------------------------------===//
892 // TargetLowering queries
893 //===----------------------------------------------------------------------===//
894 
895 // v_mad_mix* support a conversion from f16 to f32.
896 //
897 // There is only one special case when denormals are enabled we don't currently,
898 // where this is OK to use.
isFPExtFoldable(const SelectionDAG & DAG,unsigned Opcode,EVT DestVT,EVT SrcVT) const899 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
900                                        EVT DestVT, EVT SrcVT) const {
901   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
902           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
903     DestVT.getScalarType() == MVT::f32 &&
904     SrcVT.getScalarType() == MVT::f16 &&
905     // TODO: This probably only requires no input flushing?
906     !hasFP32Denormals(DAG.getMachineFunction());
907 }
908 
isShuffleMaskLegal(ArrayRef<int>,EVT) const909 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
910   // SI has some legal vector types, but no legal vector operations. Say no
911   // shuffles are legal in order to prefer scalarizing some vector operations.
912   return false;
913 }
914 
getRegisterTypeForCallingConv(LLVMContext & Context,CallingConv::ID CC,EVT VT) const915 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
916                                                     CallingConv::ID CC,
917                                                     EVT VT) const {
918   if (CC == CallingConv::AMDGPU_KERNEL)
919     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
920 
921   if (VT.isVector()) {
922     EVT ScalarVT = VT.getScalarType();
923     unsigned Size = ScalarVT.getSizeInBits();
924     if (Size == 16) {
925       if (Subtarget->has16BitInsts())
926         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
927       return VT.isInteger() ? MVT::i32 : MVT::f32;
928     }
929 
930     if (Size < 16)
931       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
932     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
933   }
934 
935   if (VT.getSizeInBits() > 32)
936     return MVT::i32;
937 
938   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
939 }
940 
getNumRegistersForCallingConv(LLVMContext & Context,CallingConv::ID CC,EVT VT) const941 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
942                                                          CallingConv::ID CC,
943                                                          EVT VT) const {
944   if (CC == CallingConv::AMDGPU_KERNEL)
945     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
946 
947   if (VT.isVector()) {
948     unsigned NumElts = VT.getVectorNumElements();
949     EVT ScalarVT = VT.getScalarType();
950     unsigned Size = ScalarVT.getSizeInBits();
951 
952     // FIXME: Should probably promote 8-bit vectors to i16.
953     if (Size == 16 && Subtarget->has16BitInsts())
954       return (NumElts + 1) / 2;
955 
956     if (Size <= 32)
957       return NumElts;
958 
959     if (Size > 32)
960       return NumElts * ((Size + 31) / 32);
961   } else if (VT.getSizeInBits() > 32)
962     return (VT.getSizeInBits() + 31) / 32;
963 
964   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
965 }
966 
getVectorTypeBreakdownForCallingConv(LLVMContext & Context,CallingConv::ID CC,EVT VT,EVT & IntermediateVT,unsigned & NumIntermediates,MVT & RegisterVT) const967 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
968   LLVMContext &Context, CallingConv::ID CC,
969   EVT VT, EVT &IntermediateVT,
970   unsigned &NumIntermediates, MVT &RegisterVT) const {
971   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
972     unsigned NumElts = VT.getVectorNumElements();
973     EVT ScalarVT = VT.getScalarType();
974     unsigned Size = ScalarVT.getSizeInBits();
975     // FIXME: We should fix the ABI to be the same on targets without 16-bit
976     // support, but unless we can properly handle 3-vectors, it will be still be
977     // inconsistent.
978     if (Size == 16 && Subtarget->has16BitInsts()) {
979       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
980       IntermediateVT = RegisterVT;
981       NumIntermediates = (NumElts + 1) / 2;
982       return NumIntermediates;
983     }
984 
985     if (Size == 32) {
986       RegisterVT = ScalarVT.getSimpleVT();
987       IntermediateVT = RegisterVT;
988       NumIntermediates = NumElts;
989       return NumIntermediates;
990     }
991 
992     if (Size < 16 && Subtarget->has16BitInsts()) {
993       // FIXME: Should probably form v2i16 pieces
994       RegisterVT = MVT::i16;
995       IntermediateVT = ScalarVT;
996       NumIntermediates = NumElts;
997       return NumIntermediates;
998     }
999 
1000 
1001     if (Size != 16 && Size <= 32) {
1002       RegisterVT = MVT::i32;
1003       IntermediateVT = ScalarVT;
1004       NumIntermediates = NumElts;
1005       return NumIntermediates;
1006     }
1007 
1008     if (Size > 32) {
1009       RegisterVT = MVT::i32;
1010       IntermediateVT = RegisterVT;
1011       NumIntermediates = NumElts * ((Size + 31) / 32);
1012       return NumIntermediates;
1013     }
1014   }
1015 
1016   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1017     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1018 }
1019 
memVTFromImageData(Type * Ty,unsigned DMaskLanes)1020 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1021   assert(DMaskLanes != 0);
1022 
1023   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1024     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1025     return EVT::getVectorVT(Ty->getContext(),
1026                             EVT::getEVT(VT->getElementType()),
1027                             NumElts);
1028   }
1029 
1030   return EVT::getEVT(Ty);
1031 }
1032 
1033 // Peek through TFE struct returns to only use the data size.
memVTFromImageReturn(Type * Ty,unsigned DMaskLanes)1034 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1035   auto *ST = dyn_cast<StructType>(Ty);
1036   if (!ST)
1037     return memVTFromImageData(Ty, DMaskLanes);
1038 
1039   // Some intrinsics return an aggregate type - special case to work out the
1040   // correct memVT.
1041   //
1042   // Only limited forms of aggregate type currently expected.
1043   if (ST->getNumContainedTypes() != 2 ||
1044       !ST->getContainedType(1)->isIntegerTy(32))
1045     return EVT();
1046   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1047 }
1048 
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & CI,MachineFunction & MF,unsigned IntrID) const1049 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1050                                           const CallInst &CI,
1051                                           MachineFunction &MF,
1052                                           unsigned IntrID) const {
1053   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1054           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1055     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1056                                                   (Intrinsic::ID)IntrID);
1057     if (Attr.hasFnAttribute(Attribute::ReadNone))
1058       return false;
1059 
1060     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1061 
1062     if (RsrcIntr->IsImage) {
1063       Info.ptrVal = MFI->getImagePSV(
1064         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1065         CI.getArgOperand(RsrcIntr->RsrcArg));
1066       Info.align.reset();
1067     } else {
1068       Info.ptrVal = MFI->getBufferPSV(
1069         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1070         CI.getArgOperand(RsrcIntr->RsrcArg));
1071     }
1072 
1073     Info.flags = MachineMemOperand::MODereferenceable;
1074     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1075       unsigned DMaskLanes = 4;
1076 
1077       if (RsrcIntr->IsImage) {
1078         const AMDGPU::ImageDimIntrinsicInfo *Intr
1079           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1080         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1081           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1082 
1083         if (!BaseOpcode->Gather4) {
1084           // If this isn't a gather, we may have excess loaded elements in the
1085           // IR type. Check the dmask for the real number of elements loaded.
1086           unsigned DMask
1087             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1088           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1089         }
1090 
1091         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1092       } else
1093         Info.memVT = EVT::getEVT(CI.getType());
1094 
1095       // FIXME: What does alignment mean for an image?
1096       Info.opc = ISD::INTRINSIC_W_CHAIN;
1097       Info.flags |= MachineMemOperand::MOLoad;
1098     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1099       Info.opc = ISD::INTRINSIC_VOID;
1100 
1101       Type *DataTy = CI.getArgOperand(0)->getType();
1102       if (RsrcIntr->IsImage) {
1103         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1104         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1105         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1106       } else
1107         Info.memVT = EVT::getEVT(DataTy);
1108 
1109       Info.flags |= MachineMemOperand::MOStore;
1110     } else {
1111       // Atomic
1112       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1113                                             ISD::INTRINSIC_W_CHAIN;
1114       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1115       Info.flags = MachineMemOperand::MOLoad |
1116                    MachineMemOperand::MOStore |
1117                    MachineMemOperand::MODereferenceable;
1118 
1119       // XXX - Should this be volatile without known ordering?
1120       Info.flags |= MachineMemOperand::MOVolatile;
1121     }
1122     return true;
1123   }
1124 
1125   switch (IntrID) {
1126   case Intrinsic::amdgcn_atomic_inc:
1127   case Intrinsic::amdgcn_atomic_dec:
1128   case Intrinsic::amdgcn_ds_ordered_add:
1129   case Intrinsic::amdgcn_ds_ordered_swap:
1130   case Intrinsic::amdgcn_ds_fadd:
1131   case Intrinsic::amdgcn_ds_fmin:
1132   case Intrinsic::amdgcn_ds_fmax: {
1133     Info.opc = ISD::INTRINSIC_W_CHAIN;
1134     Info.memVT = MVT::getVT(CI.getType());
1135     Info.ptrVal = CI.getOperand(0);
1136     Info.align.reset();
1137     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1138 
1139     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1140     if (!Vol->isZero())
1141       Info.flags |= MachineMemOperand::MOVolatile;
1142 
1143     return true;
1144   }
1145   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1146     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1147 
1148     Info.opc = ISD::INTRINSIC_W_CHAIN;
1149     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1150     Info.ptrVal = MFI->getBufferPSV(
1151       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1152       CI.getArgOperand(1));
1153     Info.align.reset();
1154     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1155 
1156     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1157     if (!Vol || !Vol->isZero())
1158       Info.flags |= MachineMemOperand::MOVolatile;
1159 
1160     return true;
1161   }
1162   case Intrinsic::amdgcn_ds_append:
1163   case Intrinsic::amdgcn_ds_consume: {
1164     Info.opc = ISD::INTRINSIC_W_CHAIN;
1165     Info.memVT = MVT::getVT(CI.getType());
1166     Info.ptrVal = CI.getOperand(0);
1167     Info.align.reset();
1168     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1169 
1170     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1171     if (!Vol->isZero())
1172       Info.flags |= MachineMemOperand::MOVolatile;
1173 
1174     return true;
1175   }
1176   case Intrinsic::amdgcn_global_atomic_csub: {
1177     Info.opc = ISD::INTRINSIC_W_CHAIN;
1178     Info.memVT = MVT::getVT(CI.getType());
1179     Info.ptrVal = CI.getOperand(0);
1180     Info.align.reset();
1181     Info.flags = MachineMemOperand::MOLoad |
1182                  MachineMemOperand::MOStore |
1183                  MachineMemOperand::MOVolatile;
1184     return true;
1185   }
1186   case Intrinsic::amdgcn_global_atomic_fadd: {
1187     Info.opc = ISD::INTRINSIC_W_CHAIN;
1188     Info.memVT = MVT::getVT(CI.getType());
1189     Info.ptrVal = CI.getOperand(0);
1190     Info.align.reset();
1191     Info.flags = MachineMemOperand::MOLoad |
1192                  MachineMemOperand::MOStore |
1193                  MachineMemOperand::MODereferenceable |
1194                  MachineMemOperand::MOVolatile;
1195     return true;
1196   }
1197   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1198     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1199     Info.opc = ISD::INTRINSIC_W_CHAIN;
1200     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1201     Info.ptrVal = MFI->getImagePSV(
1202         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), CI.getArgOperand(5));
1203     Info.align.reset();
1204     Info.flags = MachineMemOperand::MOLoad |
1205                  MachineMemOperand::MODereferenceable;
1206     return true;
1207   }
1208   case Intrinsic::amdgcn_ds_gws_init:
1209   case Intrinsic::amdgcn_ds_gws_barrier:
1210   case Intrinsic::amdgcn_ds_gws_sema_v:
1211   case Intrinsic::amdgcn_ds_gws_sema_br:
1212   case Intrinsic::amdgcn_ds_gws_sema_p:
1213   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1214     Info.opc = ISD::INTRINSIC_VOID;
1215 
1216     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1217     Info.ptrVal =
1218         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1219 
1220     // This is an abstract access, but we need to specify a type and size.
1221     Info.memVT = MVT::i32;
1222     Info.size = 4;
1223     Info.align = Align(4);
1224 
1225     Info.flags = MachineMemOperand::MOStore;
1226     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1227       Info.flags = MachineMemOperand::MOLoad;
1228     return true;
1229   }
1230   default:
1231     return false;
1232   }
1233 }
1234 
getAddrModeArguments(IntrinsicInst * II,SmallVectorImpl<Value * > & Ops,Type * & AccessTy) const1235 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1236                                             SmallVectorImpl<Value*> &Ops,
1237                                             Type *&AccessTy) const {
1238   switch (II->getIntrinsicID()) {
1239   case Intrinsic::amdgcn_atomic_inc:
1240   case Intrinsic::amdgcn_atomic_dec:
1241   case Intrinsic::amdgcn_ds_ordered_add:
1242   case Intrinsic::amdgcn_ds_ordered_swap:
1243   case Intrinsic::amdgcn_ds_append:
1244   case Intrinsic::amdgcn_ds_consume:
1245   case Intrinsic::amdgcn_ds_fadd:
1246   case Intrinsic::amdgcn_ds_fmin:
1247   case Intrinsic::amdgcn_ds_fmax:
1248   case Intrinsic::amdgcn_global_atomic_fadd:
1249   case Intrinsic::amdgcn_global_atomic_csub: {
1250     Value *Ptr = II->getArgOperand(0);
1251     AccessTy = II->getType();
1252     Ops.push_back(Ptr);
1253     return true;
1254   }
1255   default:
1256     return false;
1257   }
1258 }
1259 
isLegalFlatAddressingMode(const AddrMode & AM) const1260 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1261   if (!Subtarget->hasFlatInstOffsets()) {
1262     // Flat instructions do not have offsets, and only have the register
1263     // address.
1264     return AM.BaseOffs == 0 && AM.Scale == 0;
1265   }
1266 
1267   return AM.Scale == 0 &&
1268          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1269                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1270                                   /*Signed=*/false));
1271 }
1272 
isLegalGlobalAddressingMode(const AddrMode & AM) const1273 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1274   if (Subtarget->hasFlatGlobalInsts())
1275     return AM.Scale == 0 &&
1276            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1277                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1278                                     /*Signed=*/true));
1279 
1280   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1281       // Assume the we will use FLAT for all global memory accesses
1282       // on VI.
1283       // FIXME: This assumption is currently wrong.  On VI we still use
1284       // MUBUF instructions for the r + i addressing mode.  As currently
1285       // implemented, the MUBUF instructions only work on buffer < 4GB.
1286       // It may be possible to support > 4GB buffers with MUBUF instructions,
1287       // by setting the stride value in the resource descriptor which would
1288       // increase the size limit to (stride * 4GB).  However, this is risky,
1289       // because it has never been validated.
1290     return isLegalFlatAddressingMode(AM);
1291   }
1292 
1293   return isLegalMUBUFAddressingMode(AM);
1294 }
1295 
isLegalMUBUFAddressingMode(const AddrMode & AM) const1296 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1297   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1298   // additionally can do r + r + i with addr64. 32-bit has more addressing
1299   // mode options. Depending on the resource constant, it can also do
1300   // (i64 r0) + (i32 r1) * (i14 i).
1301   //
1302   // Private arrays end up using a scratch buffer most of the time, so also
1303   // assume those use MUBUF instructions. Scratch loads / stores are currently
1304   // implemented as mubuf instructions with offen bit set, so slightly
1305   // different than the normal addr64.
1306   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1307     return false;
1308 
1309   // FIXME: Since we can split immediate into soffset and immediate offset,
1310   // would it make sense to allow any immediate?
1311 
1312   switch (AM.Scale) {
1313   case 0: // r + i or just i, depending on HasBaseReg.
1314     return true;
1315   case 1:
1316     return true; // We have r + r or r + i.
1317   case 2:
1318     if (AM.HasBaseReg) {
1319       // Reject 2 * r + r.
1320       return false;
1321     }
1322 
1323     // Allow 2 * r as r + r
1324     // Or  2 * r + i is allowed as r + r + i.
1325     return true;
1326   default: // Don't allow n * r
1327     return false;
1328   }
1329 }
1330 
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS,Instruction * I) const1331 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1332                                              const AddrMode &AM, Type *Ty,
1333                                              unsigned AS, Instruction *I) const {
1334   // No global is ever allowed as a base.
1335   if (AM.BaseGV)
1336     return false;
1337 
1338   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1339     return isLegalGlobalAddressingMode(AM);
1340 
1341   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1342       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1343       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1344     // If the offset isn't a multiple of 4, it probably isn't going to be
1345     // correctly aligned.
1346     // FIXME: Can we get the real alignment here?
1347     if (AM.BaseOffs % 4 != 0)
1348       return isLegalMUBUFAddressingMode(AM);
1349 
1350     // There are no SMRD extloads, so if we have to do a small type access we
1351     // will use a MUBUF load.
1352     // FIXME?: We also need to do this if unaligned, but we don't know the
1353     // alignment here.
1354     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1355       return isLegalGlobalAddressingMode(AM);
1356 
1357     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1358       // SMRD instructions have an 8-bit, dword offset on SI.
1359       if (!isUInt<8>(AM.BaseOffs / 4))
1360         return false;
1361     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1362       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1363       // in 8-bits, it can use a smaller encoding.
1364       if (!isUInt<32>(AM.BaseOffs / 4))
1365         return false;
1366     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1367       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1368       if (!isUInt<20>(AM.BaseOffs))
1369         return false;
1370     } else
1371       llvm_unreachable("unhandled generation");
1372 
1373     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1374       return true;
1375 
1376     if (AM.Scale == 1 && AM.HasBaseReg)
1377       return true;
1378 
1379     return false;
1380 
1381   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1382     return isLegalMUBUFAddressingMode(AM);
1383   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1384              AS == AMDGPUAS::REGION_ADDRESS) {
1385     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1386     // field.
1387     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1388     // an 8-bit dword offset but we don't know the alignment here.
1389     if (!isUInt<16>(AM.BaseOffs))
1390       return false;
1391 
1392     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1393       return true;
1394 
1395     if (AM.Scale == 1 && AM.HasBaseReg)
1396       return true;
1397 
1398     return false;
1399   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1400              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1401     // For an unknown address space, this usually means that this is for some
1402     // reason being used for pure arithmetic, and not based on some addressing
1403     // computation. We don't have instructions that compute pointers with any
1404     // addressing modes, so treat them as having no offset like flat
1405     // instructions.
1406     return isLegalFlatAddressingMode(AM);
1407   }
1408 
1409   // Assume a user alias of global for unknown address spaces.
1410   return isLegalGlobalAddressingMode(AM);
1411 }
1412 
canMergeStoresTo(unsigned AS,EVT MemVT,const SelectionDAG & DAG) const1413 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1414                                         const SelectionDAG &DAG) const {
1415   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1416     return (MemVT.getSizeInBits() <= 4 * 32);
1417   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1418     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1419     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1420   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1421     return (MemVT.getSizeInBits() <= 2 * 32);
1422   }
1423   return true;
1424 }
1425 
allowsMisalignedMemoryAccessesImpl(unsigned Size,unsigned AddrSpace,Align Alignment,MachineMemOperand::Flags Flags,bool * IsFast) const1426 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1427     unsigned Size, unsigned AddrSpace, Align Alignment,
1428     MachineMemOperand::Flags Flags, bool *IsFast) const {
1429   if (IsFast)
1430     *IsFast = false;
1431 
1432   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1433       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1434     // Check if alignment requirements for ds_read/write instructions are
1435     // disabled.
1436     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1437         !Subtarget->hasLDSMisalignedBug()) {
1438       if (IsFast)
1439         *IsFast = Alignment != Align(2);
1440       return true;
1441     }
1442 
1443     if (Size == 64) {
1444       // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1445       // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1446       // with adjacent offsets.
1447       bool AlignedBy4 = Alignment >= Align(4);
1448       if (IsFast)
1449         *IsFast = AlignedBy4;
1450 
1451       return AlignedBy4;
1452     }
1453     if (Size == 96) {
1454       // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1455       bool Aligned = Alignment >= Align(16);
1456       if (IsFast)
1457         *IsFast = Aligned;
1458 
1459       return Aligned;
1460     }
1461     if (Size == 128) {
1462       // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1463       // can do a 8 byte aligned, 16 byte access in a single operation using
1464       // ds_read2/write2_b64.
1465       bool Aligned = Alignment >= Align(8);
1466       if (IsFast)
1467         *IsFast = Aligned;
1468 
1469       return Aligned;
1470     }
1471   }
1472 
1473   // FIXME: We have to be conservative here and assume that flat operations
1474   // will access scratch.  If we had access to the IR function, then we
1475   // could determine if any private memory was used in the function.
1476   if (!Subtarget->hasUnalignedScratchAccess() &&
1477       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1478        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1479     bool AlignedBy4 = Alignment >= Align(4);
1480     if (IsFast)
1481       *IsFast = AlignedBy4;
1482 
1483     return AlignedBy4;
1484   }
1485 
1486   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1487       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1488         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1489     // If we have an uniform constant load, it still requires using a slow
1490     // buffer instruction if unaligned.
1491     if (IsFast) {
1492       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1493       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1494       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1495                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1496         Alignment >= Align(4) : Alignment != Align(2);
1497     }
1498 
1499     return true;
1500   }
1501 
1502   // Smaller than dword value must be aligned.
1503   if (Size < 32)
1504     return false;
1505 
1506   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1507   // byte-address are ignored, thus forcing Dword alignment.
1508   // This applies to private, global, and constant memory.
1509   if (IsFast)
1510     *IsFast = true;
1511 
1512   return Size >= 32 && Alignment >= Align(4);
1513 }
1514 
allowsMisalignedMemoryAccesses(EVT VT,unsigned AddrSpace,unsigned Alignment,MachineMemOperand::Flags Flags,bool * IsFast) const1515 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1516     EVT VT, unsigned AddrSpace, unsigned Alignment,
1517     MachineMemOperand::Flags Flags, bool *IsFast) const {
1518   if (IsFast)
1519     *IsFast = false;
1520 
1521   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1522   // which isn't a simple VT.
1523   // Until MVT is extended to handle this, simply check for the size and
1524   // rely on the condition below: allow accesses if the size is a multiple of 4.
1525   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1526                            VT.getStoreSize() > 16)) {
1527     return false;
1528   }
1529 
1530   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1531                                             Align(Alignment), Flags, IsFast);
1532 }
1533 
getOptimalMemOpType(const MemOp & Op,const AttributeList & FuncAttributes) const1534 EVT SITargetLowering::getOptimalMemOpType(
1535     const MemOp &Op, const AttributeList &FuncAttributes) const {
1536   // FIXME: Should account for address space here.
1537 
1538   // The default fallback uses the private pointer size as a guess for a type to
1539   // use. Make sure we switch these to 64-bit accesses.
1540 
1541   if (Op.size() >= 16 &&
1542       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1543     return MVT::v4i32;
1544 
1545   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1546     return MVT::v2i32;
1547 
1548   // Use the default.
1549   return MVT::Other;
1550 }
1551 
isMemOpHasNoClobberedMemOperand(const SDNode * N) const1552 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1553   const MemSDNode *MemNode = cast<MemSDNode>(N);
1554   const Value *Ptr = MemNode->getMemOperand()->getValue();
1555   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1556   return I && I->getMetadata("amdgpu.noclobber");
1557 }
1558 
isFreeAddrSpaceCast(unsigned SrcAS,unsigned DestAS) const1559 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1560                                            unsigned DestAS) const {
1561   // Flat -> private/local is a simple truncate.
1562   // Flat -> global is no-op
1563   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1564     return true;
1565 
1566   const GCNTargetMachine &TM =
1567       static_cast<const GCNTargetMachine &>(getTargetMachine());
1568   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1569 }
1570 
isMemOpUniform(const SDNode * N) const1571 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1572   const MemSDNode *MemNode = cast<MemSDNode>(N);
1573 
1574   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1575 }
1576 
1577 TargetLoweringBase::LegalizeTypeAction
getPreferredVectorAction(MVT VT) const1578 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1579   int NumElts = VT.getVectorNumElements();
1580   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1581     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1582   return TargetLoweringBase::getPreferredVectorAction(VT);
1583 }
1584 
shouldConvertConstantLoadToIntImm(const APInt & Imm,Type * Ty) const1585 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1586                                                          Type *Ty) const {
1587   // FIXME: Could be smarter if called for vector constants.
1588   return true;
1589 }
1590 
isTypeDesirableForOp(unsigned Op,EVT VT) const1591 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1592   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1593     switch (Op) {
1594     case ISD::LOAD:
1595     case ISD::STORE:
1596 
1597     // These operations are done with 32-bit instructions anyway.
1598     case ISD::AND:
1599     case ISD::OR:
1600     case ISD::XOR:
1601     case ISD::SELECT:
1602       // TODO: Extensions?
1603       return true;
1604     default:
1605       return false;
1606     }
1607   }
1608 
1609   // SimplifySetCC uses this function to determine whether or not it should
1610   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1611   if (VT == MVT::i1 && Op == ISD::SETCC)
1612     return false;
1613 
1614   return TargetLowering::isTypeDesirableForOp(Op, VT);
1615 }
1616 
lowerKernArgParameterPtr(SelectionDAG & DAG,const SDLoc & SL,SDValue Chain,uint64_t Offset) const1617 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1618                                                    const SDLoc &SL,
1619                                                    SDValue Chain,
1620                                                    uint64_t Offset) const {
1621   const DataLayout &DL = DAG.getDataLayout();
1622   MachineFunction &MF = DAG.getMachineFunction();
1623   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1624 
1625   const ArgDescriptor *InputPtrReg;
1626   const TargetRegisterClass *RC;
1627   LLT ArgTy;
1628 
1629   std::tie(InputPtrReg, RC, ArgTy) =
1630       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1631 
1632   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1633   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1634   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1635     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1636 
1637   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1638 }
1639 
getImplicitArgPtr(SelectionDAG & DAG,const SDLoc & SL) const1640 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1641                                             const SDLoc &SL) const {
1642   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1643                                                FIRST_IMPLICIT);
1644   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1645 }
1646 
convertArgType(SelectionDAG & DAG,EVT VT,EVT MemVT,const SDLoc & SL,SDValue Val,bool Signed,const ISD::InputArg * Arg) const1647 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1648                                          const SDLoc &SL, SDValue Val,
1649                                          bool Signed,
1650                                          const ISD::InputArg *Arg) const {
1651   // First, if it is a widened vector, narrow it.
1652   if (VT.isVector() &&
1653       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1654     EVT NarrowedVT =
1655         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1656                          VT.getVectorNumElements());
1657     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1658                       DAG.getConstant(0, SL, MVT::i32));
1659   }
1660 
1661   // Then convert the vector elements or scalar value.
1662   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1663       VT.bitsLT(MemVT)) {
1664     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1665     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1666   }
1667 
1668   if (MemVT.isFloatingPoint())
1669     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1670   else if (Signed)
1671     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1672   else
1673     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1674 
1675   return Val;
1676 }
1677 
lowerKernargMemParameter(SelectionDAG & DAG,EVT VT,EVT MemVT,const SDLoc & SL,SDValue Chain,uint64_t Offset,Align Alignment,bool Signed,const ISD::InputArg * Arg) const1678 SDValue SITargetLowering::lowerKernargMemParameter(
1679     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1680     uint64_t Offset, Align Alignment, bool Signed,
1681     const ISD::InputArg *Arg) const {
1682   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1683 
1684   // Try to avoid using an extload by loading earlier than the argument address,
1685   // and extracting the relevant bits. The load should hopefully be merged with
1686   // the previous argument.
1687   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1688     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1689     int64_t AlignDownOffset = alignDown(Offset, 4);
1690     int64_t OffsetDiff = Offset - AlignDownOffset;
1691 
1692     EVT IntVT = MemVT.changeTypeToInteger();
1693 
1694     // TODO: If we passed in the base kernel offset we could have a better
1695     // alignment than 4, but we don't really need it.
1696     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1697     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1698                                MachineMemOperand::MODereferenceable |
1699                                    MachineMemOperand::MOInvariant);
1700 
1701     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1702     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1703 
1704     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1705     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1706     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1707 
1708 
1709     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1710   }
1711 
1712   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1713   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1714                              MachineMemOperand::MODereferenceable |
1715                                  MachineMemOperand::MOInvariant);
1716 
1717   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1718   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1719 }
1720 
lowerStackParameter(SelectionDAG & DAG,CCValAssign & VA,const SDLoc & SL,SDValue Chain,const ISD::InputArg & Arg) const1721 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1722                                               const SDLoc &SL, SDValue Chain,
1723                                               const ISD::InputArg &Arg) const {
1724   MachineFunction &MF = DAG.getMachineFunction();
1725   MachineFrameInfo &MFI = MF.getFrameInfo();
1726 
1727   if (Arg.Flags.isByVal()) {
1728     unsigned Size = Arg.Flags.getByValSize();
1729     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1730     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1731   }
1732 
1733   unsigned ArgOffset = VA.getLocMemOffset();
1734   unsigned ArgSize = VA.getValVT().getStoreSize();
1735 
1736   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1737 
1738   // Create load nodes to retrieve arguments from the stack.
1739   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1740   SDValue ArgValue;
1741 
1742   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1743   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1744   MVT MemVT = VA.getValVT();
1745 
1746   switch (VA.getLocInfo()) {
1747   default:
1748     break;
1749   case CCValAssign::BCvt:
1750     MemVT = VA.getLocVT();
1751     break;
1752   case CCValAssign::SExt:
1753     ExtType = ISD::SEXTLOAD;
1754     break;
1755   case CCValAssign::ZExt:
1756     ExtType = ISD::ZEXTLOAD;
1757     break;
1758   case CCValAssign::AExt:
1759     ExtType = ISD::EXTLOAD;
1760     break;
1761   }
1762 
1763   ArgValue = DAG.getExtLoad(
1764     ExtType, SL, VA.getLocVT(), Chain, FIN,
1765     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1766     MemVT);
1767   return ArgValue;
1768 }
1769 
getPreloadedValue(SelectionDAG & DAG,const SIMachineFunctionInfo & MFI,EVT VT,AMDGPUFunctionArgInfo::PreloadedValue PVID) const1770 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1771   const SIMachineFunctionInfo &MFI,
1772   EVT VT,
1773   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1774   const ArgDescriptor *Reg;
1775   const TargetRegisterClass *RC;
1776   LLT Ty;
1777 
1778   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1779   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1780 }
1781 
processPSInputArgs(SmallVectorImpl<ISD::InputArg> & Splits,CallingConv::ID CallConv,ArrayRef<ISD::InputArg> Ins,BitVector & Skipped,FunctionType * FType,SIMachineFunctionInfo * Info)1782 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1783                                CallingConv::ID CallConv,
1784                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1785                                FunctionType *FType,
1786                                SIMachineFunctionInfo *Info) {
1787   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1788     const ISD::InputArg *Arg = &Ins[I];
1789 
1790     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1791            "vector type argument should have been split");
1792 
1793     // First check if it's a PS input addr.
1794     if (CallConv == CallingConv::AMDGPU_PS &&
1795         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1796       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1797 
1798       // Inconveniently only the first part of the split is marked as isSplit,
1799       // so skip to the end. We only want to increment PSInputNum once for the
1800       // entire split argument.
1801       if (Arg->Flags.isSplit()) {
1802         while (!Arg->Flags.isSplitEnd()) {
1803           assert((!Arg->VT.isVector() ||
1804                   Arg->VT.getScalarSizeInBits() == 16) &&
1805                  "unexpected vector split in ps argument type");
1806           if (!SkipArg)
1807             Splits.push_back(*Arg);
1808           Arg = &Ins[++I];
1809         }
1810       }
1811 
1812       if (SkipArg) {
1813         // We can safely skip PS inputs.
1814         Skipped.set(Arg->getOrigArgIndex());
1815         ++PSInputNum;
1816         continue;
1817       }
1818 
1819       Info->markPSInputAllocated(PSInputNum);
1820       if (Arg->Used)
1821         Info->markPSInputEnabled(PSInputNum);
1822 
1823       ++PSInputNum;
1824     }
1825 
1826     Splits.push_back(*Arg);
1827   }
1828 }
1829 
1830 // Allocate special inputs passed in VGPRs.
allocateSpecialEntryInputVGPRs(CCState & CCInfo,MachineFunction & MF,const SIRegisterInfo & TRI,SIMachineFunctionInfo & Info) const1831 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1832                                                       MachineFunction &MF,
1833                                                       const SIRegisterInfo &TRI,
1834                                                       SIMachineFunctionInfo &Info) const {
1835   const LLT S32 = LLT::scalar(32);
1836   MachineRegisterInfo &MRI = MF.getRegInfo();
1837 
1838   if (Info.hasWorkItemIDX()) {
1839     Register Reg = AMDGPU::VGPR0;
1840     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1841 
1842     CCInfo.AllocateReg(Reg);
1843     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1844   }
1845 
1846   if (Info.hasWorkItemIDY()) {
1847     Register Reg = AMDGPU::VGPR1;
1848     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1849 
1850     CCInfo.AllocateReg(Reg);
1851     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1852   }
1853 
1854   if (Info.hasWorkItemIDZ()) {
1855     Register Reg = AMDGPU::VGPR2;
1856     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1857 
1858     CCInfo.AllocateReg(Reg);
1859     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1860   }
1861 }
1862 
1863 // Try to allocate a VGPR at the end of the argument list, or if no argument
1864 // VGPRs are left allocating a stack slot.
1865 // If \p Mask is is given it indicates bitfield position in the register.
1866 // If \p Arg is given use it with new ]p Mask instead of allocating new.
allocateVGPR32Input(CCState & CCInfo,unsigned Mask=~0u,ArgDescriptor Arg=ArgDescriptor ())1867 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1868                                          ArgDescriptor Arg = ArgDescriptor()) {
1869   if (Arg.isSet())
1870     return ArgDescriptor::createArg(Arg, Mask);
1871 
1872   ArrayRef<MCPhysReg> ArgVGPRs
1873     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1874   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1875   if (RegIdx == ArgVGPRs.size()) {
1876     // Spill to stack required.
1877     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1878 
1879     return ArgDescriptor::createStack(Offset, Mask);
1880   }
1881 
1882   unsigned Reg = ArgVGPRs[RegIdx];
1883   Reg = CCInfo.AllocateReg(Reg);
1884   assert(Reg != AMDGPU::NoRegister);
1885 
1886   MachineFunction &MF = CCInfo.getMachineFunction();
1887   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1888   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1889   return ArgDescriptor::createRegister(Reg, Mask);
1890 }
1891 
allocateSGPR32InputImpl(CCState & CCInfo,const TargetRegisterClass * RC,unsigned NumArgRegs)1892 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1893                                              const TargetRegisterClass *RC,
1894                                              unsigned NumArgRegs) {
1895   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1896   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1897   if (RegIdx == ArgSGPRs.size())
1898     report_fatal_error("ran out of SGPRs for arguments");
1899 
1900   unsigned Reg = ArgSGPRs[RegIdx];
1901   Reg = CCInfo.AllocateReg(Reg);
1902   assert(Reg != AMDGPU::NoRegister);
1903 
1904   MachineFunction &MF = CCInfo.getMachineFunction();
1905   MF.addLiveIn(Reg, RC);
1906   return ArgDescriptor::createRegister(Reg);
1907 }
1908 
allocateSGPR32Input(CCState & CCInfo)1909 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1910   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1911 }
1912 
allocateSGPR64Input(CCState & CCInfo)1913 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1914   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1915 }
1916 
1917 /// Allocate implicit function VGPR arguments at the end of allocated user
1918 /// arguments.
allocateSpecialInputVGPRs(CCState & CCInfo,MachineFunction & MF,const SIRegisterInfo & TRI,SIMachineFunctionInfo & Info) const1919 void SITargetLowering::allocateSpecialInputVGPRs(
1920   CCState &CCInfo, MachineFunction &MF,
1921   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1922   const unsigned Mask = 0x3ff;
1923   ArgDescriptor Arg;
1924 
1925   if (Info.hasWorkItemIDX()) {
1926     Arg = allocateVGPR32Input(CCInfo, Mask);
1927     Info.setWorkItemIDX(Arg);
1928   }
1929 
1930   if (Info.hasWorkItemIDY()) {
1931     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1932     Info.setWorkItemIDY(Arg);
1933   }
1934 
1935   if (Info.hasWorkItemIDZ())
1936     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1937 }
1938 
1939 /// Allocate implicit function VGPR arguments in fixed registers.
allocateSpecialInputVGPRsFixed(CCState & CCInfo,MachineFunction & MF,const SIRegisterInfo & TRI,SIMachineFunctionInfo & Info) const1940 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1941   CCState &CCInfo, MachineFunction &MF,
1942   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1943   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1944   if (!Reg)
1945     report_fatal_error("failed to allocated VGPR for implicit arguments");
1946 
1947   const unsigned Mask = 0x3ff;
1948   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1949   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1950   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1951 }
1952 
allocateSpecialInputSGPRs(CCState & CCInfo,MachineFunction & MF,const SIRegisterInfo & TRI,SIMachineFunctionInfo & Info) const1953 void SITargetLowering::allocateSpecialInputSGPRs(
1954   CCState &CCInfo,
1955   MachineFunction &MF,
1956   const SIRegisterInfo &TRI,
1957   SIMachineFunctionInfo &Info) const {
1958   auto &ArgInfo = Info.getArgInfo();
1959 
1960   // TODO: Unify handling with private memory pointers.
1961 
1962   if (Info.hasDispatchPtr())
1963     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1964 
1965   if (Info.hasQueuePtr())
1966     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1967 
1968   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1969   // constant offset from the kernarg segment.
1970   if (Info.hasImplicitArgPtr())
1971     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1972 
1973   if (Info.hasDispatchID())
1974     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1975 
1976   // flat_scratch_init is not applicable for non-kernel functions.
1977 
1978   if (Info.hasWorkGroupIDX())
1979     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1980 
1981   if (Info.hasWorkGroupIDY())
1982     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1983 
1984   if (Info.hasWorkGroupIDZ())
1985     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1986 }
1987 
1988 // Allocate special inputs passed in user SGPRs.
allocateHSAUserSGPRs(CCState & CCInfo,MachineFunction & MF,const SIRegisterInfo & TRI,SIMachineFunctionInfo & Info) const1989 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1990                                             MachineFunction &MF,
1991                                             const SIRegisterInfo &TRI,
1992                                             SIMachineFunctionInfo &Info) const {
1993   if (Info.hasImplicitBufferPtr()) {
1994     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1995     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1996     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1997   }
1998 
1999   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2000   if (Info.hasPrivateSegmentBuffer()) {
2001     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2002     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2003     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2004   }
2005 
2006   if (Info.hasDispatchPtr()) {
2007     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2008     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2009     CCInfo.AllocateReg(DispatchPtrReg);
2010   }
2011 
2012   if (Info.hasQueuePtr()) {
2013     Register QueuePtrReg = Info.addQueuePtr(TRI);
2014     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2015     CCInfo.AllocateReg(QueuePtrReg);
2016   }
2017 
2018   if (Info.hasKernargSegmentPtr()) {
2019     MachineRegisterInfo &MRI = MF.getRegInfo();
2020     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2021     CCInfo.AllocateReg(InputPtrReg);
2022 
2023     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2024     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2025   }
2026 
2027   if (Info.hasDispatchID()) {
2028     Register DispatchIDReg = Info.addDispatchID(TRI);
2029     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2030     CCInfo.AllocateReg(DispatchIDReg);
2031   }
2032 
2033   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2034     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2035     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2036     CCInfo.AllocateReg(FlatScratchInitReg);
2037   }
2038 
2039   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2040   // these from the dispatch pointer.
2041 }
2042 
2043 // Allocate special input registers that are initialized per-wave.
allocateSystemSGPRs(CCState & CCInfo,MachineFunction & MF,SIMachineFunctionInfo & Info,CallingConv::ID CallConv,bool IsShader) const2044 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2045                                            MachineFunction &MF,
2046                                            SIMachineFunctionInfo &Info,
2047                                            CallingConv::ID CallConv,
2048                                            bool IsShader) const {
2049   if (Info.hasWorkGroupIDX()) {
2050     Register Reg = Info.addWorkGroupIDX();
2051     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2052     CCInfo.AllocateReg(Reg);
2053   }
2054 
2055   if (Info.hasWorkGroupIDY()) {
2056     Register Reg = Info.addWorkGroupIDY();
2057     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2058     CCInfo.AllocateReg(Reg);
2059   }
2060 
2061   if (Info.hasWorkGroupIDZ()) {
2062     Register Reg = Info.addWorkGroupIDZ();
2063     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2064     CCInfo.AllocateReg(Reg);
2065   }
2066 
2067   if (Info.hasWorkGroupInfo()) {
2068     Register Reg = Info.addWorkGroupInfo();
2069     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2070     CCInfo.AllocateReg(Reg);
2071   }
2072 
2073   if (Info.hasPrivateSegmentWaveByteOffset()) {
2074     // Scratch wave offset passed in system SGPR.
2075     unsigned PrivateSegmentWaveByteOffsetReg;
2076 
2077     if (IsShader) {
2078       PrivateSegmentWaveByteOffsetReg =
2079         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2080 
2081       // This is true if the scratch wave byte offset doesn't have a fixed
2082       // location.
2083       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2084         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2085         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2086       }
2087     } else
2088       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2089 
2090     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2091     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2092   }
2093 }
2094 
reservePrivateMemoryRegs(const TargetMachine & TM,MachineFunction & MF,const SIRegisterInfo & TRI,SIMachineFunctionInfo & Info)2095 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2096                                      MachineFunction &MF,
2097                                      const SIRegisterInfo &TRI,
2098                                      SIMachineFunctionInfo &Info) {
2099   // Now that we've figured out where the scratch register inputs are, see if
2100   // should reserve the arguments and use them directly.
2101   MachineFrameInfo &MFI = MF.getFrameInfo();
2102   bool HasStackObjects = MFI.hasStackObjects();
2103   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2104 
2105   // Record that we know we have non-spill stack objects so we don't need to
2106   // check all stack objects later.
2107   if (HasStackObjects)
2108     Info.setHasNonSpillStackObjects(true);
2109 
2110   // Everything live out of a block is spilled with fast regalloc, so it's
2111   // almost certain that spilling will be required.
2112   if (TM.getOptLevel() == CodeGenOpt::None)
2113     HasStackObjects = true;
2114 
2115   // For now assume stack access is needed in any callee functions, so we need
2116   // the scratch registers to pass in.
2117   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2118 
2119   if (!ST.enableFlatScratch()) {
2120     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2121       // If we have stack objects, we unquestionably need the private buffer
2122       // resource. For the Code Object V2 ABI, this will be the first 4 user
2123       // SGPR inputs. We can reserve those and use them directly.
2124 
2125       Register PrivateSegmentBufferReg =
2126           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2127       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2128     } else {
2129       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2130       // We tentatively reserve the last registers (skipping the last registers
2131       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2132       // we'll replace these with the ones immediately after those which were
2133       // really allocated. In the prologue copies will be inserted from the
2134       // argument to these reserved registers.
2135 
2136       // Without HSA, relocations are used for the scratch pointer and the
2137       // buffer resource setup is always inserted in the prologue. Scratch wave
2138       // offset is still in an input SGPR.
2139       Info.setScratchRSrcReg(ReservedBufferReg);
2140     }
2141   }
2142 
2143   MachineRegisterInfo &MRI = MF.getRegInfo();
2144 
2145   // For entry functions we have to set up the stack pointer if we use it,
2146   // whereas non-entry functions get this "for free". This means there is no
2147   // intrinsic advantage to using S32 over S34 in cases where we do not have
2148   // calls but do need a frame pointer (i.e. if we are requested to have one
2149   // because frame pointer elimination is disabled). To keep things simple we
2150   // only ever use S32 as the call ABI stack pointer, and so using it does not
2151   // imply we need a separate frame pointer.
2152   //
2153   // Try to use s32 as the SP, but move it if it would interfere with input
2154   // arguments. This won't work with calls though.
2155   //
2156   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2157   // registers.
2158   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2159     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2160   } else {
2161     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2162 
2163     if (MFI.hasCalls())
2164       report_fatal_error("call in graphics shader with too many input SGPRs");
2165 
2166     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2167       if (!MRI.isLiveIn(Reg)) {
2168         Info.setStackPtrOffsetReg(Reg);
2169         break;
2170       }
2171     }
2172 
2173     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2174       report_fatal_error("failed to find register for SP");
2175   }
2176 
2177   // hasFP should be accurate for entry functions even before the frame is
2178   // finalized, because it does not rely on the known stack size, only
2179   // properties like whether variable sized objects are present.
2180   if (ST.getFrameLowering()->hasFP(MF)) {
2181     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2182   }
2183 }
2184 
supportSplitCSR(MachineFunction * MF) const2185 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2186   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2187   return !Info->isEntryFunction();
2188 }
2189 
initializeSplitCSR(MachineBasicBlock * Entry) const2190 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2191 
2192 }
2193 
insertCopiesSplitCSR(MachineBasicBlock * Entry,const SmallVectorImpl<MachineBasicBlock * > & Exits) const2194 void SITargetLowering::insertCopiesSplitCSR(
2195   MachineBasicBlock *Entry,
2196   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2197   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2198 
2199   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2200   if (!IStart)
2201     return;
2202 
2203   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2204   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2205   MachineBasicBlock::iterator MBBI = Entry->begin();
2206   for (const MCPhysReg *I = IStart; *I; ++I) {
2207     const TargetRegisterClass *RC = nullptr;
2208     if (AMDGPU::SReg_64RegClass.contains(*I))
2209       RC = &AMDGPU::SGPR_64RegClass;
2210     else if (AMDGPU::SReg_32RegClass.contains(*I))
2211       RC = &AMDGPU::SGPR_32RegClass;
2212     else
2213       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2214 
2215     Register NewVR = MRI->createVirtualRegister(RC);
2216     // Create copy from CSR to a virtual register.
2217     Entry->addLiveIn(*I);
2218     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2219       .addReg(*I);
2220 
2221     // Insert the copy-back instructions right before the terminator.
2222     for (auto *Exit : Exits)
2223       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2224               TII->get(TargetOpcode::COPY), *I)
2225         .addReg(NewVR);
2226   }
2227 }
2228 
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & DL,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const2229 SDValue SITargetLowering::LowerFormalArguments(
2230     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2231     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2232     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2233   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2234 
2235   MachineFunction &MF = DAG.getMachineFunction();
2236   const Function &Fn = MF.getFunction();
2237   FunctionType *FType = MF.getFunction().getFunctionType();
2238   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2239 
2240   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2241     DiagnosticInfoUnsupported NoGraphicsHSA(
2242         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2243     DAG.getContext()->diagnose(NoGraphicsHSA);
2244     return DAG.getEntryNode();
2245   }
2246 
2247   SmallVector<ISD::InputArg, 16> Splits;
2248   SmallVector<CCValAssign, 16> ArgLocs;
2249   BitVector Skipped(Ins.size());
2250   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2251                  *DAG.getContext());
2252 
2253   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2254   bool IsKernel = AMDGPU::isKernel(CallConv);
2255   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2256 
2257   if (IsGraphics) {
2258     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2259            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2260            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2261            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2262            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2263            !Info->hasWorkItemIDZ());
2264   }
2265 
2266   if (CallConv == CallingConv::AMDGPU_PS) {
2267     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2268 
2269     // At least one interpolation mode must be enabled or else the GPU will
2270     // hang.
2271     //
2272     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2273     // set PSInputAddr, the user wants to enable some bits after the compilation
2274     // based on run-time states. Since we can't know what the final PSInputEna
2275     // will look like, so we shouldn't do anything here and the user should take
2276     // responsibility for the correct programming.
2277     //
2278     // Otherwise, the following restrictions apply:
2279     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2280     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2281     //   enabled too.
2282     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2283         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2284       CCInfo.AllocateReg(AMDGPU::VGPR0);
2285       CCInfo.AllocateReg(AMDGPU::VGPR1);
2286       Info->markPSInputAllocated(0);
2287       Info->markPSInputEnabled(0);
2288     }
2289     if (Subtarget->isAmdPalOS()) {
2290       // For isAmdPalOS, the user does not enable some bits after compilation
2291       // based on run-time states; the register values being generated here are
2292       // the final ones set in hardware. Therefore we need to apply the
2293       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2294       // a bit is set in PSInputAddr but not PSInputEnable is where the
2295       // frontend set up an input arg for a particular interpolation mode, but
2296       // nothing uses that input arg. Really we should have an earlier pass
2297       // that removes such an arg.)
2298       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2299       if ((PsInputBits & 0x7F) == 0 ||
2300           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2301         Info->markPSInputEnabled(
2302             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2303     }
2304   } else if (IsKernel) {
2305     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2306   } else {
2307     Splits.append(Ins.begin(), Ins.end());
2308   }
2309 
2310   if (IsEntryFunc) {
2311     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2312     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2313   } else {
2314     // For the fixed ABI, pass workitem IDs in the last argument register.
2315     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2316       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2317   }
2318 
2319   if (IsKernel) {
2320     analyzeFormalArgumentsCompute(CCInfo, Ins);
2321   } else {
2322     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2323     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2324   }
2325 
2326   SmallVector<SDValue, 16> Chains;
2327 
2328   // FIXME: This is the minimum kernel argument alignment. We should improve
2329   // this to the maximum alignment of the arguments.
2330   //
2331   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2332   // kern arg offset.
2333   const Align KernelArgBaseAlign = Align(16);
2334 
2335   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2336     const ISD::InputArg &Arg = Ins[i];
2337     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2338       InVals.push_back(DAG.getUNDEF(Arg.VT));
2339       continue;
2340     }
2341 
2342     CCValAssign &VA = ArgLocs[ArgIdx++];
2343     MVT VT = VA.getLocVT();
2344 
2345     if (IsEntryFunc && VA.isMemLoc()) {
2346       VT = Ins[i].VT;
2347       EVT MemVT = VA.getLocVT();
2348 
2349       const uint64_t Offset = VA.getLocMemOffset();
2350       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2351 
2352       if (Arg.Flags.isByRef()) {
2353         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2354 
2355         const GCNTargetMachine &TM =
2356             static_cast<const GCNTargetMachine &>(getTargetMachine());
2357         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2358                                     Arg.Flags.getPointerAddrSpace())) {
2359           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2360                                      Arg.Flags.getPointerAddrSpace());
2361         }
2362 
2363         InVals.push_back(Ptr);
2364         continue;
2365       }
2366 
2367       SDValue Arg = lowerKernargMemParameter(
2368         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2369       Chains.push_back(Arg.getValue(1));
2370 
2371       auto *ParamTy =
2372         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2373       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2374           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2375                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2376         // On SI local pointers are just offsets into LDS, so they are always
2377         // less than 16-bits.  On CI and newer they could potentially be
2378         // real pointers, so we can't guarantee their size.
2379         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2380                           DAG.getValueType(MVT::i16));
2381       }
2382 
2383       InVals.push_back(Arg);
2384       continue;
2385     } else if (!IsEntryFunc && VA.isMemLoc()) {
2386       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2387       InVals.push_back(Val);
2388       if (!Arg.Flags.isByVal())
2389         Chains.push_back(Val.getValue(1));
2390       continue;
2391     }
2392 
2393     assert(VA.isRegLoc() && "Parameter must be in a register!");
2394 
2395     Register Reg = VA.getLocReg();
2396     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2397     EVT ValVT = VA.getValVT();
2398 
2399     Reg = MF.addLiveIn(Reg, RC);
2400     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2401 
2402     if (Arg.Flags.isSRet()) {
2403       // The return object should be reasonably addressable.
2404 
2405       // FIXME: This helps when the return is a real sret. If it is a
2406       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2407       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2408       unsigned NumBits
2409         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2410       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2411         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2412     }
2413 
2414     // If this is an 8 or 16-bit value, it is really passed promoted
2415     // to 32 bits. Insert an assert[sz]ext to capture this, then
2416     // truncate to the right size.
2417     switch (VA.getLocInfo()) {
2418     case CCValAssign::Full:
2419       break;
2420     case CCValAssign::BCvt:
2421       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2422       break;
2423     case CCValAssign::SExt:
2424       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2425                         DAG.getValueType(ValVT));
2426       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2427       break;
2428     case CCValAssign::ZExt:
2429       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2430                         DAG.getValueType(ValVT));
2431       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2432       break;
2433     case CCValAssign::AExt:
2434       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2435       break;
2436     default:
2437       llvm_unreachable("Unknown loc info!");
2438     }
2439 
2440     InVals.push_back(Val);
2441   }
2442 
2443   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2444     // Special inputs come after user arguments.
2445     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2446   }
2447 
2448   // Start adding system SGPRs.
2449   if (IsEntryFunc) {
2450     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2451   } else {
2452     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2453     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2454   }
2455 
2456   auto &ArgUsageInfo =
2457     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2458   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2459 
2460   unsigned StackArgSize = CCInfo.getNextStackOffset();
2461   Info->setBytesInStackArgArea(StackArgSize);
2462 
2463   return Chains.empty() ? Chain :
2464     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2465 }
2466 
2467 // TODO: If return values can't fit in registers, we should return as many as
2468 // possible in registers before passing on stack.
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool IsVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context) const2469 bool SITargetLowering::CanLowerReturn(
2470   CallingConv::ID CallConv,
2471   MachineFunction &MF, bool IsVarArg,
2472   const SmallVectorImpl<ISD::OutputArg> &Outs,
2473   LLVMContext &Context) const {
2474   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2475   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2476   // for shaders. Vector types should be explicitly handled by CC.
2477   if (AMDGPU::isEntryFunctionCC(CallConv))
2478     return true;
2479 
2480   SmallVector<CCValAssign, 16> RVLocs;
2481   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2482   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2483 }
2484 
2485 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & DL,SelectionDAG & DAG) const2486 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2487                               bool isVarArg,
2488                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2489                               const SmallVectorImpl<SDValue> &OutVals,
2490                               const SDLoc &DL, SelectionDAG &DAG) const {
2491   MachineFunction &MF = DAG.getMachineFunction();
2492   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2493 
2494   if (AMDGPU::isKernel(CallConv)) {
2495     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2496                                              OutVals, DL, DAG);
2497   }
2498 
2499   bool IsShader = AMDGPU::isShader(CallConv);
2500 
2501   Info->setIfReturnsVoid(Outs.empty());
2502   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2503 
2504   // CCValAssign - represent the assignment of the return value to a location.
2505   SmallVector<CCValAssign, 48> RVLocs;
2506   SmallVector<ISD::OutputArg, 48> Splits;
2507 
2508   // CCState - Info about the registers and stack slots.
2509   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2510                  *DAG.getContext());
2511 
2512   // Analyze outgoing return values.
2513   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2514 
2515   SDValue Flag;
2516   SmallVector<SDValue, 48> RetOps;
2517   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2518 
2519   // Add return address for callable functions.
2520   if (!Info->isEntryFunction()) {
2521     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2522     SDValue ReturnAddrReg = CreateLiveInRegister(
2523       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2524 
2525     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2526         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2527         MVT::i64);
2528     Chain =
2529         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2530     Flag = Chain.getValue(1);
2531     RetOps.push_back(ReturnAddrVirtualReg);
2532   }
2533 
2534   // Copy the result values into the output registers.
2535   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2536        ++I, ++RealRVLocIdx) {
2537     CCValAssign &VA = RVLocs[I];
2538     assert(VA.isRegLoc() && "Can only return in registers!");
2539     // TODO: Partially return in registers if return values don't fit.
2540     SDValue Arg = OutVals[RealRVLocIdx];
2541 
2542     // Copied from other backends.
2543     switch (VA.getLocInfo()) {
2544     case CCValAssign::Full:
2545       break;
2546     case CCValAssign::BCvt:
2547       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2548       break;
2549     case CCValAssign::SExt:
2550       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2551       break;
2552     case CCValAssign::ZExt:
2553       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2554       break;
2555     case CCValAssign::AExt:
2556       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2557       break;
2558     default:
2559       llvm_unreachable("Unknown loc info!");
2560     }
2561 
2562     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2563     Flag = Chain.getValue(1);
2564     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2565   }
2566 
2567   // FIXME: Does sret work properly?
2568   if (!Info->isEntryFunction()) {
2569     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2570     const MCPhysReg *I =
2571       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2572     if (I) {
2573       for (; *I; ++I) {
2574         if (AMDGPU::SReg_64RegClass.contains(*I))
2575           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2576         else if (AMDGPU::SReg_32RegClass.contains(*I))
2577           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2578         else
2579           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2580       }
2581     }
2582   }
2583 
2584   // Update chain and glue.
2585   RetOps[0] = Chain;
2586   if (Flag.getNode())
2587     RetOps.push_back(Flag);
2588 
2589   unsigned Opc = AMDGPUISD::ENDPGM;
2590   if (!IsWaveEnd)
2591     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2592   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2593 }
2594 
LowerCallResult(SDValue Chain,SDValue InFlag,CallingConv::ID CallConv,bool IsVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & DL,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals,bool IsThisReturn,SDValue ThisVal) const2595 SDValue SITargetLowering::LowerCallResult(
2596     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2597     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2598     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2599     SDValue ThisVal) const {
2600   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2601 
2602   // Assign locations to each value returned by this call.
2603   SmallVector<CCValAssign, 16> RVLocs;
2604   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2605                  *DAG.getContext());
2606   CCInfo.AnalyzeCallResult(Ins, RetCC);
2607 
2608   // Copy all of the result registers out of their specified physreg.
2609   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2610     CCValAssign VA = RVLocs[i];
2611     SDValue Val;
2612 
2613     if (VA.isRegLoc()) {
2614       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2615       Chain = Val.getValue(1);
2616       InFlag = Val.getValue(2);
2617     } else if (VA.isMemLoc()) {
2618       report_fatal_error("TODO: return values in memory");
2619     } else
2620       llvm_unreachable("unknown argument location type");
2621 
2622     switch (VA.getLocInfo()) {
2623     case CCValAssign::Full:
2624       break;
2625     case CCValAssign::BCvt:
2626       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2627       break;
2628     case CCValAssign::ZExt:
2629       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2630                         DAG.getValueType(VA.getValVT()));
2631       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2632       break;
2633     case CCValAssign::SExt:
2634       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2635                         DAG.getValueType(VA.getValVT()));
2636       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2637       break;
2638     case CCValAssign::AExt:
2639       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2640       break;
2641     default:
2642       llvm_unreachable("Unknown loc info!");
2643     }
2644 
2645     InVals.push_back(Val);
2646   }
2647 
2648   return Chain;
2649 }
2650 
2651 // Add code to pass special inputs required depending on used features separate
2652 // from the explicit user arguments present in the IR.
passSpecialInputs(CallLoweringInfo & CLI,CCState & CCInfo,const SIMachineFunctionInfo & Info,SmallVectorImpl<std::pair<unsigned,SDValue>> & RegsToPass,SmallVectorImpl<SDValue> & MemOpChains,SDValue Chain) const2653 void SITargetLowering::passSpecialInputs(
2654     CallLoweringInfo &CLI,
2655     CCState &CCInfo,
2656     const SIMachineFunctionInfo &Info,
2657     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2658     SmallVectorImpl<SDValue> &MemOpChains,
2659     SDValue Chain) const {
2660   // If we don't have a call site, this was a call inserted by
2661   // legalization. These can never use special inputs.
2662   if (!CLI.CB)
2663     return;
2664 
2665   SelectionDAG &DAG = CLI.DAG;
2666   const SDLoc &DL = CLI.DL;
2667 
2668   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2669   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2670 
2671   const AMDGPUFunctionArgInfo *CalleeArgInfo
2672     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2673   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2674     auto &ArgUsageInfo =
2675       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2676     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2677   }
2678 
2679   // TODO: Unify with private memory register handling. This is complicated by
2680   // the fact that at least in kernels, the input argument is not necessarily
2681   // in the same location as the input.
2682   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2683     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2684     AMDGPUFunctionArgInfo::QUEUE_PTR,
2685     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2686     AMDGPUFunctionArgInfo::DISPATCH_ID,
2687     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2688     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2689     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2690   };
2691 
2692   for (auto InputID : InputRegs) {
2693     const ArgDescriptor *OutgoingArg;
2694     const TargetRegisterClass *ArgRC;
2695     LLT ArgTy;
2696 
2697     std::tie(OutgoingArg, ArgRC, ArgTy) =
2698         CalleeArgInfo->getPreloadedValue(InputID);
2699     if (!OutgoingArg)
2700       continue;
2701 
2702     const ArgDescriptor *IncomingArg;
2703     const TargetRegisterClass *IncomingArgRC;
2704     LLT Ty;
2705     std::tie(IncomingArg, IncomingArgRC, Ty) =
2706         CallerArgInfo.getPreloadedValue(InputID);
2707     assert(IncomingArgRC == ArgRC);
2708 
2709     // All special arguments are ints for now.
2710     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2711     SDValue InputReg;
2712 
2713     if (IncomingArg) {
2714       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2715     } else {
2716       // The implicit arg ptr is special because it doesn't have a corresponding
2717       // input for kernels, and is computed from the kernarg segment pointer.
2718       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2719       InputReg = getImplicitArgPtr(DAG, DL);
2720     }
2721 
2722     if (OutgoingArg->isRegister()) {
2723       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2724       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2725         report_fatal_error("failed to allocate implicit input argument");
2726     } else {
2727       unsigned SpecialArgOffset =
2728           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2729       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2730                                               SpecialArgOffset);
2731       MemOpChains.push_back(ArgStore);
2732     }
2733   }
2734 
2735   // Pack workitem IDs into a single register or pass it as is if already
2736   // packed.
2737   const ArgDescriptor *OutgoingArg;
2738   const TargetRegisterClass *ArgRC;
2739   LLT Ty;
2740 
2741   std::tie(OutgoingArg, ArgRC, Ty) =
2742       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2743   if (!OutgoingArg)
2744     std::tie(OutgoingArg, ArgRC, Ty) =
2745         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2746   if (!OutgoingArg)
2747     std::tie(OutgoingArg, ArgRC, Ty) =
2748         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2749   if (!OutgoingArg)
2750     return;
2751 
2752   const ArgDescriptor *IncomingArgX = std::get<0>(
2753       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2754   const ArgDescriptor *IncomingArgY = std::get<0>(
2755       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2756   const ArgDescriptor *IncomingArgZ = std::get<0>(
2757       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2758 
2759   SDValue InputReg;
2760   SDLoc SL;
2761 
2762   // If incoming ids are not packed we need to pack them.
2763   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2764     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2765 
2766   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2767     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2768     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2769                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2770     InputReg = InputReg.getNode() ?
2771                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2772   }
2773 
2774   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2775     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2776     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2777                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2778     InputReg = InputReg.getNode() ?
2779                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2780   }
2781 
2782   if (!InputReg.getNode()) {
2783     // Workitem ids are already packed, any of present incoming arguments
2784     // will carry all required fields.
2785     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2786       IncomingArgX ? *IncomingArgX :
2787       IncomingArgY ? *IncomingArgY :
2788                      *IncomingArgZ, ~0u);
2789     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2790   }
2791 
2792   if (OutgoingArg->isRegister()) {
2793     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2794     CCInfo.AllocateReg(OutgoingArg->getRegister());
2795   } else {
2796     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2797     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2798                                             SpecialArgOffset);
2799     MemOpChains.push_back(ArgStore);
2800   }
2801 }
2802 
canGuaranteeTCO(CallingConv::ID CC)2803 static bool canGuaranteeTCO(CallingConv::ID CC) {
2804   return CC == CallingConv::Fast;
2805 }
2806 
2807 /// Return true if we might ever do TCO for calls with this calling convention.
mayTailCallThisCC(CallingConv::ID CC)2808 static bool mayTailCallThisCC(CallingConv::ID CC) {
2809   switch (CC) {
2810   case CallingConv::C:
2811     return true;
2812   default:
2813     return canGuaranteeTCO(CC);
2814   }
2815 }
2816 
isEligibleForTailCallOptimization(SDValue Callee,CallingConv::ID CalleeCC,bool IsVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SmallVectorImpl<ISD::InputArg> & Ins,SelectionDAG & DAG) const2817 bool SITargetLowering::isEligibleForTailCallOptimization(
2818     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2819     const SmallVectorImpl<ISD::OutputArg> &Outs,
2820     const SmallVectorImpl<SDValue> &OutVals,
2821     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2822   if (!mayTailCallThisCC(CalleeCC))
2823     return false;
2824 
2825   MachineFunction &MF = DAG.getMachineFunction();
2826   const Function &CallerF = MF.getFunction();
2827   CallingConv::ID CallerCC = CallerF.getCallingConv();
2828   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2829   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2830 
2831   // Kernels aren't callable, and don't have a live in return address so it
2832   // doesn't make sense to do a tail call with entry functions.
2833   if (!CallerPreserved)
2834     return false;
2835 
2836   bool CCMatch = CallerCC == CalleeCC;
2837 
2838   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2839     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2840       return true;
2841     return false;
2842   }
2843 
2844   // TODO: Can we handle var args?
2845   if (IsVarArg)
2846     return false;
2847 
2848   for (const Argument &Arg : CallerF.args()) {
2849     if (Arg.hasByValAttr())
2850       return false;
2851   }
2852 
2853   LLVMContext &Ctx = *DAG.getContext();
2854 
2855   // Check that the call results are passed in the same way.
2856   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2857                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2858                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2859     return false;
2860 
2861   // The callee has to preserve all registers the caller needs to preserve.
2862   if (!CCMatch) {
2863     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2864     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2865       return false;
2866   }
2867 
2868   // Nothing more to check if the callee is taking no arguments.
2869   if (Outs.empty())
2870     return true;
2871 
2872   SmallVector<CCValAssign, 16> ArgLocs;
2873   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2874 
2875   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2876 
2877   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2878   // If the stack arguments for this call do not fit into our own save area then
2879   // the call cannot be made tail.
2880   // TODO: Is this really necessary?
2881   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2882     return false;
2883 
2884   const MachineRegisterInfo &MRI = MF.getRegInfo();
2885   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2886 }
2887 
mayBeEmittedAsTailCall(const CallInst * CI) const2888 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2889   if (!CI->isTailCall())
2890     return false;
2891 
2892   const Function *ParentFn = CI->getParent()->getParent();
2893   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2894     return false;
2895   return true;
2896 }
2897 
2898 // The wave scratch offset register is used as the global base pointer.
LowerCall(CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const2899 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2900                                     SmallVectorImpl<SDValue> &InVals) const {
2901   SelectionDAG &DAG = CLI.DAG;
2902   const SDLoc &DL = CLI.DL;
2903   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2904   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2905   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2906   SDValue Chain = CLI.Chain;
2907   SDValue Callee = CLI.Callee;
2908   bool &IsTailCall = CLI.IsTailCall;
2909   CallingConv::ID CallConv = CLI.CallConv;
2910   bool IsVarArg = CLI.IsVarArg;
2911   bool IsSibCall = false;
2912   bool IsThisReturn = false;
2913   MachineFunction &MF = DAG.getMachineFunction();
2914 
2915   if (Callee.isUndef() || isNullConstant(Callee)) {
2916     if (!CLI.IsTailCall) {
2917       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2918         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2919     }
2920 
2921     return Chain;
2922   }
2923 
2924   if (IsVarArg) {
2925     return lowerUnhandledCall(CLI, InVals,
2926                               "unsupported call to variadic function ");
2927   }
2928 
2929   if (!CLI.CB)
2930     report_fatal_error("unsupported libcall legalization");
2931 
2932   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2933       !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) {
2934     return lowerUnhandledCall(CLI, InVals,
2935                               "unsupported indirect call to function ");
2936   }
2937 
2938   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2939     return lowerUnhandledCall(CLI, InVals,
2940                               "unsupported required tail call to function ");
2941   }
2942 
2943   if (AMDGPU::isShader(CallConv)) {
2944     // Note the issue is with the CC of the called function, not of the call
2945     // itself.
2946     return lowerUnhandledCall(CLI, InVals,
2947                               "unsupported call to a shader function ");
2948   }
2949 
2950   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
2951       CallConv != CallingConv::AMDGPU_Gfx) {
2952     // Only allow calls with specific calling conventions.
2953     return lowerUnhandledCall(CLI, InVals,
2954                               "unsupported calling convention for call from "
2955                               "graphics shader of function ");
2956   }
2957 
2958   if (IsTailCall) {
2959     IsTailCall = isEligibleForTailCallOptimization(
2960       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2961     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2962       report_fatal_error("failed to perform tail call elimination on a call "
2963                          "site marked musttail");
2964     }
2965 
2966     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2967 
2968     // A sibling call is one where we're under the usual C ABI and not planning
2969     // to change that but can still do a tail call:
2970     if (!TailCallOpt && IsTailCall)
2971       IsSibCall = true;
2972 
2973     if (IsTailCall)
2974       ++NumTailCalls;
2975   }
2976 
2977   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2978   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2979   SmallVector<SDValue, 8> MemOpChains;
2980 
2981   // Analyze operands of the call, assigning locations to each operand.
2982   SmallVector<CCValAssign, 16> ArgLocs;
2983   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2984   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2985 
2986   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
2987       CallConv != CallingConv::AMDGPU_Gfx) {
2988     // With a fixed ABI, allocate fixed registers before user arguments.
2989     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2990   }
2991 
2992   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2993 
2994   // Get a count of how many bytes are to be pushed on the stack.
2995   unsigned NumBytes = CCInfo.getNextStackOffset();
2996 
2997   if (IsSibCall) {
2998     // Since we're not changing the ABI to make this a tail call, the memory
2999     // operands are already available in the caller's incoming argument space.
3000     NumBytes = 0;
3001   }
3002 
3003   // FPDiff is the byte offset of the call's argument area from the callee's.
3004   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3005   // by this amount for a tail call. In a sibling call it must be 0 because the
3006   // caller will deallocate the entire stack and the callee still expects its
3007   // arguments to begin at SP+0. Completely unused for non-tail calls.
3008   int32_t FPDiff = 0;
3009   MachineFrameInfo &MFI = MF.getFrameInfo();
3010 
3011   // Adjust the stack pointer for the new arguments...
3012   // These operations are automatically eliminated by the prolog/epilog pass
3013   if (!IsSibCall) {
3014     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3015 
3016     if (!Subtarget->enableFlatScratch()) {
3017       SmallVector<SDValue, 4> CopyFromChains;
3018 
3019       // In the HSA case, this should be an identity copy.
3020       SDValue ScratchRSrcReg
3021         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3022       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3023       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3024       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3025     }
3026   }
3027 
3028   MVT PtrVT = MVT::i32;
3029 
3030   // Walk the register/memloc assignments, inserting copies/loads.
3031   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3032     CCValAssign &VA = ArgLocs[i];
3033     SDValue Arg = OutVals[i];
3034 
3035     // Promote the value if needed.
3036     switch (VA.getLocInfo()) {
3037     case CCValAssign::Full:
3038       break;
3039     case CCValAssign::BCvt:
3040       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3041       break;
3042     case CCValAssign::ZExt:
3043       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3044       break;
3045     case CCValAssign::SExt:
3046       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3047       break;
3048     case CCValAssign::AExt:
3049       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3050       break;
3051     case CCValAssign::FPExt:
3052       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3053       break;
3054     default:
3055       llvm_unreachable("Unknown loc info!");
3056     }
3057 
3058     if (VA.isRegLoc()) {
3059       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3060     } else {
3061       assert(VA.isMemLoc());
3062 
3063       SDValue DstAddr;
3064       MachinePointerInfo DstInfo;
3065 
3066       unsigned LocMemOffset = VA.getLocMemOffset();
3067       int32_t Offset = LocMemOffset;
3068 
3069       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3070       MaybeAlign Alignment;
3071 
3072       if (IsTailCall) {
3073         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3074         unsigned OpSize = Flags.isByVal() ?
3075           Flags.getByValSize() : VA.getValVT().getStoreSize();
3076 
3077         // FIXME: We can have better than the minimum byval required alignment.
3078         Alignment =
3079             Flags.isByVal()
3080                 ? Flags.getNonZeroByValAlign()
3081                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3082 
3083         Offset = Offset + FPDiff;
3084         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3085 
3086         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3087         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3088 
3089         // Make sure any stack arguments overlapping with where we're storing
3090         // are loaded before this eventual operation. Otherwise they'll be
3091         // clobbered.
3092 
3093         // FIXME: Why is this really necessary? This seems to just result in a
3094         // lot of code to copy the stack and write them back to the same
3095         // locations, which are supposed to be immutable?
3096         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3097       } else {
3098         DstAddr = PtrOff;
3099         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3100         Alignment =
3101             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3102       }
3103 
3104       if (Outs[i].Flags.isByVal()) {
3105         SDValue SizeNode =
3106             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3107         SDValue Cpy =
3108             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3109                           Outs[i].Flags.getNonZeroByValAlign(),
3110                           /*isVol = */ false, /*AlwaysInline = */ true,
3111                           /*isTailCall = */ false, DstInfo,
3112                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3113 
3114         MemOpChains.push_back(Cpy);
3115       } else {
3116         SDValue Store =
3117             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3118         MemOpChains.push_back(Store);
3119       }
3120     }
3121   }
3122 
3123   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3124       CallConv != CallingConv::AMDGPU_Gfx) {
3125     // Copy special input registers after user input arguments.
3126     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3127   }
3128 
3129   if (!MemOpChains.empty())
3130     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3131 
3132   // Build a sequence of copy-to-reg nodes chained together with token chain
3133   // and flag operands which copy the outgoing args into the appropriate regs.
3134   SDValue InFlag;
3135   for (auto &RegToPass : RegsToPass) {
3136     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3137                              RegToPass.second, InFlag);
3138     InFlag = Chain.getValue(1);
3139   }
3140 
3141 
3142   SDValue PhysReturnAddrReg;
3143   if (IsTailCall) {
3144     // Since the return is being combined with the call, we need to pass on the
3145     // return address.
3146 
3147     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3148     SDValue ReturnAddrReg = CreateLiveInRegister(
3149       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3150 
3151     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3152                                         MVT::i64);
3153     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3154     InFlag = Chain.getValue(1);
3155   }
3156 
3157   // We don't usually want to end the call-sequence here because we would tidy
3158   // the frame up *after* the call, however in the ABI-changing tail-call case
3159   // we've carefully laid out the parameters so that when sp is reset they'll be
3160   // in the correct location.
3161   if (IsTailCall && !IsSibCall) {
3162     Chain = DAG.getCALLSEQ_END(Chain,
3163                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3164                                DAG.getTargetConstant(0, DL, MVT::i32),
3165                                InFlag, DL);
3166     InFlag = Chain.getValue(1);
3167   }
3168 
3169   std::vector<SDValue> Ops;
3170   Ops.push_back(Chain);
3171   Ops.push_back(Callee);
3172   // Add a redundant copy of the callee global which will not be legalized, as
3173   // we need direct access to the callee later.
3174   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3175     const GlobalValue *GV = GSD->getGlobal();
3176     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3177   } else {
3178     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3179   }
3180 
3181   if (IsTailCall) {
3182     // Each tail call may have to adjust the stack by a different amount, so
3183     // this information must travel along with the operation for eventual
3184     // consumption by emitEpilogue.
3185     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3186 
3187     Ops.push_back(PhysReturnAddrReg);
3188   }
3189 
3190   // Add argument registers to the end of the list so that they are known live
3191   // into the call.
3192   for (auto &RegToPass : RegsToPass) {
3193     Ops.push_back(DAG.getRegister(RegToPass.first,
3194                                   RegToPass.second.getValueType()));
3195   }
3196 
3197   // Add a register mask operand representing the call-preserved registers.
3198 
3199   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3200   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3201   assert(Mask && "Missing call preserved mask for calling convention");
3202   Ops.push_back(DAG.getRegisterMask(Mask));
3203 
3204   if (InFlag.getNode())
3205     Ops.push_back(InFlag);
3206 
3207   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3208 
3209   // If we're doing a tall call, use a TC_RETURN here rather than an
3210   // actual call instruction.
3211   if (IsTailCall) {
3212     MFI.setHasTailCall();
3213     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3214   }
3215 
3216   // Returns a chain and a flag for retval copy to use.
3217   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3218   Chain = Call.getValue(0);
3219   InFlag = Call.getValue(1);
3220 
3221   uint64_t CalleePopBytes = NumBytes;
3222   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3223                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3224                              InFlag, DL);
3225   if (!Ins.empty())
3226     InFlag = Chain.getValue(1);
3227 
3228   // Handle result values, copying them out of physregs into vregs that we
3229   // return.
3230   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3231                          InVals, IsThisReturn,
3232                          IsThisReturn ? OutVals[0] : SDValue());
3233 }
3234 
3235 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3236 // except for applying the wave size scale to the increment amount.
lowerDYNAMIC_STACKALLOCImpl(SDValue Op,SelectionDAG & DAG) const3237 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3238     SDValue Op, SelectionDAG &DAG) const {
3239   const MachineFunction &MF = DAG.getMachineFunction();
3240   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3241 
3242   SDLoc dl(Op);
3243   EVT VT = Op.getValueType();
3244   SDValue Tmp1 = Op;
3245   SDValue Tmp2 = Op.getValue(1);
3246   SDValue Tmp3 = Op.getOperand(2);
3247   SDValue Chain = Tmp1.getOperand(0);
3248 
3249   Register SPReg = Info->getStackPtrOffsetReg();
3250 
3251   // Chain the dynamic stack allocation so that it doesn't modify the stack
3252   // pointer when other instructions are using the stack.
3253   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3254 
3255   SDValue Size  = Tmp2.getOperand(1);
3256   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3257   Chain = SP.getValue(1);
3258   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3259   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3260   const TargetFrameLowering *TFL = ST.getFrameLowering();
3261   unsigned Opc =
3262     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3263     ISD::ADD : ISD::SUB;
3264 
3265   SDValue ScaledSize = DAG.getNode(
3266       ISD::SHL, dl, VT, Size,
3267       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3268 
3269   Align StackAlign = TFL->getStackAlign();
3270   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3271   if (Alignment && *Alignment > StackAlign) {
3272     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3273                        DAG.getConstant(-(uint64_t)Alignment->value()
3274                                            << ST.getWavefrontSizeLog2(),
3275                                        dl, VT));
3276   }
3277 
3278   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3279   Tmp2 = DAG.getCALLSEQ_END(
3280       Chain, DAG.getIntPtrConstant(0, dl, true),
3281       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3282 
3283   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3284 }
3285 
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG) const3286 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3287                                                   SelectionDAG &DAG) const {
3288   // We only handle constant sizes here to allow non-entry block, static sized
3289   // allocas. A truly dynamic value is more difficult to support because we
3290   // don't know if the size value is uniform or not. If the size isn't uniform,
3291   // we would need to do a wave reduction to get the maximum size to know how
3292   // much to increment the uniform stack pointer.
3293   SDValue Size = Op.getOperand(1);
3294   if (isa<ConstantSDNode>(Size))
3295       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3296 
3297   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3298 }
3299 
getRegisterByName(const char * RegName,LLT VT,const MachineFunction & MF) const3300 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3301                                              const MachineFunction &MF) const {
3302   Register Reg = StringSwitch<Register>(RegName)
3303     .Case("m0", AMDGPU::M0)
3304     .Case("exec", AMDGPU::EXEC)
3305     .Case("exec_lo", AMDGPU::EXEC_LO)
3306     .Case("exec_hi", AMDGPU::EXEC_HI)
3307     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3308     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3309     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3310     .Default(Register());
3311 
3312   if (Reg == AMDGPU::NoRegister) {
3313     report_fatal_error(Twine("invalid register name \""
3314                              + StringRef(RegName)  + "\"."));
3315 
3316   }
3317 
3318   if (!Subtarget->hasFlatScrRegister() &&
3319        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3320     report_fatal_error(Twine("invalid register \""
3321                              + StringRef(RegName)  + "\" for subtarget."));
3322   }
3323 
3324   switch (Reg) {
3325   case AMDGPU::M0:
3326   case AMDGPU::EXEC_LO:
3327   case AMDGPU::EXEC_HI:
3328   case AMDGPU::FLAT_SCR_LO:
3329   case AMDGPU::FLAT_SCR_HI:
3330     if (VT.getSizeInBits() == 32)
3331       return Reg;
3332     break;
3333   case AMDGPU::EXEC:
3334   case AMDGPU::FLAT_SCR:
3335     if (VT.getSizeInBits() == 64)
3336       return Reg;
3337     break;
3338   default:
3339     llvm_unreachable("missing register type checking");
3340   }
3341 
3342   report_fatal_error(Twine("invalid type for register \""
3343                            + StringRef(RegName) + "\"."));
3344 }
3345 
3346 // If kill is not the last instruction, split the block so kill is always a
3347 // proper terminator.
3348 MachineBasicBlock *
splitKillBlock(MachineInstr & MI,MachineBasicBlock * BB) const3349 SITargetLowering::splitKillBlock(MachineInstr &MI,
3350                                  MachineBasicBlock *BB) const {
3351   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3352   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3353   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3354   return SplitBB;
3355 }
3356 
3357 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3358 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3359 // be the first instruction in the remainder block.
3360 //
3361 /// \returns { LoopBody, Remainder }
3362 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
splitBlockForLoop(MachineInstr & MI,MachineBasicBlock & MBB,bool InstInLoop)3363 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3364   MachineFunction *MF = MBB.getParent();
3365   MachineBasicBlock::iterator I(&MI);
3366 
3367   // To insert the loop we need to split the block. Move everything after this
3368   // point to a new block, and insert a new empty block between the two.
3369   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3370   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3371   MachineFunction::iterator MBBI(MBB);
3372   ++MBBI;
3373 
3374   MF->insert(MBBI, LoopBB);
3375   MF->insert(MBBI, RemainderBB);
3376 
3377   LoopBB->addSuccessor(LoopBB);
3378   LoopBB->addSuccessor(RemainderBB);
3379 
3380   // Move the rest of the block into a new block.
3381   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3382 
3383   if (InstInLoop) {
3384     auto Next = std::next(I);
3385 
3386     // Move instruction to loop body.
3387     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3388 
3389     // Move the rest of the block.
3390     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3391   } else {
3392     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3393   }
3394 
3395   MBB.addSuccessor(LoopBB);
3396 
3397   return std::make_pair(LoopBB, RemainderBB);
3398 }
3399 
3400 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
bundleInstWithWaitcnt(MachineInstr & MI) const3401 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3402   MachineBasicBlock *MBB = MI.getParent();
3403   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3404   auto I = MI.getIterator();
3405   auto E = std::next(I);
3406 
3407   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3408     .addImm(0);
3409 
3410   MIBundleBuilder Bundler(*MBB, I, E);
3411   finalizeBundle(*MBB, Bundler.begin());
3412 }
3413 
3414 MachineBasicBlock *
emitGWSMemViolTestLoop(MachineInstr & MI,MachineBasicBlock * BB) const3415 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3416                                          MachineBasicBlock *BB) const {
3417   const DebugLoc &DL = MI.getDebugLoc();
3418 
3419   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3420 
3421   MachineBasicBlock *LoopBB;
3422   MachineBasicBlock *RemainderBB;
3423   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3424 
3425   // Apparently kill flags are only valid if the def is in the same block?
3426   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3427     Src->setIsKill(false);
3428 
3429   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3430 
3431   MachineBasicBlock::iterator I = LoopBB->end();
3432 
3433   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3434     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3435 
3436   // Clear TRAP_STS.MEM_VIOL
3437   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3438     .addImm(0)
3439     .addImm(EncodedReg);
3440 
3441   bundleInstWithWaitcnt(MI);
3442 
3443   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3444 
3445   // Load and check TRAP_STS.MEM_VIOL
3446   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3447     .addImm(EncodedReg);
3448 
3449   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3450   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3451     .addReg(Reg, RegState::Kill)
3452     .addImm(0);
3453   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3454     .addMBB(LoopBB);
3455 
3456   return RemainderBB;
3457 }
3458 
3459 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3460 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3461 // will only do one iteration. In the worst case, this will loop 64 times.
3462 //
3463 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3464 static MachineBasicBlock::iterator
emitLoadM0FromVGPRLoop(const SIInstrInfo * TII,MachineRegisterInfo & MRI,MachineBasicBlock & OrigBB,MachineBasicBlock & LoopBB,const DebugLoc & DL,const MachineOperand & Idx,unsigned InitReg,unsigned ResultReg,unsigned PhiReg,unsigned InitSaveExecReg,int Offset,bool UseGPRIdxMode,Register & SGPRIdxReg)3465 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3466                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3467                        const DebugLoc &DL, const MachineOperand &Idx,
3468                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3469                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3470                        Register &SGPRIdxReg) {
3471 
3472   MachineFunction *MF = OrigBB.getParent();
3473   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3474   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3475   MachineBasicBlock::iterator I = LoopBB.begin();
3476 
3477   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3478   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3479   Register NewExec = MRI.createVirtualRegister(BoolRC);
3480   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3481   Register CondReg = MRI.createVirtualRegister(BoolRC);
3482 
3483   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3484     .addReg(InitReg)
3485     .addMBB(&OrigBB)
3486     .addReg(ResultReg)
3487     .addMBB(&LoopBB);
3488 
3489   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3490     .addReg(InitSaveExecReg)
3491     .addMBB(&OrigBB)
3492     .addReg(NewExec)
3493     .addMBB(&LoopBB);
3494 
3495   // Read the next variant <- also loop target.
3496   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3497       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3498 
3499   // Compare the just read M0 value to all possible Idx values.
3500   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3501       .addReg(CurrentIdxReg)
3502       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3503 
3504   // Update EXEC, save the original EXEC value to VCC.
3505   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3506                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3507           NewExec)
3508     .addReg(CondReg, RegState::Kill);
3509 
3510   MRI.setSimpleHint(NewExec, CondReg);
3511 
3512   if (UseGPRIdxMode) {
3513     if (Offset == 0) {
3514       SGPRIdxReg = CurrentIdxReg;
3515     } else {
3516       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3517       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3518           .addReg(CurrentIdxReg, RegState::Kill)
3519           .addImm(Offset);
3520     }
3521   } else {
3522     // Move index from VCC into M0
3523     if (Offset == 0) {
3524       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3525         .addReg(CurrentIdxReg, RegState::Kill);
3526     } else {
3527       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3528         .addReg(CurrentIdxReg, RegState::Kill)
3529         .addImm(Offset);
3530     }
3531   }
3532 
3533   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3534   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3535   MachineInstr *InsertPt =
3536     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3537                                                   : AMDGPU::S_XOR_B64_term), Exec)
3538       .addReg(Exec)
3539       .addReg(NewExec);
3540 
3541   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3542   // s_cbranch_scc0?
3543 
3544   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3545   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3546     .addMBB(&LoopBB);
3547 
3548   return InsertPt->getIterator();
3549 }
3550 
3551 // This has slightly sub-optimal regalloc when the source vector is killed by
3552 // the read. The register allocator does not understand that the kill is
3553 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3554 // subregister from it, using 1 more VGPR than necessary. This was saved when
3555 // this was expanded after register allocation.
3556 static MachineBasicBlock::iterator
loadM0FromVGPR(const SIInstrInfo * TII,MachineBasicBlock & MBB,MachineInstr & MI,unsigned InitResultReg,unsigned PhiReg,int Offset,bool UseGPRIdxMode,Register & SGPRIdxReg)3557 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3558                unsigned InitResultReg, unsigned PhiReg, int Offset,
3559                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3560   MachineFunction *MF = MBB.getParent();
3561   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3562   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3563   MachineRegisterInfo &MRI = MF->getRegInfo();
3564   const DebugLoc &DL = MI.getDebugLoc();
3565   MachineBasicBlock::iterator I(&MI);
3566 
3567   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3568   Register DstReg = MI.getOperand(0).getReg();
3569   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3570   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3571   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3572   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3573 
3574   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3575 
3576   // Save the EXEC mask
3577   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3578     .addReg(Exec);
3579 
3580   MachineBasicBlock *LoopBB;
3581   MachineBasicBlock *RemainderBB;
3582   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3583 
3584   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3585 
3586   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3587                                       InitResultReg, DstReg, PhiReg, TmpExec,
3588                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3589 
3590   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3591   MachineFunction::iterator MBBI(LoopBB);
3592   ++MBBI;
3593   MF->insert(MBBI, LandingPad);
3594   LoopBB->removeSuccessor(RemainderBB);
3595   LandingPad->addSuccessor(RemainderBB);
3596   LoopBB->addSuccessor(LandingPad);
3597   MachineBasicBlock::iterator First = LandingPad->begin();
3598   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3599     .addReg(SaveExec);
3600 
3601   return InsPt;
3602 }
3603 
3604 // Returns subreg index, offset
3605 static std::pair<unsigned, int>
computeIndirectRegAndOffset(const SIRegisterInfo & TRI,const TargetRegisterClass * SuperRC,unsigned VecReg,int Offset)3606 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3607                             const TargetRegisterClass *SuperRC,
3608                             unsigned VecReg,
3609                             int Offset) {
3610   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3611 
3612   // Skip out of bounds offsets, or else we would end up using an undefined
3613   // register.
3614   if (Offset >= NumElts || Offset < 0)
3615     return std::make_pair(AMDGPU::sub0, Offset);
3616 
3617   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3618 }
3619 
setM0ToIndexFromSGPR(const SIInstrInfo * TII,MachineRegisterInfo & MRI,MachineInstr & MI,int Offset)3620 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3621                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3622                                  int Offset) {
3623   MachineBasicBlock *MBB = MI.getParent();
3624   const DebugLoc &DL = MI.getDebugLoc();
3625   MachineBasicBlock::iterator I(&MI);
3626 
3627   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3628 
3629   assert(Idx->getReg() != AMDGPU::NoRegister);
3630 
3631   if (Offset == 0) {
3632     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3633   } else {
3634     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3635         .add(*Idx)
3636         .addImm(Offset);
3637   }
3638 }
3639 
getIndirectSGPRIdx(const SIInstrInfo * TII,MachineRegisterInfo & MRI,MachineInstr & MI,int Offset)3640 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3641                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3642                                    int Offset) {
3643   MachineBasicBlock *MBB = MI.getParent();
3644   const DebugLoc &DL = MI.getDebugLoc();
3645   MachineBasicBlock::iterator I(&MI);
3646 
3647   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3648 
3649   if (Offset == 0)
3650     return Idx->getReg();
3651 
3652   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3653   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3654       .add(*Idx)
3655       .addImm(Offset);
3656   return Tmp;
3657 }
3658 
emitIndirectSrc(MachineInstr & MI,MachineBasicBlock & MBB,const GCNSubtarget & ST)3659 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3660                                           MachineBasicBlock &MBB,
3661                                           const GCNSubtarget &ST) {
3662   const SIInstrInfo *TII = ST.getInstrInfo();
3663   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3664   MachineFunction *MF = MBB.getParent();
3665   MachineRegisterInfo &MRI = MF->getRegInfo();
3666 
3667   Register Dst = MI.getOperand(0).getReg();
3668   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3669   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3670   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3671 
3672   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3673   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3674 
3675   unsigned SubReg;
3676   std::tie(SubReg, Offset)
3677     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3678 
3679   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3680 
3681   // Check for a SGPR index.
3682   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3683     MachineBasicBlock::iterator I(&MI);
3684     const DebugLoc &DL = MI.getDebugLoc();
3685 
3686     if (UseGPRIdxMode) {
3687       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3688       // to avoid interfering with other uses, so probably requires a new
3689       // optimization pass.
3690       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3691 
3692       const MCInstrDesc &GPRIDXDesc =
3693           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3694       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3695           .addReg(SrcReg)
3696           .addReg(Idx)
3697           .addImm(SubReg);
3698     } else {
3699       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3700 
3701       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3702         .addReg(SrcReg, 0, SubReg)
3703         .addReg(SrcReg, RegState::Implicit);
3704     }
3705 
3706     MI.eraseFromParent();
3707 
3708     return &MBB;
3709   }
3710 
3711   // Control flow needs to be inserted if indexing with a VGPR.
3712   const DebugLoc &DL = MI.getDebugLoc();
3713   MachineBasicBlock::iterator I(&MI);
3714 
3715   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3716   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3717 
3718   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3719 
3720   Register SGPRIdxReg;
3721   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3722                               UseGPRIdxMode, SGPRIdxReg);
3723 
3724   MachineBasicBlock *LoopBB = InsPt->getParent();
3725 
3726   if (UseGPRIdxMode) {
3727     const MCInstrDesc &GPRIDXDesc =
3728         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3729 
3730     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3731         .addReg(SrcReg)
3732         .addReg(SGPRIdxReg)
3733         .addImm(SubReg);
3734   } else {
3735     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3736       .addReg(SrcReg, 0, SubReg)
3737       .addReg(SrcReg, RegState::Implicit);
3738   }
3739 
3740   MI.eraseFromParent();
3741 
3742   return LoopBB;
3743 }
3744 
emitIndirectDst(MachineInstr & MI,MachineBasicBlock & MBB,const GCNSubtarget & ST)3745 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3746                                           MachineBasicBlock &MBB,
3747                                           const GCNSubtarget &ST) {
3748   const SIInstrInfo *TII = ST.getInstrInfo();
3749   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3750   MachineFunction *MF = MBB.getParent();
3751   MachineRegisterInfo &MRI = MF->getRegInfo();
3752 
3753   Register Dst = MI.getOperand(0).getReg();
3754   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3755   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3756   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3757   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3758   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3759   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3760 
3761   // This can be an immediate, but will be folded later.
3762   assert(Val->getReg());
3763 
3764   unsigned SubReg;
3765   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3766                                                          SrcVec->getReg(),
3767                                                          Offset);
3768   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3769 
3770   if (Idx->getReg() == AMDGPU::NoRegister) {
3771     MachineBasicBlock::iterator I(&MI);
3772     const DebugLoc &DL = MI.getDebugLoc();
3773 
3774     assert(Offset == 0);
3775 
3776     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3777         .add(*SrcVec)
3778         .add(*Val)
3779         .addImm(SubReg);
3780 
3781     MI.eraseFromParent();
3782     return &MBB;
3783   }
3784 
3785   // Check for a SGPR index.
3786   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3787     MachineBasicBlock::iterator I(&MI);
3788     const DebugLoc &DL = MI.getDebugLoc();
3789 
3790     if (UseGPRIdxMode) {
3791       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3792 
3793       const MCInstrDesc &GPRIDXDesc =
3794           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3795       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3796           .addReg(SrcVec->getReg())
3797           .add(*Val)
3798           .addReg(Idx)
3799           .addImm(SubReg);
3800     } else {
3801       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3802 
3803       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3804           TRI.getRegSizeInBits(*VecRC), 32, false);
3805       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3806           .addReg(SrcVec->getReg())
3807           .add(*Val)
3808           .addImm(SubReg);
3809     }
3810     MI.eraseFromParent();
3811     return &MBB;
3812   }
3813 
3814   // Control flow needs to be inserted if indexing with a VGPR.
3815   if (Val->isReg())
3816     MRI.clearKillFlags(Val->getReg());
3817 
3818   const DebugLoc &DL = MI.getDebugLoc();
3819 
3820   Register PhiReg = MRI.createVirtualRegister(VecRC);
3821 
3822   Register SGPRIdxReg;
3823   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3824                               UseGPRIdxMode, SGPRIdxReg);
3825   MachineBasicBlock *LoopBB = InsPt->getParent();
3826 
3827   if (UseGPRIdxMode) {
3828     const MCInstrDesc &GPRIDXDesc =
3829         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3830 
3831     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3832         .addReg(PhiReg)
3833         .add(*Val)
3834         .addReg(SGPRIdxReg)
3835         .addImm(AMDGPU::sub0);
3836   } else {
3837     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3838         TRI.getRegSizeInBits(*VecRC), 32, false);
3839     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3840         .addReg(PhiReg)
3841         .add(*Val)
3842         .addImm(AMDGPU::sub0);
3843   }
3844 
3845   MI.eraseFromParent();
3846   return LoopBB;
3847 }
3848 
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const3849 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3850   MachineInstr &MI, MachineBasicBlock *BB) const {
3851 
3852   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3853   MachineFunction *MF = BB->getParent();
3854   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3855 
3856   switch (MI.getOpcode()) {
3857   case AMDGPU::S_UADDO_PSEUDO:
3858   case AMDGPU::S_USUBO_PSEUDO: {
3859     const DebugLoc &DL = MI.getDebugLoc();
3860     MachineOperand &Dest0 = MI.getOperand(0);
3861     MachineOperand &Dest1 = MI.getOperand(1);
3862     MachineOperand &Src0 = MI.getOperand(2);
3863     MachineOperand &Src1 = MI.getOperand(3);
3864 
3865     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3866                        ? AMDGPU::S_ADD_I32
3867                        : AMDGPU::S_SUB_I32;
3868     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3869 
3870     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3871         .addImm(1)
3872         .addImm(0);
3873 
3874     MI.eraseFromParent();
3875     return BB;
3876   }
3877   case AMDGPU::S_ADD_U64_PSEUDO:
3878   case AMDGPU::S_SUB_U64_PSEUDO: {
3879     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3880     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3881     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3882     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3883     const DebugLoc &DL = MI.getDebugLoc();
3884 
3885     MachineOperand &Dest = MI.getOperand(0);
3886     MachineOperand &Src0 = MI.getOperand(1);
3887     MachineOperand &Src1 = MI.getOperand(2);
3888 
3889     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3890     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3891 
3892     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3893         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3894     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3895         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3896 
3897     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3898         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3899     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3900         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3901 
3902     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3903 
3904     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3905     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3906     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3907     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3908     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3909         .addReg(DestSub0)
3910         .addImm(AMDGPU::sub0)
3911         .addReg(DestSub1)
3912         .addImm(AMDGPU::sub1);
3913     MI.eraseFromParent();
3914     return BB;
3915   }
3916   case AMDGPU::V_ADD_U64_PSEUDO:
3917   case AMDGPU::V_SUB_U64_PSEUDO: {
3918     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3919     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3920     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3921     const DebugLoc &DL = MI.getDebugLoc();
3922 
3923     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3924 
3925     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3926 
3927     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3928     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3929 
3930     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3931     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3932 
3933     MachineOperand &Dest = MI.getOperand(0);
3934     MachineOperand &Src0 = MI.getOperand(1);
3935     MachineOperand &Src1 = MI.getOperand(2);
3936 
3937     const TargetRegisterClass *Src0RC = Src0.isReg()
3938                                             ? MRI.getRegClass(Src0.getReg())
3939                                             : &AMDGPU::VReg_64RegClass;
3940     const TargetRegisterClass *Src1RC = Src1.isReg()
3941                                             ? MRI.getRegClass(Src1.getReg())
3942                                             : &AMDGPU::VReg_64RegClass;
3943 
3944     const TargetRegisterClass *Src0SubRC =
3945         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3946     const TargetRegisterClass *Src1SubRC =
3947         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3948 
3949     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3950         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3951     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3952         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3953 
3954     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3955         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3956     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3957         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3958 
3959     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3960     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3961                                .addReg(CarryReg, RegState::Define)
3962                                .add(SrcReg0Sub0)
3963                                .add(SrcReg1Sub0)
3964                                .addImm(0); // clamp bit
3965 
3966     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3967     MachineInstr *HiHalf =
3968         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3969             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3970             .add(SrcReg0Sub1)
3971             .add(SrcReg1Sub1)
3972             .addReg(CarryReg, RegState::Kill)
3973             .addImm(0); // clamp bit
3974 
3975     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3976         .addReg(DestSub0)
3977         .addImm(AMDGPU::sub0)
3978         .addReg(DestSub1)
3979         .addImm(AMDGPU::sub1);
3980     TII->legalizeOperands(*LoHalf);
3981     TII->legalizeOperands(*HiHalf);
3982     MI.eraseFromParent();
3983     return BB;
3984   }
3985   case AMDGPU::S_ADD_CO_PSEUDO:
3986   case AMDGPU::S_SUB_CO_PSEUDO: {
3987     // This pseudo has a chance to be selected
3988     // only from uniform add/subcarry node. All the VGPR operands
3989     // therefore assumed to be splat vectors.
3990     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3991     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3992     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3993     MachineBasicBlock::iterator MII = MI;
3994     const DebugLoc &DL = MI.getDebugLoc();
3995     MachineOperand &Dest = MI.getOperand(0);
3996     MachineOperand &CarryDest = MI.getOperand(1);
3997     MachineOperand &Src0 = MI.getOperand(2);
3998     MachineOperand &Src1 = MI.getOperand(3);
3999     MachineOperand &Src2 = MI.getOperand(4);
4000     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4001                        ? AMDGPU::S_ADDC_U32
4002                        : AMDGPU::S_SUBB_U32;
4003     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4004       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4005       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4006           .addReg(Src0.getReg());
4007       Src0.setReg(RegOp0);
4008     }
4009     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4010       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4011       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4012           .addReg(Src1.getReg());
4013       Src1.setReg(RegOp1);
4014     }
4015     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4016     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4017       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4018           .addReg(Src2.getReg());
4019       Src2.setReg(RegOp2);
4020     }
4021 
4022     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4023     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4024       if (ST.hasScalarCompareEq64()) {
4025         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4026             .addReg(Src2.getReg())
4027             .addImm(0);
4028       } else {
4029         const TargetRegisterClass *SubRC =
4030             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4031         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4032             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4033         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4034             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4035         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4036 
4037         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4038             .add(Src2Sub0)
4039             .add(Src2Sub1);
4040 
4041         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4042             .addReg(Src2_32, RegState::Kill)
4043             .addImm(0);
4044       }
4045     } else {
4046       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4047           .addReg(Src2.getReg())
4048           .addImm(0);
4049     }
4050 
4051     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4052 
4053     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4054       .addReg(AMDGPU::SCC);
4055     MI.eraseFromParent();
4056     return BB;
4057   }
4058   case AMDGPU::SI_INIT_M0: {
4059     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4060             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4061         .add(MI.getOperand(0));
4062     MI.eraseFromParent();
4063     return BB;
4064   }
4065   case AMDGPU::SI_INIT_EXEC:
4066     // This should be before all vector instructions.
4067     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
4068             AMDGPU::EXEC)
4069         .addImm(MI.getOperand(0).getImm());
4070     MI.eraseFromParent();
4071     return BB;
4072 
4073   case AMDGPU::SI_INIT_EXEC_LO:
4074     // This should be before all vector instructions.
4075     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
4076             AMDGPU::EXEC_LO)
4077         .addImm(MI.getOperand(0).getImm());
4078     MI.eraseFromParent();
4079     return BB;
4080 
4081   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
4082     // Extract the thread count from an SGPR input and set EXEC accordingly.
4083     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
4084     //
4085     // S_BFE_U32 count, input, {shift, 7}
4086     // S_BFM_B64 exec, count, 0
4087     // S_CMP_EQ_U32 count, 64
4088     // S_CMOV_B64 exec, -1
4089     MachineInstr *FirstMI = &*BB->begin();
4090     MachineRegisterInfo &MRI = MF->getRegInfo();
4091     Register InputReg = MI.getOperand(0).getReg();
4092     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4093     bool Found = false;
4094 
4095     // Move the COPY of the input reg to the beginning, so that we can use it.
4096     for (auto I = BB->begin(); I != &MI; I++) {
4097       if (I->getOpcode() != TargetOpcode::COPY ||
4098           I->getOperand(0).getReg() != InputReg)
4099         continue;
4100 
4101       if (I == FirstMI) {
4102         FirstMI = &*++BB->begin();
4103       } else {
4104         I->removeFromParent();
4105         BB->insert(FirstMI, &*I);
4106       }
4107       Found = true;
4108       break;
4109     }
4110     assert(Found);
4111     (void)Found;
4112 
4113     // This should be before all vector instructions.
4114     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
4115     bool isWave32 = getSubtarget()->isWave32();
4116     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4117     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
4118         .addReg(InputReg)
4119         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
4120     BuildMI(*BB, FirstMI, DebugLoc(),
4121             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
4122             Exec)
4123         .addReg(CountReg)
4124         .addImm(0);
4125     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
4126         .addReg(CountReg, RegState::Kill)
4127         .addImm(getSubtarget()->getWavefrontSize());
4128     BuildMI(*BB, FirstMI, DebugLoc(),
4129             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
4130             Exec)
4131         .addImm(-1);
4132     MI.eraseFromParent();
4133     return BB;
4134   }
4135 
4136   case AMDGPU::GET_GROUPSTATICSIZE: {
4137     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4138            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4139     DebugLoc DL = MI.getDebugLoc();
4140     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4141         .add(MI.getOperand(0))
4142         .addImm(MFI->getLDSSize());
4143     MI.eraseFromParent();
4144     return BB;
4145   }
4146   case AMDGPU::SI_INDIRECT_SRC_V1:
4147   case AMDGPU::SI_INDIRECT_SRC_V2:
4148   case AMDGPU::SI_INDIRECT_SRC_V4:
4149   case AMDGPU::SI_INDIRECT_SRC_V8:
4150   case AMDGPU::SI_INDIRECT_SRC_V16:
4151   case AMDGPU::SI_INDIRECT_SRC_V32:
4152     return emitIndirectSrc(MI, *BB, *getSubtarget());
4153   case AMDGPU::SI_INDIRECT_DST_V1:
4154   case AMDGPU::SI_INDIRECT_DST_V2:
4155   case AMDGPU::SI_INDIRECT_DST_V4:
4156   case AMDGPU::SI_INDIRECT_DST_V8:
4157   case AMDGPU::SI_INDIRECT_DST_V16:
4158   case AMDGPU::SI_INDIRECT_DST_V32:
4159     return emitIndirectDst(MI, *BB, *getSubtarget());
4160   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4161   case AMDGPU::SI_KILL_I1_PSEUDO:
4162     return splitKillBlock(MI, BB);
4163   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4164     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4165     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4166     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4167 
4168     Register Dst = MI.getOperand(0).getReg();
4169     Register Src0 = MI.getOperand(1).getReg();
4170     Register Src1 = MI.getOperand(2).getReg();
4171     const DebugLoc &DL = MI.getDebugLoc();
4172     Register SrcCond = MI.getOperand(3).getReg();
4173 
4174     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4175     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4176     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4177     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4178 
4179     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4180       .addReg(SrcCond);
4181     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4182       .addImm(0)
4183       .addReg(Src0, 0, AMDGPU::sub0)
4184       .addImm(0)
4185       .addReg(Src1, 0, AMDGPU::sub0)
4186       .addReg(SrcCondCopy);
4187     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4188       .addImm(0)
4189       .addReg(Src0, 0, AMDGPU::sub1)
4190       .addImm(0)
4191       .addReg(Src1, 0, AMDGPU::sub1)
4192       .addReg(SrcCondCopy);
4193 
4194     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4195       .addReg(DstLo)
4196       .addImm(AMDGPU::sub0)
4197       .addReg(DstHi)
4198       .addImm(AMDGPU::sub1);
4199     MI.eraseFromParent();
4200     return BB;
4201   }
4202   case AMDGPU::SI_BR_UNDEF: {
4203     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4204     const DebugLoc &DL = MI.getDebugLoc();
4205     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4206                            .add(MI.getOperand(0));
4207     Br->getOperand(1).setIsUndef(true); // read undef SCC
4208     MI.eraseFromParent();
4209     return BB;
4210   }
4211   case AMDGPU::ADJCALLSTACKUP:
4212   case AMDGPU::ADJCALLSTACKDOWN: {
4213     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4214     MachineInstrBuilder MIB(*MF, &MI);
4215     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4216        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4217     return BB;
4218   }
4219   case AMDGPU::SI_CALL_ISEL: {
4220     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4221     const DebugLoc &DL = MI.getDebugLoc();
4222 
4223     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4224 
4225     MachineInstrBuilder MIB;
4226     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4227 
4228     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4229       MIB.add(MI.getOperand(I));
4230 
4231     MIB.cloneMemRefs(MI);
4232     MI.eraseFromParent();
4233     return BB;
4234   }
4235   case AMDGPU::V_ADD_CO_U32_e32:
4236   case AMDGPU::V_SUB_CO_U32_e32:
4237   case AMDGPU::V_SUBREV_CO_U32_e32: {
4238     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4239     const DebugLoc &DL = MI.getDebugLoc();
4240     unsigned Opc = MI.getOpcode();
4241 
4242     bool NeedClampOperand = false;
4243     if (TII->pseudoToMCOpcode(Opc) == -1) {
4244       Opc = AMDGPU::getVOPe64(Opc);
4245       NeedClampOperand = true;
4246     }
4247 
4248     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4249     if (TII->isVOP3(*I)) {
4250       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4251       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4252       I.addReg(TRI->getVCC(), RegState::Define);
4253     }
4254     I.add(MI.getOperand(1))
4255      .add(MI.getOperand(2));
4256     if (NeedClampOperand)
4257       I.addImm(0); // clamp bit for e64 encoding
4258 
4259     TII->legalizeOperands(*I);
4260 
4261     MI.eraseFromParent();
4262     return BB;
4263   }
4264   case AMDGPU::DS_GWS_INIT:
4265   case AMDGPU::DS_GWS_SEMA_V:
4266   case AMDGPU::DS_GWS_SEMA_BR:
4267   case AMDGPU::DS_GWS_SEMA_P:
4268   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4269   case AMDGPU::DS_GWS_BARRIER:
4270     // A s_waitcnt 0 is required to be the instruction immediately following.
4271     if (getSubtarget()->hasGWSAutoReplay()) {
4272       bundleInstWithWaitcnt(MI);
4273       return BB;
4274     }
4275 
4276     return emitGWSMemViolTestLoop(MI, BB);
4277   case AMDGPU::S_SETREG_B32: {
4278     // Try to optimize cases that only set the denormal mode or rounding mode.
4279     //
4280     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4281     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4282     // instead.
4283     //
4284     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4285     // allow you to have a no side effect instruction in the output of a
4286     // sideeffecting pattern.
4287     unsigned ID, Offset, Width;
4288     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4289     if (ID != AMDGPU::Hwreg::ID_MODE)
4290       return BB;
4291 
4292     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4293     const unsigned SetMask = WidthMask << Offset;
4294 
4295     if (getSubtarget()->hasDenormModeInst()) {
4296       unsigned SetDenormOp = 0;
4297       unsigned SetRoundOp = 0;
4298 
4299       // The dedicated instructions can only set the whole denorm or round mode
4300       // at once, not a subset of bits in either.
4301       if (SetMask ==
4302           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4303         // If this fully sets both the round and denorm mode, emit the two
4304         // dedicated instructions for these.
4305         SetRoundOp = AMDGPU::S_ROUND_MODE;
4306         SetDenormOp = AMDGPU::S_DENORM_MODE;
4307       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4308         SetRoundOp = AMDGPU::S_ROUND_MODE;
4309       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4310         SetDenormOp = AMDGPU::S_DENORM_MODE;
4311       }
4312 
4313       if (SetRoundOp || SetDenormOp) {
4314         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4315         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4316         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4317           unsigned ImmVal = Def->getOperand(1).getImm();
4318           if (SetRoundOp) {
4319             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4320                 .addImm(ImmVal & 0xf);
4321 
4322             // If we also have the denorm mode, get just the denorm mode bits.
4323             ImmVal >>= 4;
4324           }
4325 
4326           if (SetDenormOp) {
4327             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4328                 .addImm(ImmVal & 0xf);
4329           }
4330 
4331           MI.eraseFromParent();
4332           return BB;
4333         }
4334       }
4335     }
4336 
4337     // If only FP bits are touched, used the no side effects pseudo.
4338     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4339                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4340       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4341 
4342     return BB;
4343   }
4344   default:
4345     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4346   }
4347 }
4348 
hasBitPreservingFPLogic(EVT VT) const4349 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4350   return isTypeLegal(VT.getScalarType());
4351 }
4352 
enableAggressiveFMAFusion(EVT VT) const4353 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4354   // This currently forces unfolding various combinations of fsub into fma with
4355   // free fneg'd operands. As long as we have fast FMA (controlled by
4356   // isFMAFasterThanFMulAndFAdd), we should perform these.
4357 
4358   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4359   // most of these combines appear to be cycle neutral but save on instruction
4360   // count / code size.
4361   return true;
4362 }
4363 
getSetCCResultType(const DataLayout & DL,LLVMContext & Ctx,EVT VT) const4364 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4365                                          EVT VT) const {
4366   if (!VT.isVector()) {
4367     return MVT::i1;
4368   }
4369   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4370 }
4371 
getScalarShiftAmountTy(const DataLayout &,EVT VT) const4372 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4373   // TODO: Should i16 be used always if legal? For now it would force VALU
4374   // shifts.
4375   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4376 }
4377 
getPreferredShiftAmountTy(LLT Ty) const4378 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4379   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4380              ? Ty.changeElementSize(16)
4381              : Ty.changeElementSize(32);
4382 }
4383 
4384 // Answering this is somewhat tricky and depends on the specific device which
4385 // have different rates for fma or all f64 operations.
4386 //
4387 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4388 // regardless of which device (although the number of cycles differs between
4389 // devices), so it is always profitable for f64.
4390 //
4391 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4392 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4393 // which we can always do even without fused FP ops since it returns the same
4394 // result as the separate operations and since it is always full
4395 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4396 // however does not support denormals, so we do report fma as faster if we have
4397 // a fast fma device and require denormals.
4398 //
isFMAFasterThanFMulAndFAdd(const MachineFunction & MF,EVT VT) const4399 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4400                                                   EVT VT) const {
4401   VT = VT.getScalarType();
4402 
4403   switch (VT.getSimpleVT().SimpleTy) {
4404   case MVT::f32: {
4405     // If mad is not available this depends only on if f32 fma is full rate.
4406     if (!Subtarget->hasMadMacF32Insts())
4407       return Subtarget->hasFastFMAF32();
4408 
4409     // Otherwise f32 mad is always full rate and returns the same result as
4410     // the separate operations so should be preferred over fma.
4411     // However does not support denomals.
4412     if (hasFP32Denormals(MF))
4413       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4414 
4415     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4416     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4417   }
4418   case MVT::f64:
4419     return true;
4420   case MVT::f16:
4421     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4422   default:
4423     break;
4424   }
4425 
4426   return false;
4427 }
4428 
isFMADLegal(const SelectionDAG & DAG,const SDNode * N) const4429 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4430                                    const SDNode *N) const {
4431   // TODO: Check future ftz flag
4432   // v_mad_f32/v_mac_f32 do not support denormals.
4433   EVT VT = N->getValueType(0);
4434   if (VT == MVT::f32)
4435     return Subtarget->hasMadMacF32Insts() &&
4436            !hasFP32Denormals(DAG.getMachineFunction());
4437   if (VT == MVT::f16) {
4438     return Subtarget->hasMadF16() &&
4439            !hasFP64FP16Denormals(DAG.getMachineFunction());
4440   }
4441 
4442   return false;
4443 }
4444 
4445 //===----------------------------------------------------------------------===//
4446 // Custom DAG Lowering Operations
4447 //===----------------------------------------------------------------------===//
4448 
4449 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4450 // wider vector type is legal.
splitUnaryVectorOp(SDValue Op,SelectionDAG & DAG) const4451 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4452                                              SelectionDAG &DAG) const {
4453   unsigned Opc = Op.getOpcode();
4454   EVT VT = Op.getValueType();
4455   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4456 
4457   SDValue Lo, Hi;
4458   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4459 
4460   SDLoc SL(Op);
4461   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4462                              Op->getFlags());
4463   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4464                              Op->getFlags());
4465 
4466   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4467 }
4468 
4469 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4470 // wider vector type is legal.
splitBinaryVectorOp(SDValue Op,SelectionDAG & DAG) const4471 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4472                                               SelectionDAG &DAG) const {
4473   unsigned Opc = Op.getOpcode();
4474   EVT VT = Op.getValueType();
4475   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4476 
4477   SDValue Lo0, Hi0;
4478   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4479   SDValue Lo1, Hi1;
4480   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4481 
4482   SDLoc SL(Op);
4483 
4484   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4485                              Op->getFlags());
4486   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4487                              Op->getFlags());
4488 
4489   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4490 }
4491 
splitTernaryVectorOp(SDValue Op,SelectionDAG & DAG) const4492 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4493                                               SelectionDAG &DAG) const {
4494   unsigned Opc = Op.getOpcode();
4495   EVT VT = Op.getValueType();
4496   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4497 
4498   SDValue Lo0, Hi0;
4499   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4500   SDValue Lo1, Hi1;
4501   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4502   SDValue Lo2, Hi2;
4503   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4504 
4505   SDLoc SL(Op);
4506 
4507   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4508                              Op->getFlags());
4509   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4510                              Op->getFlags());
4511 
4512   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4513 }
4514 
4515 
LowerOperation(SDValue Op,SelectionDAG & DAG) const4516 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4517   switch (Op.getOpcode()) {
4518   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4519   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4520   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4521   case ISD::LOAD: {
4522     SDValue Result = LowerLOAD(Op, DAG);
4523     assert((!Result.getNode() ||
4524             Result.getNode()->getNumValues() == 2) &&
4525            "Load should return a value and a chain");
4526     return Result;
4527   }
4528 
4529   case ISD::FSIN:
4530   case ISD::FCOS:
4531     return LowerTrig(Op, DAG);
4532   case ISD::SELECT: return LowerSELECT(Op, DAG);
4533   case ISD::FDIV: return LowerFDIV(Op, DAG);
4534   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4535   case ISD::STORE: return LowerSTORE(Op, DAG);
4536   case ISD::GlobalAddress: {
4537     MachineFunction &MF = DAG.getMachineFunction();
4538     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4539     return LowerGlobalAddress(MFI, Op, DAG);
4540   }
4541   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4542   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4543   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4544   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4545   case ISD::INSERT_SUBVECTOR:
4546     return lowerINSERT_SUBVECTOR(Op, DAG);
4547   case ISD::INSERT_VECTOR_ELT:
4548     return lowerINSERT_VECTOR_ELT(Op, DAG);
4549   case ISD::EXTRACT_VECTOR_ELT:
4550     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4551   case ISD::VECTOR_SHUFFLE:
4552     return lowerVECTOR_SHUFFLE(Op, DAG);
4553   case ISD::BUILD_VECTOR:
4554     return lowerBUILD_VECTOR(Op, DAG);
4555   case ISD::FP_ROUND:
4556     return lowerFP_ROUND(Op, DAG);
4557   case ISD::TRAP:
4558     return lowerTRAP(Op, DAG);
4559   case ISD::DEBUGTRAP:
4560     return lowerDEBUGTRAP(Op, DAG);
4561   case ISD::FABS:
4562   case ISD::FNEG:
4563   case ISD::FCANONICALIZE:
4564   case ISD::BSWAP:
4565     return splitUnaryVectorOp(Op, DAG);
4566   case ISD::FMINNUM:
4567   case ISD::FMAXNUM:
4568     return lowerFMINNUM_FMAXNUM(Op, DAG);
4569   case ISD::FMA:
4570     return splitTernaryVectorOp(Op, DAG);
4571   case ISD::SHL:
4572   case ISD::SRA:
4573   case ISD::SRL:
4574   case ISD::ADD:
4575   case ISD::SUB:
4576   case ISD::MUL:
4577   case ISD::SMIN:
4578   case ISD::SMAX:
4579   case ISD::UMIN:
4580   case ISD::UMAX:
4581   case ISD::FADD:
4582   case ISD::FMUL:
4583   case ISD::FMINNUM_IEEE:
4584   case ISD::FMAXNUM_IEEE:
4585   case ISD::UADDSAT:
4586   case ISD::USUBSAT:
4587   case ISD::SADDSAT:
4588   case ISD::SSUBSAT:
4589     return splitBinaryVectorOp(Op, DAG);
4590   case ISD::SMULO:
4591   case ISD::UMULO:
4592     return lowerXMULO(Op, DAG);
4593   case ISD::DYNAMIC_STACKALLOC:
4594     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4595   }
4596   return SDValue();
4597 }
4598 
4599 // Used for D16: Casts the result of an instruction into the right vector,
4600 // packs values if loads return unpacked values.
adjustLoadValueTypeImpl(SDValue Result,EVT LoadVT,const SDLoc & DL,SelectionDAG & DAG,bool Unpacked)4601 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4602                                        const SDLoc &DL,
4603                                        SelectionDAG &DAG, bool Unpacked) {
4604   if (!LoadVT.isVector())
4605     return Result;
4606 
4607   // Cast back to the original packed type or to a larger type that is a
4608   // multiple of 32 bit for D16. Widening the return type is a required for
4609   // legalization.
4610   EVT FittingLoadVT = LoadVT;
4611   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4612     FittingLoadVT =
4613         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4614                          LoadVT.getVectorNumElements() + 1);
4615   }
4616 
4617   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4618     // Truncate to v2i16/v4i16.
4619     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4620 
4621     // Workaround legalizer not scalarizing truncate after vector op
4622     // legalization but not creating intermediate vector trunc.
4623     SmallVector<SDValue, 4> Elts;
4624     DAG.ExtractVectorElements(Result, Elts);
4625     for (SDValue &Elt : Elts)
4626       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4627 
4628     // Pad illegal v1i16/v3fi6 to v4i16
4629     if ((LoadVT.getVectorNumElements() % 2) == 1)
4630       Elts.push_back(DAG.getUNDEF(MVT::i16));
4631 
4632     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4633 
4634     // Bitcast to original type (v2f16/v4f16).
4635     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4636   }
4637 
4638   // Cast back to the original packed type.
4639   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4640 }
4641 
adjustLoadValueType(unsigned Opcode,MemSDNode * M,SelectionDAG & DAG,ArrayRef<SDValue> Ops,bool IsIntrinsic) const4642 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4643                                               MemSDNode *M,
4644                                               SelectionDAG &DAG,
4645                                               ArrayRef<SDValue> Ops,
4646                                               bool IsIntrinsic) const {
4647   SDLoc DL(M);
4648 
4649   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4650   EVT LoadVT = M->getValueType(0);
4651 
4652   EVT EquivLoadVT = LoadVT;
4653   if (LoadVT.isVector()) {
4654     if (Unpacked) {
4655       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4656                                      LoadVT.getVectorNumElements());
4657     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4658       // Widen v3f16 to legal type
4659       EquivLoadVT =
4660           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4661                            LoadVT.getVectorNumElements() + 1);
4662     }
4663   }
4664 
4665   // Change from v4f16/v2f16 to EquivLoadVT.
4666   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4667 
4668   SDValue Load
4669     = DAG.getMemIntrinsicNode(
4670       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4671       VTList, Ops, M->getMemoryVT(),
4672       M->getMemOperand());
4673 
4674   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4675 
4676   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4677 }
4678 
lowerIntrinsicLoad(MemSDNode * M,bool IsFormat,SelectionDAG & DAG,ArrayRef<SDValue> Ops) const4679 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4680                                              SelectionDAG &DAG,
4681                                              ArrayRef<SDValue> Ops) const {
4682   SDLoc DL(M);
4683   EVT LoadVT = M->getValueType(0);
4684   EVT EltType = LoadVT.getScalarType();
4685   EVT IntVT = LoadVT.changeTypeToInteger();
4686 
4687   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4688 
4689   unsigned Opc =
4690       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4691 
4692   if (IsD16) {
4693     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4694   }
4695 
4696   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4697   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4698     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4699 
4700   if (isTypeLegal(LoadVT)) {
4701     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4702                                M->getMemOperand(), DAG);
4703   }
4704 
4705   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4706   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4707   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4708                                         M->getMemOperand(), DAG);
4709   return DAG.getMergeValues(
4710       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4711       DL);
4712 }
4713 
lowerICMPIntrinsic(const SITargetLowering & TLI,SDNode * N,SelectionDAG & DAG)4714 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4715                                   SDNode *N, SelectionDAG &DAG) {
4716   EVT VT = N->getValueType(0);
4717   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4718   unsigned CondCode = CD->getZExtValue();
4719   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4720     return DAG.getUNDEF(VT);
4721 
4722   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4723 
4724   SDValue LHS = N->getOperand(1);
4725   SDValue RHS = N->getOperand(2);
4726 
4727   SDLoc DL(N);
4728 
4729   EVT CmpVT = LHS.getValueType();
4730   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4731     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4732       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4733     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4734     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4735   }
4736 
4737   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4738 
4739   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4740   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4741 
4742   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4743                               DAG.getCondCode(CCOpcode));
4744   if (VT.bitsEq(CCVT))
4745     return SetCC;
4746   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4747 }
4748 
lowerFCMPIntrinsic(const SITargetLowering & TLI,SDNode * N,SelectionDAG & DAG)4749 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4750                                   SDNode *N, SelectionDAG &DAG) {
4751   EVT VT = N->getValueType(0);
4752   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4753 
4754   unsigned CondCode = CD->getZExtValue();
4755   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4756     return DAG.getUNDEF(VT);
4757 
4758   SDValue Src0 = N->getOperand(1);
4759   SDValue Src1 = N->getOperand(2);
4760   EVT CmpVT = Src0.getValueType();
4761   SDLoc SL(N);
4762 
4763   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4764     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4765     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4766   }
4767 
4768   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4769   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4770   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4771   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4772   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4773                               Src1, DAG.getCondCode(CCOpcode));
4774   if (VT.bitsEq(CCVT))
4775     return SetCC;
4776   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4777 }
4778 
lowerBALLOTIntrinsic(const SITargetLowering & TLI,SDNode * N,SelectionDAG & DAG)4779 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4780                                     SelectionDAG &DAG) {
4781   EVT VT = N->getValueType(0);
4782   SDValue Src = N->getOperand(1);
4783   SDLoc SL(N);
4784 
4785   if (Src.getOpcode() == ISD::SETCC) {
4786     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4787     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4788                        Src.getOperand(1), Src.getOperand(2));
4789   }
4790   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4791     // (ballot 0) -> 0
4792     if (Arg->isNullValue())
4793       return DAG.getConstant(0, SL, VT);
4794 
4795     // (ballot 1) -> EXEC/EXEC_LO
4796     if (Arg->isOne()) {
4797       Register Exec;
4798       if (VT.getScalarSizeInBits() == 32)
4799         Exec = AMDGPU::EXEC_LO;
4800       else if (VT.getScalarSizeInBits() == 64)
4801         Exec = AMDGPU::EXEC;
4802       else
4803         return SDValue();
4804 
4805       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4806     }
4807   }
4808 
4809   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4810   // ISD::SETNE)
4811   return DAG.getNode(
4812       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4813       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4814 }
4815 
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const4816 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4817                                           SmallVectorImpl<SDValue> &Results,
4818                                           SelectionDAG &DAG) const {
4819   switch (N->getOpcode()) {
4820   case ISD::INSERT_VECTOR_ELT: {
4821     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4822       Results.push_back(Res);
4823     return;
4824   }
4825   case ISD::EXTRACT_VECTOR_ELT: {
4826     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4827       Results.push_back(Res);
4828     return;
4829   }
4830   case ISD::INTRINSIC_WO_CHAIN: {
4831     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4832     switch (IID) {
4833     case Intrinsic::amdgcn_cvt_pkrtz: {
4834       SDValue Src0 = N->getOperand(1);
4835       SDValue Src1 = N->getOperand(2);
4836       SDLoc SL(N);
4837       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4838                                 Src0, Src1);
4839       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4840       return;
4841     }
4842     case Intrinsic::amdgcn_cvt_pknorm_i16:
4843     case Intrinsic::amdgcn_cvt_pknorm_u16:
4844     case Intrinsic::amdgcn_cvt_pk_i16:
4845     case Intrinsic::amdgcn_cvt_pk_u16: {
4846       SDValue Src0 = N->getOperand(1);
4847       SDValue Src1 = N->getOperand(2);
4848       SDLoc SL(N);
4849       unsigned Opcode;
4850 
4851       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4852         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4853       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4854         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4855       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4856         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4857       else
4858         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4859 
4860       EVT VT = N->getValueType(0);
4861       if (isTypeLegal(VT))
4862         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4863       else {
4864         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4865         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4866       }
4867       return;
4868     }
4869     }
4870     break;
4871   }
4872   case ISD::INTRINSIC_W_CHAIN: {
4873     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4874       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4875         // FIXME: Hacky
4876         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4877           Results.push_back(Res.getOperand(I));
4878         }
4879       } else {
4880         Results.push_back(Res);
4881         Results.push_back(Res.getValue(1));
4882       }
4883       return;
4884     }
4885 
4886     break;
4887   }
4888   case ISD::SELECT: {
4889     SDLoc SL(N);
4890     EVT VT = N->getValueType(0);
4891     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4892     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4893     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4894 
4895     EVT SelectVT = NewVT;
4896     if (NewVT.bitsLT(MVT::i32)) {
4897       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4898       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4899       SelectVT = MVT::i32;
4900     }
4901 
4902     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4903                                     N->getOperand(0), LHS, RHS);
4904 
4905     if (NewVT != SelectVT)
4906       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4907     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4908     return;
4909   }
4910   case ISD::FNEG: {
4911     if (N->getValueType(0) != MVT::v2f16)
4912       break;
4913 
4914     SDLoc SL(N);
4915     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4916 
4917     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4918                              BC,
4919                              DAG.getConstant(0x80008000, SL, MVT::i32));
4920     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4921     return;
4922   }
4923   case ISD::FABS: {
4924     if (N->getValueType(0) != MVT::v2f16)
4925       break;
4926 
4927     SDLoc SL(N);
4928     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4929 
4930     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4931                              BC,
4932                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4933     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4934     return;
4935   }
4936   default:
4937     break;
4938   }
4939 }
4940 
4941 /// Helper function for LowerBRCOND
findUser(SDValue Value,unsigned Opcode)4942 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4943 
4944   SDNode *Parent = Value.getNode();
4945   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4946        I != E; ++I) {
4947 
4948     if (I.getUse().get() != Value)
4949       continue;
4950 
4951     if (I->getOpcode() == Opcode)
4952       return *I;
4953   }
4954   return nullptr;
4955 }
4956 
isCFIntrinsic(const SDNode * Intr) const4957 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4958   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4959     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4960     case Intrinsic::amdgcn_if:
4961       return AMDGPUISD::IF;
4962     case Intrinsic::amdgcn_else:
4963       return AMDGPUISD::ELSE;
4964     case Intrinsic::amdgcn_loop:
4965       return AMDGPUISD::LOOP;
4966     case Intrinsic::amdgcn_end_cf:
4967       llvm_unreachable("should not occur");
4968     default:
4969       return 0;
4970     }
4971   }
4972 
4973   // break, if_break, else_break are all only used as inputs to loop, not
4974   // directly as branch conditions.
4975   return 0;
4976 }
4977 
shouldEmitFixup(const GlobalValue * GV) const4978 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4979   const Triple &TT = getTargetMachine().getTargetTriple();
4980   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4981           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4982          AMDGPU::shouldEmitConstantsToTextSection(TT);
4983 }
4984 
shouldEmitGOTReloc(const GlobalValue * GV) const4985 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4986   // FIXME: Either avoid relying on address space here or change the default
4987   // address space for functions to avoid the explicit check.
4988   return (GV->getValueType()->isFunctionTy() ||
4989           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4990          !shouldEmitFixup(GV) &&
4991          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4992 }
4993 
shouldEmitPCReloc(const GlobalValue * GV) const4994 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4995   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4996 }
4997 
shouldUseLDSConstAddress(const GlobalValue * GV) const4998 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4999   if (!GV->hasExternalLinkage())
5000     return true;
5001 
5002   const auto OS = getTargetMachine().getTargetTriple().getOS();
5003   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5004 }
5005 
5006 /// This transforms the control flow intrinsics to get the branch destination as
5007 /// last parameter, also switches branch target with BR if the need arise
LowerBRCOND(SDValue BRCOND,SelectionDAG & DAG) const5008 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5009                                       SelectionDAG &DAG) const {
5010   SDLoc DL(BRCOND);
5011 
5012   SDNode *Intr = BRCOND.getOperand(1).getNode();
5013   SDValue Target = BRCOND.getOperand(2);
5014   SDNode *BR = nullptr;
5015   SDNode *SetCC = nullptr;
5016 
5017   if (Intr->getOpcode() == ISD::SETCC) {
5018     // As long as we negate the condition everything is fine
5019     SetCC = Intr;
5020     Intr = SetCC->getOperand(0).getNode();
5021 
5022   } else {
5023     // Get the target from BR if we don't negate the condition
5024     BR = findUser(BRCOND, ISD::BR);
5025     assert(BR && "brcond missing unconditional branch user");
5026     Target = BR->getOperand(1);
5027   }
5028 
5029   unsigned CFNode = isCFIntrinsic(Intr);
5030   if (CFNode == 0) {
5031     // This is a uniform branch so we don't need to legalize.
5032     return BRCOND;
5033   }
5034 
5035   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5036                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5037 
5038   assert(!SetCC ||
5039         (SetCC->getConstantOperandVal(1) == 1 &&
5040          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5041                                                              ISD::SETNE));
5042 
5043   // operands of the new intrinsic call
5044   SmallVector<SDValue, 4> Ops;
5045   if (HaveChain)
5046     Ops.push_back(BRCOND.getOperand(0));
5047 
5048   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5049   Ops.push_back(Target);
5050 
5051   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5052 
5053   // build the new intrinsic call
5054   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5055 
5056   if (!HaveChain) {
5057     SDValue Ops[] =  {
5058       SDValue(Result, 0),
5059       BRCOND.getOperand(0)
5060     };
5061 
5062     Result = DAG.getMergeValues(Ops, DL).getNode();
5063   }
5064 
5065   if (BR) {
5066     // Give the branch instruction our target
5067     SDValue Ops[] = {
5068       BR->getOperand(0),
5069       BRCOND.getOperand(2)
5070     };
5071     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5072     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5073   }
5074 
5075   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5076 
5077   // Copy the intrinsic results to registers
5078   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5079     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5080     if (!CopyToReg)
5081       continue;
5082 
5083     Chain = DAG.getCopyToReg(
5084       Chain, DL,
5085       CopyToReg->getOperand(1),
5086       SDValue(Result, i - 1),
5087       SDValue());
5088 
5089     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5090   }
5091 
5092   // Remove the old intrinsic from the chain
5093   DAG.ReplaceAllUsesOfValueWith(
5094     SDValue(Intr, Intr->getNumValues() - 1),
5095     Intr->getOperand(0));
5096 
5097   return Chain;
5098 }
5099 
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const5100 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5101                                           SelectionDAG &DAG) const {
5102   MVT VT = Op.getSimpleValueType();
5103   SDLoc DL(Op);
5104   // Checking the depth
5105   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5106     return DAG.getConstant(0, DL, VT);
5107 
5108   MachineFunction &MF = DAG.getMachineFunction();
5109   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5110   // Check for kernel and shader functions
5111   if (Info->isEntryFunction())
5112     return DAG.getConstant(0, DL, VT);
5113 
5114   MachineFrameInfo &MFI = MF.getFrameInfo();
5115   // There is a call to @llvm.returnaddress in this function
5116   MFI.setReturnAddressIsTaken(true);
5117 
5118   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5119   // Get the return address reg and mark it as an implicit live-in
5120   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5121 
5122   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5123 }
5124 
getFPExtOrFPRound(SelectionDAG & DAG,SDValue Op,const SDLoc & DL,EVT VT) const5125 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5126                                             SDValue Op,
5127                                             const SDLoc &DL,
5128                                             EVT VT) const {
5129   return Op.getValueType().bitsLE(VT) ?
5130       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5131     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5132                 DAG.getTargetConstant(0, DL, MVT::i32));
5133 }
5134 
lowerFP_ROUND(SDValue Op,SelectionDAG & DAG) const5135 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5136   assert(Op.getValueType() == MVT::f16 &&
5137          "Do not know how to custom lower FP_ROUND for non-f16 type");
5138 
5139   SDValue Src = Op.getOperand(0);
5140   EVT SrcVT = Src.getValueType();
5141   if (SrcVT != MVT::f64)
5142     return Op;
5143 
5144   SDLoc DL(Op);
5145 
5146   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5147   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5148   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5149 }
5150 
lowerFMINNUM_FMAXNUM(SDValue Op,SelectionDAG & DAG) const5151 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5152                                                SelectionDAG &DAG) const {
5153   EVT VT = Op.getValueType();
5154   const MachineFunction &MF = DAG.getMachineFunction();
5155   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5156   bool IsIEEEMode = Info->getMode().IEEE;
5157 
5158   // FIXME: Assert during selection that this is only selected for
5159   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5160   // mode functions, but this happens to be OK since it's only done in cases
5161   // where there is known no sNaN.
5162   if (IsIEEEMode)
5163     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5164 
5165   if (VT == MVT::v4f16)
5166     return splitBinaryVectorOp(Op, DAG);
5167   return Op;
5168 }
5169 
lowerXMULO(SDValue Op,SelectionDAG & DAG) const5170 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5171   EVT VT = Op.getValueType();
5172   SDLoc SL(Op);
5173   SDValue LHS = Op.getOperand(0);
5174   SDValue RHS = Op.getOperand(1);
5175   bool isSigned = Op.getOpcode() == ISD::SMULO;
5176 
5177   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5178     const APInt &C = RHSC->getAPIntValue();
5179     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5180     if (C.isPowerOf2()) {
5181       // smulo(x, signed_min) is same as umulo(x, signed_min).
5182       bool UseArithShift = isSigned && !C.isMinSignedValue();
5183       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5184       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5185       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5186           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5187                       SL, VT, Result, ShiftAmt),
5188           LHS, ISD::SETNE);
5189       return DAG.getMergeValues({ Result, Overflow }, SL);
5190     }
5191   }
5192 
5193   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5194   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5195                             SL, VT, LHS, RHS);
5196 
5197   SDValue Sign = isSigned
5198     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5199                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5200     : DAG.getConstant(0, SL, VT);
5201   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5202 
5203   return DAG.getMergeValues({ Result, Overflow }, SL);
5204 }
5205 
lowerTRAP(SDValue Op,SelectionDAG & DAG) const5206 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5207   SDLoc SL(Op);
5208   SDValue Chain = Op.getOperand(0);
5209 
5210   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5211       !Subtarget->isTrapHandlerEnabled())
5212     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5213 
5214   MachineFunction &MF = DAG.getMachineFunction();
5215   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5216   Register UserSGPR = Info->getQueuePtrUserSGPR();
5217   assert(UserSGPR != AMDGPU::NoRegister);
5218   SDValue QueuePtr = CreateLiveInRegister(
5219     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5220   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5221   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5222                                    QueuePtr, SDValue());
5223   SDValue Ops[] = {
5224     ToReg,
5225     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5226     SGPR01,
5227     ToReg.getValue(1)
5228   };
5229   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5230 }
5231 
lowerDEBUGTRAP(SDValue Op,SelectionDAG & DAG) const5232 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5233   SDLoc SL(Op);
5234   SDValue Chain = Op.getOperand(0);
5235   MachineFunction &MF = DAG.getMachineFunction();
5236 
5237   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5238       !Subtarget->isTrapHandlerEnabled()) {
5239     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5240                                      "debugtrap handler not supported",
5241                                      Op.getDebugLoc(),
5242                                      DS_Warning);
5243     LLVMContext &Ctx = MF.getFunction().getContext();
5244     Ctx.diagnose(NoTrap);
5245     return Chain;
5246   }
5247 
5248   SDValue Ops[] = {
5249     Chain,
5250     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5251   };
5252   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5253 }
5254 
getSegmentAperture(unsigned AS,const SDLoc & DL,SelectionDAG & DAG) const5255 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5256                                              SelectionDAG &DAG) const {
5257   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5258   if (Subtarget->hasApertureRegs()) {
5259     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5260         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5261         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5262     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5263         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5264         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5265     unsigned Encoding =
5266         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5267         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5268         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5269 
5270     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5271     SDValue ApertureReg = SDValue(
5272         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5273     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5274     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5275   }
5276 
5277   MachineFunction &MF = DAG.getMachineFunction();
5278   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5279   Register UserSGPR = Info->getQueuePtrUserSGPR();
5280   assert(UserSGPR != AMDGPU::NoRegister);
5281 
5282   SDValue QueuePtr = CreateLiveInRegister(
5283     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5284 
5285   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5286   // private_segment_aperture_base_hi.
5287   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5288 
5289   SDValue Ptr =
5290       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5291 
5292   // TODO: Use custom target PseudoSourceValue.
5293   // TODO: We should use the value from the IR intrinsic call, but it might not
5294   // be available and how do we get it?
5295   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5296   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5297                      commonAlignment(Align(64), StructOffset),
5298                      MachineMemOperand::MODereferenceable |
5299                          MachineMemOperand::MOInvariant);
5300 }
5301 
lowerADDRSPACECAST(SDValue Op,SelectionDAG & DAG) const5302 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5303                                              SelectionDAG &DAG) const {
5304   SDLoc SL(Op);
5305   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5306 
5307   SDValue Src = ASC->getOperand(0);
5308   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5309 
5310   const AMDGPUTargetMachine &TM =
5311     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5312 
5313   // flat -> local/private
5314   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5315     unsigned DestAS = ASC->getDestAddressSpace();
5316 
5317     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5318         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5319       unsigned NullVal = TM.getNullPointerValue(DestAS);
5320       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5321       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5322       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5323 
5324       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5325                          NonNull, Ptr, SegmentNullPtr);
5326     }
5327   }
5328 
5329   // local/private -> flat
5330   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5331     unsigned SrcAS = ASC->getSrcAddressSpace();
5332 
5333     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5334         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5335       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5336       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5337 
5338       SDValue NonNull
5339         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5340 
5341       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5342       SDValue CvtPtr
5343         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5344 
5345       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5346                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5347                          FlatNullPtr);
5348     }
5349   }
5350 
5351   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5352       Src.getValueType() == MVT::i64)
5353     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5354 
5355   // global <-> flat are no-ops and never emitted.
5356 
5357   const MachineFunction &MF = DAG.getMachineFunction();
5358   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5359     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5360   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5361 
5362   return DAG.getUNDEF(ASC->getValueType(0));
5363 }
5364 
5365 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5366 // the small vector and inserting them into the big vector. That is better than
5367 // the default expansion of doing it via a stack slot. Even though the use of
5368 // the stack slot would be optimized away afterwards, the stack slot itself
5369 // remains.
lowerINSERT_SUBVECTOR(SDValue Op,SelectionDAG & DAG) const5370 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5371                                                 SelectionDAG &DAG) const {
5372   SDValue Vec = Op.getOperand(0);
5373   SDValue Ins = Op.getOperand(1);
5374   SDValue Idx = Op.getOperand(2);
5375   EVT VecVT = Vec.getValueType();
5376   EVT InsVT = Ins.getValueType();
5377   EVT EltVT = VecVT.getVectorElementType();
5378   unsigned InsNumElts = InsVT.getVectorNumElements();
5379   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5380   SDLoc SL(Op);
5381 
5382   for (unsigned I = 0; I != InsNumElts; ++I) {
5383     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5384                               DAG.getConstant(I, SL, MVT::i32));
5385     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5386                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5387   }
5388   return Vec;
5389 }
5390 
lowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const5391 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5392                                                  SelectionDAG &DAG) const {
5393   SDValue Vec = Op.getOperand(0);
5394   SDValue InsVal = Op.getOperand(1);
5395   SDValue Idx = Op.getOperand(2);
5396   EVT VecVT = Vec.getValueType();
5397   EVT EltVT = VecVT.getVectorElementType();
5398   unsigned VecSize = VecVT.getSizeInBits();
5399   unsigned EltSize = EltVT.getSizeInBits();
5400 
5401 
5402   assert(VecSize <= 64);
5403 
5404   unsigned NumElts = VecVT.getVectorNumElements();
5405   SDLoc SL(Op);
5406   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5407 
5408   if (NumElts == 4 && EltSize == 16 && KIdx) {
5409     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5410 
5411     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5412                                  DAG.getConstant(0, SL, MVT::i32));
5413     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5414                                  DAG.getConstant(1, SL, MVT::i32));
5415 
5416     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5417     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5418 
5419     unsigned Idx = KIdx->getZExtValue();
5420     bool InsertLo = Idx < 2;
5421     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5422       InsertLo ? LoVec : HiVec,
5423       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5424       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5425 
5426     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5427 
5428     SDValue Concat = InsertLo ?
5429       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5430       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5431 
5432     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5433   }
5434 
5435   if (isa<ConstantSDNode>(Idx))
5436     return SDValue();
5437 
5438   MVT IntVT = MVT::getIntegerVT(VecSize);
5439 
5440   // Avoid stack access for dynamic indexing.
5441   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5442 
5443   // Create a congruent vector with the target value in each element so that
5444   // the required element can be masked and ORed into the target vector.
5445   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5446                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5447 
5448   assert(isPowerOf2_32(EltSize));
5449   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5450 
5451   // Convert vector index to bit-index.
5452   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5453 
5454   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5455   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5456                             DAG.getConstant(0xffff, SL, IntVT),
5457                             ScaledIdx);
5458 
5459   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5460   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5461                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5462 
5463   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5464   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5465 }
5466 
lowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const5467 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5468                                                   SelectionDAG &DAG) const {
5469   SDLoc SL(Op);
5470 
5471   EVT ResultVT = Op.getValueType();
5472   SDValue Vec = Op.getOperand(0);
5473   SDValue Idx = Op.getOperand(1);
5474   EVT VecVT = Vec.getValueType();
5475   unsigned VecSize = VecVT.getSizeInBits();
5476   EVT EltVT = VecVT.getVectorElementType();
5477   assert(VecSize <= 64);
5478 
5479   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5480 
5481   // Make sure we do any optimizations that will make it easier to fold
5482   // source modifiers before obscuring it with bit operations.
5483 
5484   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5485   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5486     return Combined;
5487 
5488   unsigned EltSize = EltVT.getSizeInBits();
5489   assert(isPowerOf2_32(EltSize));
5490 
5491   MVT IntVT = MVT::getIntegerVT(VecSize);
5492   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5493 
5494   // Convert vector index to bit-index (* EltSize)
5495   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5496 
5497   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5498   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5499 
5500   if (ResultVT == MVT::f16) {
5501     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5502     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5503   }
5504 
5505   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5506 }
5507 
elementPairIsContiguous(ArrayRef<int> Mask,int Elt)5508 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5509   assert(Elt % 2 == 0);
5510   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5511 }
5512 
lowerVECTOR_SHUFFLE(SDValue Op,SelectionDAG & DAG) const5513 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5514                                               SelectionDAG &DAG) const {
5515   SDLoc SL(Op);
5516   EVT ResultVT = Op.getValueType();
5517   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5518 
5519   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5520   EVT EltVT = PackVT.getVectorElementType();
5521   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5522 
5523   // vector_shuffle <0,1,6,7> lhs, rhs
5524   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5525   //
5526   // vector_shuffle <6,7,2,3> lhs, rhs
5527   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5528   //
5529   // vector_shuffle <6,7,0,1> lhs, rhs
5530   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5531 
5532   // Avoid scalarizing when both halves are reading from consecutive elements.
5533   SmallVector<SDValue, 4> Pieces;
5534   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5535     if (elementPairIsContiguous(SVN->getMask(), I)) {
5536       const int Idx = SVN->getMaskElt(I);
5537       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5538       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5539       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5540                                     PackVT, SVN->getOperand(VecIdx),
5541                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5542       Pieces.push_back(SubVec);
5543     } else {
5544       const int Idx0 = SVN->getMaskElt(I);
5545       const int Idx1 = SVN->getMaskElt(I + 1);
5546       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5547       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5548       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5549       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5550 
5551       SDValue Vec0 = SVN->getOperand(VecIdx0);
5552       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5553                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5554 
5555       SDValue Vec1 = SVN->getOperand(VecIdx1);
5556       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5557                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5558       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5559     }
5560   }
5561 
5562   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5563 }
5564 
lowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG) const5565 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5566                                             SelectionDAG &DAG) const {
5567   SDLoc SL(Op);
5568   EVT VT = Op.getValueType();
5569 
5570   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5571     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5572 
5573     // Turn into pair of packed build_vectors.
5574     // TODO: Special case for constants that can be materialized with s_mov_b64.
5575     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5576                                     { Op.getOperand(0), Op.getOperand(1) });
5577     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5578                                     { Op.getOperand(2), Op.getOperand(3) });
5579 
5580     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5581     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5582 
5583     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5584     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5585   }
5586 
5587   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5588   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5589 
5590   SDValue Lo = Op.getOperand(0);
5591   SDValue Hi = Op.getOperand(1);
5592 
5593   // Avoid adding defined bits with the zero_extend.
5594   if (Hi.isUndef()) {
5595     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5596     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5597     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5598   }
5599 
5600   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5601   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5602 
5603   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5604                               DAG.getConstant(16, SL, MVT::i32));
5605   if (Lo.isUndef())
5606     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5607 
5608   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5609   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5610 
5611   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5612   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5613 }
5614 
5615 bool
isOffsetFoldingLegal(const GlobalAddressSDNode * GA) const5616 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5617   // We can fold offsets for anything that doesn't require a GOT relocation.
5618   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5619           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5620           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5621          !shouldEmitGOTReloc(GA->getGlobal());
5622 }
5623 
5624 static SDValue
buildPCRelGlobalAddress(SelectionDAG & DAG,const GlobalValue * GV,const SDLoc & DL,int64_t Offset,EVT PtrVT,unsigned GAFlags=SIInstrInfo::MO_NONE)5625 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5626                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5627                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5628   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5629   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5630   // lowered to the following code sequence:
5631   //
5632   // For constant address space:
5633   //   s_getpc_b64 s[0:1]
5634   //   s_add_u32 s0, s0, $symbol
5635   //   s_addc_u32 s1, s1, 0
5636   //
5637   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5638   //   a fixup or relocation is emitted to replace $symbol with a literal
5639   //   constant, which is a pc-relative offset from the encoding of the $symbol
5640   //   operand to the global variable.
5641   //
5642   // For global address space:
5643   //   s_getpc_b64 s[0:1]
5644   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5645   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5646   //
5647   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5648   //   fixups or relocations are emitted to replace $symbol@*@lo and
5649   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5650   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5651   //   operand to the global variable.
5652   //
5653   // What we want here is an offset from the value returned by s_getpc
5654   // (which is the address of the s_add_u32 instruction) to the global
5655   // variable, but since the encoding of $symbol starts 4 bytes after the start
5656   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5657   // small. This requires us to add 4 to the global variable offset in order to
5658   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5659   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5660   // instruction.
5661   SDValue PtrLo =
5662       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5663   SDValue PtrHi;
5664   if (GAFlags == SIInstrInfo::MO_NONE) {
5665     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5666   } else {
5667     PtrHi =
5668         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5669   }
5670   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5671 }
5672 
LowerGlobalAddress(AMDGPUMachineFunction * MFI,SDValue Op,SelectionDAG & DAG) const5673 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5674                                              SDValue Op,
5675                                              SelectionDAG &DAG) const {
5676   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5677   SDLoc DL(GSD);
5678   EVT PtrVT = Op.getValueType();
5679 
5680   const GlobalValue *GV = GSD->getGlobal();
5681   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5682        shouldUseLDSConstAddress(GV)) ||
5683       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5684       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5685     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5686         GV->hasExternalLinkage()) {
5687       Type *Ty = GV->getValueType();
5688       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5689       // zero-sized type in other languages to declare the dynamic shared
5690       // memory which size is not known at the compile time. They will be
5691       // allocated by the runtime and placed directly after the static
5692       // allocated ones. They all share the same offset.
5693       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5694         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5695         // Adjust alignment for that dynamic shared memory array.
5696         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5697         return SDValue(
5698             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5699       }
5700     }
5701     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5702   }
5703 
5704   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5705     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5706                                             SIInstrInfo::MO_ABS32_LO);
5707     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5708   }
5709 
5710   if (shouldEmitFixup(GV))
5711     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5712   else if (shouldEmitPCReloc(GV))
5713     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5714                                    SIInstrInfo::MO_REL32);
5715 
5716   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5717                                             SIInstrInfo::MO_GOTPCREL32);
5718 
5719   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5720   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5721   const DataLayout &DataLayout = DAG.getDataLayout();
5722   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5723   MachinePointerInfo PtrInfo
5724     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5725 
5726   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5727                      MachineMemOperand::MODereferenceable |
5728                          MachineMemOperand::MOInvariant);
5729 }
5730 
copyToM0(SelectionDAG & DAG,SDValue Chain,const SDLoc & DL,SDValue V) const5731 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5732                                    const SDLoc &DL, SDValue V) const {
5733   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5734   // the destination register.
5735   //
5736   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5737   // so we will end up with redundant moves to m0.
5738   //
5739   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5740 
5741   // A Null SDValue creates a glue result.
5742   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5743                                   V, Chain);
5744   return SDValue(M0, 0);
5745 }
5746 
lowerImplicitZextParam(SelectionDAG & DAG,SDValue Op,MVT VT,unsigned Offset) const5747 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5748                                                  SDValue Op,
5749                                                  MVT VT,
5750                                                  unsigned Offset) const {
5751   SDLoc SL(Op);
5752   SDValue Param = lowerKernargMemParameter(
5753       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5754   // The local size values will have the hi 16-bits as zero.
5755   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5756                      DAG.getValueType(VT));
5757 }
5758 
emitNonHSAIntrinsicError(SelectionDAG & DAG,const SDLoc & DL,EVT VT)5759 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5760                                         EVT VT) {
5761   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5762                                       "non-hsa intrinsic with hsa target",
5763                                       DL.getDebugLoc());
5764   DAG.getContext()->diagnose(BadIntrin);
5765   return DAG.getUNDEF(VT);
5766 }
5767 
emitRemovedIntrinsicError(SelectionDAG & DAG,const SDLoc & DL,EVT VT)5768 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5769                                          EVT VT) {
5770   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5771                                       "intrinsic not supported on subtarget",
5772                                       DL.getDebugLoc());
5773   DAG.getContext()->diagnose(BadIntrin);
5774   return DAG.getUNDEF(VT);
5775 }
5776 
getBuildDwordsVector(SelectionDAG & DAG,SDLoc DL,ArrayRef<SDValue> Elts)5777 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5778                                     ArrayRef<SDValue> Elts) {
5779   assert(!Elts.empty());
5780   MVT Type;
5781   unsigned NumElts;
5782 
5783   if (Elts.size() == 1) {
5784     Type = MVT::f32;
5785     NumElts = 1;
5786   } else if (Elts.size() == 2) {
5787     Type = MVT::v2f32;
5788     NumElts = 2;
5789   } else if (Elts.size() == 3) {
5790     Type = MVT::v3f32;
5791     NumElts = 3;
5792   } else if (Elts.size() <= 4) {
5793     Type = MVT::v4f32;
5794     NumElts = 4;
5795   } else if (Elts.size() <= 8) {
5796     Type = MVT::v8f32;
5797     NumElts = 8;
5798   } else {
5799     assert(Elts.size() <= 16);
5800     Type = MVT::v16f32;
5801     NumElts = 16;
5802   }
5803 
5804   SmallVector<SDValue, 16> VecElts(NumElts);
5805   for (unsigned i = 0; i < Elts.size(); ++i) {
5806     SDValue Elt = Elts[i];
5807     if (Elt.getValueType() != MVT::f32)
5808       Elt = DAG.getBitcast(MVT::f32, Elt);
5809     VecElts[i] = Elt;
5810   }
5811   for (unsigned i = Elts.size(); i < NumElts; ++i)
5812     VecElts[i] = DAG.getUNDEF(MVT::f32);
5813 
5814   if (NumElts == 1)
5815     return VecElts[0];
5816   return DAG.getBuildVector(Type, DL, VecElts);
5817 }
5818 
parseCachePolicy(SDValue CachePolicy,SelectionDAG & DAG,SDValue * GLC,SDValue * SLC,SDValue * DLC)5819 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5820                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5821   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5822 
5823   uint64_t Value = CachePolicyConst->getZExtValue();
5824   SDLoc DL(CachePolicy);
5825   if (GLC) {
5826     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5827     Value &= ~(uint64_t)0x1;
5828   }
5829   if (SLC) {
5830     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5831     Value &= ~(uint64_t)0x2;
5832   }
5833   if (DLC) {
5834     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5835     Value &= ~(uint64_t)0x4;
5836   }
5837 
5838   return Value == 0;
5839 }
5840 
padEltsToUndef(SelectionDAG & DAG,const SDLoc & DL,EVT CastVT,SDValue Src,int ExtraElts)5841 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5842                               SDValue Src, int ExtraElts) {
5843   EVT SrcVT = Src.getValueType();
5844 
5845   SmallVector<SDValue, 8> Elts;
5846 
5847   if (SrcVT.isVector())
5848     DAG.ExtractVectorElements(Src, Elts);
5849   else
5850     Elts.push_back(Src);
5851 
5852   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5853   while (ExtraElts--)
5854     Elts.push_back(Undef);
5855 
5856   return DAG.getBuildVector(CastVT, DL, Elts);
5857 }
5858 
5859 // Re-construct the required return value for a image load intrinsic.
5860 // This is more complicated due to the optional use TexFailCtrl which means the required
5861 // return type is an aggregate
constructRetValue(SelectionDAG & DAG,MachineSDNode * Result,ArrayRef<EVT> ResultTypes,bool IsTexFail,bool Unpacked,bool IsD16,int DMaskPop,int NumVDataDwords,const SDLoc & DL,LLVMContext & Context)5862 static SDValue constructRetValue(SelectionDAG &DAG,
5863                                  MachineSDNode *Result,
5864                                  ArrayRef<EVT> ResultTypes,
5865                                  bool IsTexFail, bool Unpacked, bool IsD16,
5866                                  int DMaskPop, int NumVDataDwords,
5867                                  const SDLoc &DL, LLVMContext &Context) {
5868   // Determine the required return type. This is the same regardless of IsTexFail flag
5869   EVT ReqRetVT = ResultTypes[0];
5870   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5871   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5872     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5873 
5874   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5875     DMaskPop : (DMaskPop + 1) / 2;
5876 
5877   MVT DataDwordVT = NumDataDwords == 1 ?
5878     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5879 
5880   MVT MaskPopVT = MaskPopDwords == 1 ?
5881     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5882 
5883   SDValue Data(Result, 0);
5884   SDValue TexFail;
5885 
5886   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5887     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5888     if (MaskPopVT.isVector()) {
5889       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5890                          SDValue(Result, 0), ZeroIdx);
5891     } else {
5892       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5893                          SDValue(Result, 0), ZeroIdx);
5894     }
5895   }
5896 
5897   if (DataDwordVT.isVector())
5898     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5899                           NumDataDwords - MaskPopDwords);
5900 
5901   if (IsD16)
5902     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5903 
5904   EVT LegalReqRetVT = ReqRetVT;
5905   if (!ReqRetVT.isVector()) {
5906     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5907   } else {
5908     // We need to widen the return vector to a legal type
5909     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5910         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5911       LegalReqRetVT =
5912           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5913                            ReqRetVT.getVectorNumElements() + 1);
5914     }
5915   }
5916   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5917 
5918   if (IsTexFail) {
5919     TexFail =
5920         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5921                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5922 
5923     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5924   }
5925 
5926   if (Result->getNumValues() == 1)
5927     return Data;
5928 
5929   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5930 }
5931 
parseTexFail(SDValue TexFailCtrl,SelectionDAG & DAG,SDValue * TFE,SDValue * LWE,bool & IsTexFail)5932 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5933                          SDValue *LWE, bool &IsTexFail) {
5934   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5935 
5936   uint64_t Value = TexFailCtrlConst->getZExtValue();
5937   if (Value) {
5938     IsTexFail = true;
5939   }
5940 
5941   SDLoc DL(TexFailCtrlConst);
5942   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5943   Value &= ~(uint64_t)0x1;
5944   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5945   Value &= ~(uint64_t)0x2;
5946 
5947   return Value == 0;
5948 }
5949 
packImageA16AddressToDwords(SelectionDAG & DAG,SDValue Op,MVT PackVectorVT,SmallVectorImpl<SDValue> & PackedAddrs,unsigned DimIdx,unsigned EndIdx,unsigned NumGradients)5950 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5951                                         MVT PackVectorVT,
5952                                         SmallVectorImpl<SDValue> &PackedAddrs,
5953                                         unsigned DimIdx, unsigned EndIdx,
5954                                         unsigned NumGradients) {
5955   SDLoc DL(Op);
5956   for (unsigned I = DimIdx; I < EndIdx; I++) {
5957     SDValue Addr = Op.getOperand(I);
5958 
5959     // Gradients are packed with undef for each coordinate.
5960     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5961     // 1D: undef,dx/dh; undef,dx/dv
5962     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5963     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5964     if (((I + 1) >= EndIdx) ||
5965         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5966                                          I == DimIdx + NumGradients - 1))) {
5967       if (Addr.getValueType() != MVT::i16)
5968         Addr = DAG.getBitcast(MVT::i16, Addr);
5969       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5970     } else {
5971       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5972       I++;
5973     }
5974     Addr = DAG.getBitcast(MVT::f32, Addr);
5975     PackedAddrs.push_back(Addr);
5976   }
5977 }
5978 
lowerImage(SDValue Op,const AMDGPU::ImageDimIntrinsicInfo * Intr,SelectionDAG & DAG,bool WithChain) const5979 SDValue SITargetLowering::lowerImage(SDValue Op,
5980                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5981                                      SelectionDAG &DAG, bool WithChain) const {
5982   SDLoc DL(Op);
5983   MachineFunction &MF = DAG.getMachineFunction();
5984   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5985   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5986       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5987   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5988   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5989       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5990   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5991       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5992   unsigned IntrOpcode = Intr->BaseOpcode;
5993   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
5994 
5995   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5996   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5997   bool IsD16 = false;
5998   bool IsG16 = false;
5999   bool IsA16 = false;
6000   SDValue VData;
6001   int NumVDataDwords;
6002   bool AdjustRetType = false;
6003 
6004   // Offset of intrinsic arguments
6005   const unsigned ArgOffset = WithChain ? 2 : 1;
6006 
6007   unsigned DMask;
6008   unsigned DMaskLanes = 0;
6009 
6010   if (BaseOpcode->Atomic) {
6011     VData = Op.getOperand(2);
6012 
6013     bool Is64Bit = VData.getValueType() == MVT::i64;
6014     if (BaseOpcode->AtomicX2) {
6015       SDValue VData2 = Op.getOperand(3);
6016       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6017                                  {VData, VData2});
6018       if (Is64Bit)
6019         VData = DAG.getBitcast(MVT::v4i32, VData);
6020 
6021       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6022       DMask = Is64Bit ? 0xf : 0x3;
6023       NumVDataDwords = Is64Bit ? 4 : 2;
6024     } else {
6025       DMask = Is64Bit ? 0x3 : 0x1;
6026       NumVDataDwords = Is64Bit ? 2 : 1;
6027     }
6028   } else {
6029     auto *DMaskConst =
6030         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6031     DMask = DMaskConst->getZExtValue();
6032     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6033 
6034     if (BaseOpcode->Store) {
6035       VData = Op.getOperand(2);
6036 
6037       MVT StoreVT = VData.getSimpleValueType();
6038       if (StoreVT.getScalarType() == MVT::f16) {
6039         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6040           return Op; // D16 is unsupported for this instruction
6041 
6042         IsD16 = true;
6043         VData = handleD16VData(VData, DAG, true);
6044       }
6045 
6046       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6047     } else {
6048       // Work out the num dwords based on the dmask popcount and underlying type
6049       // and whether packing is supported.
6050       MVT LoadVT = ResultTypes[0].getSimpleVT();
6051       if (LoadVT.getScalarType() == MVT::f16) {
6052         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6053           return Op; // D16 is unsupported for this instruction
6054 
6055         IsD16 = true;
6056       }
6057 
6058       // Confirm that the return type is large enough for the dmask specified
6059       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6060           (!LoadVT.isVector() && DMaskLanes > 1))
6061           return Op;
6062 
6063       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6064       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6065       // instructions.
6066       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6067           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6068         NumVDataDwords = (DMaskLanes + 1) / 2;
6069       else
6070         NumVDataDwords = DMaskLanes;
6071 
6072       AdjustRetType = true;
6073     }
6074   }
6075 
6076   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6077   SmallVector<SDValue, 4> VAddrs;
6078 
6079   // Optimize _L to _LZ when _L is zero
6080   if (LZMappingInfo) {
6081     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6082             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6083       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6084         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6085         VAddrEnd--;                      // remove 'lod'
6086       }
6087     }
6088   }
6089 
6090   // Optimize _mip away, when 'lod' is zero
6091   if (MIPMappingInfo) {
6092     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6093             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6094       if (ConstantLod->isNullValue()) {
6095         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6096         VAddrEnd--;                           // remove 'mip'
6097       }
6098     }
6099   }
6100 
6101   // Push back extra arguments.
6102   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6103     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6104 
6105   // Check for 16 bit addresses or derivatives and pack if true.
6106   MVT VAddrVT =
6107       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6108   MVT VAddrScalarVT = VAddrVT.getScalarType();
6109   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6110   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6111 
6112   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6113   VAddrScalarVT = VAddrVT.getScalarType();
6114   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6115   if (IsA16 || IsG16) {
6116     if (IsA16) {
6117       if (!ST->hasA16()) {
6118         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6119                              "support 16 bit addresses\n");
6120         return Op;
6121       }
6122       if (!IsG16) {
6123         LLVM_DEBUG(
6124             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6125                       "need 16 bit derivatives but got 32 bit derivatives\n");
6126         return Op;
6127       }
6128     } else if (!ST->hasG16()) {
6129       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6130                            "support 16 bit derivatives\n");
6131       return Op;
6132     }
6133 
6134     if (BaseOpcode->Gradients && !IsA16) {
6135       if (!ST->hasG16()) {
6136         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6137                              "support 16 bit derivatives\n");
6138         return Op;
6139       }
6140       // Activate g16
6141       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6142           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6143       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6144     }
6145 
6146     // Don't compress addresses for G16
6147     const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6148     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs,
6149                                 ArgOffset + Intr->GradientStart, PackEndIdx,
6150                                 Intr->NumGradients);
6151 
6152     if (!IsA16) {
6153       // Add uncompressed address
6154       for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6155         VAddrs.push_back(Op.getOperand(I));
6156     }
6157   } else {
6158     for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++)
6159       VAddrs.push_back(Op.getOperand(I));
6160   }
6161 
6162   // If the register allocator cannot place the address registers contiguously
6163   // without introducing moves, then using the non-sequential address encoding
6164   // is always preferable, since it saves VALU instructions and is usually a
6165   // wash in terms of code size or even better.
6166   //
6167   // However, we currently have no way of hinting to the register allocator that
6168   // MIMG addresses should be placed contiguously when it is possible to do so,
6169   // so force non-NSA for the common 2-address case as a heuristic.
6170   //
6171   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6172   // allocation when possible.
6173   bool UseNSA =
6174       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6175   SDValue VAddr;
6176   if (!UseNSA)
6177     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6178 
6179   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6180   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6181   SDValue Unorm;
6182   if (!BaseOpcode->Sampler) {
6183     Unorm = True;
6184   } else {
6185     auto UnormConst =
6186         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6187 
6188     Unorm = UnormConst->getZExtValue() ? True : False;
6189   }
6190 
6191   SDValue TFE;
6192   SDValue LWE;
6193   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6194   bool IsTexFail = false;
6195   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6196     return Op;
6197 
6198   if (IsTexFail) {
6199     if (!DMaskLanes) {
6200       // Expecting to get an error flag since TFC is on - and dmask is 0
6201       // Force dmask to be at least 1 otherwise the instruction will fail
6202       DMask = 0x1;
6203       DMaskLanes = 1;
6204       NumVDataDwords = 1;
6205     }
6206     NumVDataDwords += 1;
6207     AdjustRetType = true;
6208   }
6209 
6210   // Has something earlier tagged that the return type needs adjusting
6211   // This happens if the instruction is a load or has set TexFailCtrl flags
6212   if (AdjustRetType) {
6213     // NumVDataDwords reflects the true number of dwords required in the return type
6214     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6215       // This is a no-op load. This can be eliminated
6216       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6217       if (isa<MemSDNode>(Op))
6218         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6219       return Undef;
6220     }
6221 
6222     EVT NewVT = NumVDataDwords > 1 ?
6223                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6224                 : MVT::i32;
6225 
6226     ResultTypes[0] = NewVT;
6227     if (ResultTypes.size() == 3) {
6228       // Original result was aggregate type used for TexFailCtrl results
6229       // The actual instruction returns as a vector type which has now been
6230       // created. Remove the aggregate result.
6231       ResultTypes.erase(&ResultTypes[1]);
6232     }
6233   }
6234 
6235   SDValue GLC;
6236   SDValue SLC;
6237   SDValue DLC;
6238   if (BaseOpcode->Atomic) {
6239     GLC = True; // TODO no-return optimization
6240     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6241                           DAG, nullptr, &SLC, IsGFX10Plus ? &DLC : nullptr))
6242       return Op;
6243   } else {
6244     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6245                           DAG, &GLC, &SLC, IsGFX10Plus ? &DLC : nullptr))
6246       return Op;
6247   }
6248 
6249   SmallVector<SDValue, 26> Ops;
6250   if (BaseOpcode->Store || BaseOpcode->Atomic)
6251     Ops.push_back(VData); // vdata
6252   if (UseNSA) {
6253     for (const SDValue &Addr : VAddrs)
6254       Ops.push_back(Addr);
6255   } else {
6256     Ops.push_back(VAddr);
6257   }
6258   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6259   if (BaseOpcode->Sampler)
6260     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6261   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6262   if (IsGFX10Plus)
6263     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6264   Ops.push_back(Unorm);
6265   if (IsGFX10Plus)
6266     Ops.push_back(DLC);
6267   Ops.push_back(GLC);
6268   Ops.push_back(SLC);
6269   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6270                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6271   if (IsGFX10Plus)
6272     Ops.push_back(IsA16 ? True : False);
6273   Ops.push_back(TFE);
6274   Ops.push_back(LWE);
6275   if (!IsGFX10Plus)
6276     Ops.push_back(DimInfo->DA ? True : False);
6277   if (BaseOpcode->HasD16)
6278     Ops.push_back(IsD16 ? True : False);
6279   if (isa<MemSDNode>(Op))
6280     Ops.push_back(Op.getOperand(0)); // chain
6281 
6282   int NumVAddrDwords =
6283       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6284   int Opcode = -1;
6285 
6286   if (IsGFX10Plus) {
6287     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6288                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6289                                           : AMDGPU::MIMGEncGfx10Default,
6290                                    NumVDataDwords, NumVAddrDwords);
6291   } else {
6292     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6293       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6294                                      NumVDataDwords, NumVAddrDwords);
6295     if (Opcode == -1)
6296       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6297                                      NumVDataDwords, NumVAddrDwords);
6298   }
6299   assert(Opcode != -1);
6300 
6301   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6302   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6303     MachineMemOperand *MemRef = MemOp->getMemOperand();
6304     DAG.setNodeMemRefs(NewNode, {MemRef});
6305   }
6306 
6307   if (BaseOpcode->AtomicX2) {
6308     SmallVector<SDValue, 1> Elt;
6309     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6310     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6311   } else if (!BaseOpcode->Store) {
6312     return constructRetValue(DAG, NewNode,
6313                              OrigResultTypes, IsTexFail,
6314                              Subtarget->hasUnpackedD16VMem(), IsD16,
6315                              DMaskLanes, NumVDataDwords, DL,
6316                              *DAG.getContext());
6317   }
6318 
6319   return SDValue(NewNode, 0);
6320 }
6321 
lowerSBuffer(EVT VT,SDLoc DL,SDValue Rsrc,SDValue Offset,SDValue CachePolicy,SelectionDAG & DAG) const6322 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6323                                        SDValue Offset, SDValue CachePolicy,
6324                                        SelectionDAG &DAG) const {
6325   MachineFunction &MF = DAG.getMachineFunction();
6326 
6327   const DataLayout &DataLayout = DAG.getDataLayout();
6328   Align Alignment =
6329       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6330 
6331   MachineMemOperand *MMO = MF.getMachineMemOperand(
6332       MachinePointerInfo(),
6333       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6334           MachineMemOperand::MOInvariant,
6335       VT.getStoreSize(), Alignment);
6336 
6337   if (!Offset->isDivergent()) {
6338     SDValue Ops[] = {
6339         Rsrc,
6340         Offset, // Offset
6341         CachePolicy
6342     };
6343 
6344     // Widen vec3 load to vec4.
6345     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6346       EVT WidenedVT =
6347           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6348       auto WidenedOp = DAG.getMemIntrinsicNode(
6349           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6350           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6351       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6352                                    DAG.getVectorIdxConstant(0, DL));
6353       return Subvector;
6354     }
6355 
6356     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6357                                    DAG.getVTList(VT), Ops, VT, MMO);
6358   }
6359 
6360   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6361   // assume that the buffer is unswizzled.
6362   SmallVector<SDValue, 4> Loads;
6363   unsigned NumLoads = 1;
6364   MVT LoadVT = VT.getSimpleVT();
6365   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6366   assert((LoadVT.getScalarType() == MVT::i32 ||
6367           LoadVT.getScalarType() == MVT::f32));
6368 
6369   if (NumElts == 8 || NumElts == 16) {
6370     NumLoads = NumElts / 4;
6371     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6372   }
6373 
6374   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6375   SDValue Ops[] = {
6376       DAG.getEntryNode(),                               // Chain
6377       Rsrc,                                             // rsrc
6378       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6379       {},                                               // voffset
6380       {},                                               // soffset
6381       {},                                               // offset
6382       CachePolicy,                                      // cachepolicy
6383       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6384   };
6385 
6386   // Use the alignment to ensure that the required offsets will fit into the
6387   // immediate offsets.
6388   setBufferOffsets(Offset, DAG, &Ops[3],
6389                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6390 
6391   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6392   for (unsigned i = 0; i < NumLoads; ++i) {
6393     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6394     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6395                                         LoadVT, MMO, DAG));
6396   }
6397 
6398   if (NumElts == 8 || NumElts == 16)
6399     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6400 
6401   return Loads[0];
6402 }
6403 
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG) const6404 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6405                                                   SelectionDAG &DAG) const {
6406   MachineFunction &MF = DAG.getMachineFunction();
6407   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6408 
6409   EVT VT = Op.getValueType();
6410   SDLoc DL(Op);
6411   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6412 
6413   // TODO: Should this propagate fast-math-flags?
6414 
6415   switch (IntrinsicID) {
6416   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6417     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6418       return emitNonHSAIntrinsicError(DAG, DL, VT);
6419     return getPreloadedValue(DAG, *MFI, VT,
6420                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6421   }
6422   case Intrinsic::amdgcn_dispatch_ptr:
6423   case Intrinsic::amdgcn_queue_ptr: {
6424     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6425       DiagnosticInfoUnsupported BadIntrin(
6426           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6427           DL.getDebugLoc());
6428       DAG.getContext()->diagnose(BadIntrin);
6429       return DAG.getUNDEF(VT);
6430     }
6431 
6432     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6433       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6434     return getPreloadedValue(DAG, *MFI, VT, RegID);
6435   }
6436   case Intrinsic::amdgcn_implicitarg_ptr: {
6437     if (MFI->isEntryFunction())
6438       return getImplicitArgPtr(DAG, DL);
6439     return getPreloadedValue(DAG, *MFI, VT,
6440                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6441   }
6442   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6443     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6444       // This only makes sense to call in a kernel, so just lower to null.
6445       return DAG.getConstant(0, DL, VT);
6446     }
6447 
6448     return getPreloadedValue(DAG, *MFI, VT,
6449                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6450   }
6451   case Intrinsic::amdgcn_dispatch_id: {
6452     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6453   }
6454   case Intrinsic::amdgcn_rcp:
6455     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6456   case Intrinsic::amdgcn_rsq:
6457     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6458   case Intrinsic::amdgcn_rsq_legacy:
6459     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6460       return emitRemovedIntrinsicError(DAG, DL, VT);
6461     return SDValue();
6462   case Intrinsic::amdgcn_rcp_legacy:
6463     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6464       return emitRemovedIntrinsicError(DAG, DL, VT);
6465     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6466   case Intrinsic::amdgcn_rsq_clamp: {
6467     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6468       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6469 
6470     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6471     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6472     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6473 
6474     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6475     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6476                               DAG.getConstantFP(Max, DL, VT));
6477     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6478                        DAG.getConstantFP(Min, DL, VT));
6479   }
6480   case Intrinsic::r600_read_ngroups_x:
6481     if (Subtarget->isAmdHsaOS())
6482       return emitNonHSAIntrinsicError(DAG, DL, VT);
6483 
6484     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6485                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6486                                     false);
6487   case Intrinsic::r600_read_ngroups_y:
6488     if (Subtarget->isAmdHsaOS())
6489       return emitNonHSAIntrinsicError(DAG, DL, VT);
6490 
6491     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6492                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6493                                     false);
6494   case Intrinsic::r600_read_ngroups_z:
6495     if (Subtarget->isAmdHsaOS())
6496       return emitNonHSAIntrinsicError(DAG, DL, VT);
6497 
6498     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6499                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6500                                     false);
6501   case Intrinsic::r600_read_global_size_x:
6502     if (Subtarget->isAmdHsaOS())
6503       return emitNonHSAIntrinsicError(DAG, DL, VT);
6504 
6505     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6506                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6507                                     Align(4), false);
6508   case Intrinsic::r600_read_global_size_y:
6509     if (Subtarget->isAmdHsaOS())
6510       return emitNonHSAIntrinsicError(DAG, DL, VT);
6511 
6512     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6513                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6514                                     Align(4), false);
6515   case Intrinsic::r600_read_global_size_z:
6516     if (Subtarget->isAmdHsaOS())
6517       return emitNonHSAIntrinsicError(DAG, DL, VT);
6518 
6519     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6520                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6521                                     Align(4), false);
6522   case Intrinsic::r600_read_local_size_x:
6523     if (Subtarget->isAmdHsaOS())
6524       return emitNonHSAIntrinsicError(DAG, DL, VT);
6525 
6526     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6527                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6528   case Intrinsic::r600_read_local_size_y:
6529     if (Subtarget->isAmdHsaOS())
6530       return emitNonHSAIntrinsicError(DAG, DL, VT);
6531 
6532     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6533                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6534   case Intrinsic::r600_read_local_size_z:
6535     if (Subtarget->isAmdHsaOS())
6536       return emitNonHSAIntrinsicError(DAG, DL, VT);
6537 
6538     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6539                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6540   case Intrinsic::amdgcn_workgroup_id_x:
6541     return getPreloadedValue(DAG, *MFI, VT,
6542                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6543   case Intrinsic::amdgcn_workgroup_id_y:
6544     return getPreloadedValue(DAG, *MFI, VT,
6545                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6546   case Intrinsic::amdgcn_workgroup_id_z:
6547     return getPreloadedValue(DAG, *MFI, VT,
6548                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6549   case Intrinsic::amdgcn_workitem_id_x:
6550     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6551                           SDLoc(DAG.getEntryNode()),
6552                           MFI->getArgInfo().WorkItemIDX);
6553   case Intrinsic::amdgcn_workitem_id_y:
6554     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6555                           SDLoc(DAG.getEntryNode()),
6556                           MFI->getArgInfo().WorkItemIDY);
6557   case Intrinsic::amdgcn_workitem_id_z:
6558     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6559                           SDLoc(DAG.getEntryNode()),
6560                           MFI->getArgInfo().WorkItemIDZ);
6561   case Intrinsic::amdgcn_wavefrontsize:
6562     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6563                            SDLoc(Op), MVT::i32);
6564   case Intrinsic::amdgcn_s_buffer_load: {
6565     bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6566     SDValue GLC;
6567     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6568     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6569                           IsGFX10Plus ? &DLC : nullptr))
6570       return Op;
6571     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6572                         DAG);
6573   }
6574   case Intrinsic::amdgcn_fdiv_fast:
6575     return lowerFDIV_FAST(Op, DAG);
6576   case Intrinsic::amdgcn_sin:
6577     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6578 
6579   case Intrinsic::amdgcn_cos:
6580     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6581 
6582   case Intrinsic::amdgcn_mul_u24:
6583     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6584   case Intrinsic::amdgcn_mul_i24:
6585     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6586 
6587   case Intrinsic::amdgcn_log_clamp: {
6588     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6589       return SDValue();
6590 
6591     DiagnosticInfoUnsupported BadIntrin(
6592       MF.getFunction(), "intrinsic not supported on subtarget",
6593       DL.getDebugLoc());
6594       DAG.getContext()->diagnose(BadIntrin);
6595       return DAG.getUNDEF(VT);
6596   }
6597   case Intrinsic::amdgcn_ldexp:
6598     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6599                        Op.getOperand(1), Op.getOperand(2));
6600 
6601   case Intrinsic::amdgcn_fract:
6602     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6603 
6604   case Intrinsic::amdgcn_class:
6605     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6606                        Op.getOperand(1), Op.getOperand(2));
6607   case Intrinsic::amdgcn_div_fmas:
6608     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6609                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6610                        Op.getOperand(4));
6611 
6612   case Intrinsic::amdgcn_div_fixup:
6613     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6614                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6615 
6616   case Intrinsic::amdgcn_div_scale: {
6617     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6618 
6619     // Translate to the operands expected by the machine instruction. The
6620     // first parameter must be the same as the first instruction.
6621     SDValue Numerator = Op.getOperand(1);
6622     SDValue Denominator = Op.getOperand(2);
6623 
6624     // Note this order is opposite of the machine instruction's operations,
6625     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6626     // intrinsic has the numerator as the first operand to match a normal
6627     // division operation.
6628 
6629     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6630 
6631     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6632                        Denominator, Numerator);
6633   }
6634   case Intrinsic::amdgcn_icmp: {
6635     // There is a Pat that handles this variant, so return it as-is.
6636     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6637         Op.getConstantOperandVal(2) == 0 &&
6638         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6639       return Op;
6640     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6641   }
6642   case Intrinsic::amdgcn_fcmp: {
6643     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6644   }
6645   case Intrinsic::amdgcn_ballot:
6646     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6647   case Intrinsic::amdgcn_fmed3:
6648     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6649                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6650   case Intrinsic::amdgcn_fdot2:
6651     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6652                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6653                        Op.getOperand(4));
6654   case Intrinsic::amdgcn_fmul_legacy:
6655     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6656                        Op.getOperand(1), Op.getOperand(2));
6657   case Intrinsic::amdgcn_sffbh:
6658     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6659   case Intrinsic::amdgcn_sbfe:
6660     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6661                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6662   case Intrinsic::amdgcn_ubfe:
6663     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6664                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6665   case Intrinsic::amdgcn_cvt_pkrtz:
6666   case Intrinsic::amdgcn_cvt_pknorm_i16:
6667   case Intrinsic::amdgcn_cvt_pknorm_u16:
6668   case Intrinsic::amdgcn_cvt_pk_i16:
6669   case Intrinsic::amdgcn_cvt_pk_u16: {
6670     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6671     EVT VT = Op.getValueType();
6672     unsigned Opcode;
6673 
6674     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6675       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6676     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6677       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6678     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6679       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6680     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6681       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6682     else
6683       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6684 
6685     if (isTypeLegal(VT))
6686       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6687 
6688     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6689                                Op.getOperand(1), Op.getOperand(2));
6690     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6691   }
6692   case Intrinsic::amdgcn_fmad_ftz:
6693     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6694                        Op.getOperand(2), Op.getOperand(3));
6695 
6696   case Intrinsic::amdgcn_if_break:
6697     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6698                                       Op->getOperand(1), Op->getOperand(2)), 0);
6699 
6700   case Intrinsic::amdgcn_groupstaticsize: {
6701     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6702     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6703       return Op;
6704 
6705     const Module *M = MF.getFunction().getParent();
6706     const GlobalValue *GV =
6707         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6708     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6709                                             SIInstrInfo::MO_ABS32_LO);
6710     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6711   }
6712   case Intrinsic::amdgcn_is_shared:
6713   case Intrinsic::amdgcn_is_private: {
6714     SDLoc SL(Op);
6715     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6716       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6717     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6718     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6719                                  Op.getOperand(1));
6720 
6721     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6722                                 DAG.getConstant(1, SL, MVT::i32));
6723     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6724   }
6725   case Intrinsic::amdgcn_alignbit:
6726     return DAG.getNode(ISD::FSHR, DL, VT,
6727                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6728   case Intrinsic::amdgcn_reloc_constant: {
6729     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6730     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6731     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6732     auto RelocSymbol = cast<GlobalVariable>(
6733         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6734     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6735                                             SIInstrInfo::MO_ABS32_LO);
6736     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6737   }
6738   default:
6739     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6740             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6741       return lowerImage(Op, ImageDimIntr, DAG, false);
6742 
6743     return Op;
6744   }
6745 }
6746 
6747 // This function computes an appropriate offset to pass to
6748 // MachineMemOperand::setOffset() based on the offset inputs to
6749 // an intrinsic.  If any of the offsets are non-contstant or
6750 // if VIndex is non-zero then this function returns 0.  Otherwise,
6751 // it returns the sum of VOffset, SOffset, and Offset.
getBufferOffsetForMMO(SDValue VOffset,SDValue SOffset,SDValue Offset,SDValue VIndex=SDValue ())6752 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6753                                       SDValue SOffset,
6754                                       SDValue Offset,
6755                                       SDValue VIndex = SDValue()) {
6756 
6757   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6758       !isa<ConstantSDNode>(Offset))
6759     return 0;
6760 
6761   if (VIndex) {
6762     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6763       return 0;
6764   }
6765 
6766   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6767          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6768          cast<ConstantSDNode>(Offset)->getSExtValue();
6769 }
6770 
lowerRawBufferAtomicIntrin(SDValue Op,SelectionDAG & DAG,unsigned NewOpcode) const6771 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6772                                                      SelectionDAG &DAG,
6773                                                      unsigned NewOpcode) const {
6774   SDLoc DL(Op);
6775 
6776   SDValue VData = Op.getOperand(2);
6777   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6778   SDValue Ops[] = {
6779     Op.getOperand(0), // Chain
6780     VData,            // vdata
6781     Op.getOperand(3), // rsrc
6782     DAG.getConstant(0, DL, MVT::i32), // vindex
6783     Offsets.first,    // voffset
6784     Op.getOperand(5), // soffset
6785     Offsets.second,   // offset
6786     Op.getOperand(6), // cachepolicy
6787     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6788   };
6789 
6790   auto *M = cast<MemSDNode>(Op);
6791   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6792 
6793   EVT MemVT = VData.getValueType();
6794   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6795                                  M->getMemOperand());
6796 }
6797 
6798 SDValue
lowerStructBufferAtomicIntrin(SDValue Op,SelectionDAG & DAG,unsigned NewOpcode) const6799 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6800                                                 unsigned NewOpcode) const {
6801   SDLoc DL(Op);
6802 
6803   SDValue VData = Op.getOperand(2);
6804   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6805   SDValue Ops[] = {
6806     Op.getOperand(0), // Chain
6807     VData,            // vdata
6808     Op.getOperand(3), // rsrc
6809     Op.getOperand(4), // vindex
6810     Offsets.first,    // voffset
6811     Op.getOperand(6), // soffset
6812     Offsets.second,   // offset
6813     Op.getOperand(7), // cachepolicy
6814     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6815   };
6816 
6817   auto *M = cast<MemSDNode>(Op);
6818   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6819                                                       Ops[3]));
6820 
6821   EVT MemVT = VData.getValueType();
6822   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6823                                  M->getMemOperand());
6824 }
6825 
LowerINTRINSIC_W_CHAIN(SDValue Op,SelectionDAG & DAG) const6826 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6827                                                  SelectionDAG &DAG) const {
6828   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6829   SDLoc DL(Op);
6830 
6831   switch (IntrID) {
6832   case Intrinsic::amdgcn_ds_ordered_add:
6833   case Intrinsic::amdgcn_ds_ordered_swap: {
6834     MemSDNode *M = cast<MemSDNode>(Op);
6835     SDValue Chain = M->getOperand(0);
6836     SDValue M0 = M->getOperand(2);
6837     SDValue Value = M->getOperand(3);
6838     unsigned IndexOperand = M->getConstantOperandVal(7);
6839     unsigned WaveRelease = M->getConstantOperandVal(8);
6840     unsigned WaveDone = M->getConstantOperandVal(9);
6841 
6842     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6843     IndexOperand &= ~0x3f;
6844     unsigned CountDw = 0;
6845 
6846     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6847       CountDw = (IndexOperand >> 24) & 0xf;
6848       IndexOperand &= ~(0xf << 24);
6849 
6850       if (CountDw < 1 || CountDw > 4) {
6851         report_fatal_error(
6852             "ds_ordered_count: dword count must be between 1 and 4");
6853       }
6854     }
6855 
6856     if (IndexOperand)
6857       report_fatal_error("ds_ordered_count: bad index operand");
6858 
6859     if (WaveDone && !WaveRelease)
6860       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6861 
6862     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6863     unsigned ShaderType =
6864         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6865     unsigned Offset0 = OrderedCountIndex << 2;
6866     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6867                        (Instruction << 4);
6868 
6869     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6870       Offset1 |= (CountDw - 1) << 6;
6871 
6872     unsigned Offset = Offset0 | (Offset1 << 8);
6873 
6874     SDValue Ops[] = {
6875       Chain,
6876       Value,
6877       DAG.getTargetConstant(Offset, DL, MVT::i16),
6878       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6879     };
6880     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6881                                    M->getVTList(), Ops, M->getMemoryVT(),
6882                                    M->getMemOperand());
6883   }
6884   case Intrinsic::amdgcn_ds_fadd: {
6885     MemSDNode *M = cast<MemSDNode>(Op);
6886     unsigned Opc;
6887     switch (IntrID) {
6888     case Intrinsic::amdgcn_ds_fadd:
6889       Opc = ISD::ATOMIC_LOAD_FADD;
6890       break;
6891     }
6892 
6893     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6894                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6895                          M->getMemOperand());
6896   }
6897   case Intrinsic::amdgcn_atomic_inc:
6898   case Intrinsic::amdgcn_atomic_dec:
6899   case Intrinsic::amdgcn_ds_fmin:
6900   case Intrinsic::amdgcn_ds_fmax: {
6901     MemSDNode *M = cast<MemSDNode>(Op);
6902     unsigned Opc;
6903     switch (IntrID) {
6904     case Intrinsic::amdgcn_atomic_inc:
6905       Opc = AMDGPUISD::ATOMIC_INC;
6906       break;
6907     case Intrinsic::amdgcn_atomic_dec:
6908       Opc = AMDGPUISD::ATOMIC_DEC;
6909       break;
6910     case Intrinsic::amdgcn_ds_fmin:
6911       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6912       break;
6913     case Intrinsic::amdgcn_ds_fmax:
6914       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6915       break;
6916     default:
6917       llvm_unreachable("Unknown intrinsic!");
6918     }
6919     SDValue Ops[] = {
6920       M->getOperand(0), // Chain
6921       M->getOperand(2), // Ptr
6922       M->getOperand(3)  // Value
6923     };
6924 
6925     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6926                                    M->getMemoryVT(), M->getMemOperand());
6927   }
6928   case Intrinsic::amdgcn_buffer_load:
6929   case Intrinsic::amdgcn_buffer_load_format: {
6930     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6931     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6932     unsigned IdxEn = 1;
6933     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6934       IdxEn = Idx->getZExtValue() != 0;
6935     SDValue Ops[] = {
6936       Op.getOperand(0), // Chain
6937       Op.getOperand(2), // rsrc
6938       Op.getOperand(3), // vindex
6939       SDValue(),        // voffset -- will be set by setBufferOffsets
6940       SDValue(),        // soffset -- will be set by setBufferOffsets
6941       SDValue(),        // offset -- will be set by setBufferOffsets
6942       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6943       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6944     };
6945 
6946     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6947     // We don't know the offset if vindex is non-zero, so clear it.
6948     if (IdxEn)
6949       Offset = 0;
6950 
6951     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6952         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6953 
6954     EVT VT = Op.getValueType();
6955     EVT IntVT = VT.changeTypeToInteger();
6956     auto *M = cast<MemSDNode>(Op);
6957     M->getMemOperand()->setOffset(Offset);
6958     EVT LoadVT = Op.getValueType();
6959 
6960     if (LoadVT.getScalarType() == MVT::f16)
6961       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6962                                  M, DAG, Ops);
6963 
6964     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6965     if (LoadVT.getScalarType() == MVT::i8 ||
6966         LoadVT.getScalarType() == MVT::i16)
6967       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6968 
6969     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6970                                M->getMemOperand(), DAG);
6971   }
6972   case Intrinsic::amdgcn_raw_buffer_load:
6973   case Intrinsic::amdgcn_raw_buffer_load_format: {
6974     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6975 
6976     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6977     SDValue Ops[] = {
6978       Op.getOperand(0), // Chain
6979       Op.getOperand(2), // rsrc
6980       DAG.getConstant(0, DL, MVT::i32), // vindex
6981       Offsets.first,    // voffset
6982       Op.getOperand(4), // soffset
6983       Offsets.second,   // offset
6984       Op.getOperand(5), // cachepolicy, swizzled buffer
6985       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6986     };
6987 
6988     auto *M = cast<MemSDNode>(Op);
6989     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6990     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6991   }
6992   case Intrinsic::amdgcn_struct_buffer_load:
6993   case Intrinsic::amdgcn_struct_buffer_load_format: {
6994     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6995 
6996     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6997     SDValue Ops[] = {
6998       Op.getOperand(0), // Chain
6999       Op.getOperand(2), // rsrc
7000       Op.getOperand(3), // vindex
7001       Offsets.first,    // voffset
7002       Op.getOperand(5), // soffset
7003       Offsets.second,   // offset
7004       Op.getOperand(6), // cachepolicy, swizzled buffer
7005       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7006     };
7007 
7008     auto *M = cast<MemSDNode>(Op);
7009     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
7010                                                         Ops[2]));
7011     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7012   }
7013   case Intrinsic::amdgcn_tbuffer_load: {
7014     MemSDNode *M = cast<MemSDNode>(Op);
7015     EVT LoadVT = Op.getValueType();
7016 
7017     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7018     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7019     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7020     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7021     unsigned IdxEn = 1;
7022     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
7023       IdxEn = Idx->getZExtValue() != 0;
7024     SDValue Ops[] = {
7025       Op.getOperand(0),  // Chain
7026       Op.getOperand(2),  // rsrc
7027       Op.getOperand(3),  // vindex
7028       Op.getOperand(4),  // voffset
7029       Op.getOperand(5),  // soffset
7030       Op.getOperand(6),  // offset
7031       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7032       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7033       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7034     };
7035 
7036     if (LoadVT.getScalarType() == MVT::f16)
7037       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7038                                  M, DAG, Ops);
7039     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7040                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7041                                DAG);
7042   }
7043   case Intrinsic::amdgcn_raw_tbuffer_load: {
7044     MemSDNode *M = cast<MemSDNode>(Op);
7045     EVT LoadVT = Op.getValueType();
7046     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7047 
7048     SDValue Ops[] = {
7049       Op.getOperand(0),  // Chain
7050       Op.getOperand(2),  // rsrc
7051       DAG.getConstant(0, DL, MVT::i32), // vindex
7052       Offsets.first,     // voffset
7053       Op.getOperand(4),  // soffset
7054       Offsets.second,    // offset
7055       Op.getOperand(5),  // format
7056       Op.getOperand(6),  // cachepolicy, swizzled buffer
7057       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7058     };
7059 
7060     if (LoadVT.getScalarType() == MVT::f16)
7061       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7062                                  M, DAG, Ops);
7063     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7064                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7065                                DAG);
7066   }
7067   case Intrinsic::amdgcn_struct_tbuffer_load: {
7068     MemSDNode *M = cast<MemSDNode>(Op);
7069     EVT LoadVT = Op.getValueType();
7070     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7071 
7072     SDValue Ops[] = {
7073       Op.getOperand(0),  // Chain
7074       Op.getOperand(2),  // rsrc
7075       Op.getOperand(3),  // vindex
7076       Offsets.first,     // voffset
7077       Op.getOperand(5),  // soffset
7078       Offsets.second,    // offset
7079       Op.getOperand(6),  // format
7080       Op.getOperand(7),  // cachepolicy, swizzled buffer
7081       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7082     };
7083 
7084     if (LoadVT.getScalarType() == MVT::f16)
7085       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7086                                  M, DAG, Ops);
7087     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7088                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7089                                DAG);
7090   }
7091   case Intrinsic::amdgcn_buffer_atomic_swap:
7092   case Intrinsic::amdgcn_buffer_atomic_add:
7093   case Intrinsic::amdgcn_buffer_atomic_sub:
7094   case Intrinsic::amdgcn_buffer_atomic_csub:
7095   case Intrinsic::amdgcn_buffer_atomic_smin:
7096   case Intrinsic::amdgcn_buffer_atomic_umin:
7097   case Intrinsic::amdgcn_buffer_atomic_smax:
7098   case Intrinsic::amdgcn_buffer_atomic_umax:
7099   case Intrinsic::amdgcn_buffer_atomic_and:
7100   case Intrinsic::amdgcn_buffer_atomic_or:
7101   case Intrinsic::amdgcn_buffer_atomic_xor:
7102   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7103     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7104     unsigned IdxEn = 1;
7105     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7106       IdxEn = Idx->getZExtValue() != 0;
7107     SDValue Ops[] = {
7108       Op.getOperand(0), // Chain
7109       Op.getOperand(2), // vdata
7110       Op.getOperand(3), // rsrc
7111       Op.getOperand(4), // vindex
7112       SDValue(),        // voffset -- will be set by setBufferOffsets
7113       SDValue(),        // soffset -- will be set by setBufferOffsets
7114       SDValue(),        // offset -- will be set by setBufferOffsets
7115       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7116       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7117     };
7118     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7119     // We don't know the offset if vindex is non-zero, so clear it.
7120     if (IdxEn)
7121       Offset = 0;
7122     EVT VT = Op.getValueType();
7123 
7124     auto *M = cast<MemSDNode>(Op);
7125     M->getMemOperand()->setOffset(Offset);
7126     unsigned Opcode = 0;
7127 
7128     switch (IntrID) {
7129     case Intrinsic::amdgcn_buffer_atomic_swap:
7130       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7131       break;
7132     case Intrinsic::amdgcn_buffer_atomic_add:
7133       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7134       break;
7135     case Intrinsic::amdgcn_buffer_atomic_sub:
7136       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7137       break;
7138     case Intrinsic::amdgcn_buffer_atomic_csub:
7139       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7140       break;
7141     case Intrinsic::amdgcn_buffer_atomic_smin:
7142       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7143       break;
7144     case Intrinsic::amdgcn_buffer_atomic_umin:
7145       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7146       break;
7147     case Intrinsic::amdgcn_buffer_atomic_smax:
7148       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7149       break;
7150     case Intrinsic::amdgcn_buffer_atomic_umax:
7151       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7152       break;
7153     case Intrinsic::amdgcn_buffer_atomic_and:
7154       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7155       break;
7156     case Intrinsic::amdgcn_buffer_atomic_or:
7157       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7158       break;
7159     case Intrinsic::amdgcn_buffer_atomic_xor:
7160       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7161       break;
7162     case Intrinsic::amdgcn_buffer_atomic_fadd:
7163       if (!Op.getValue(0).use_empty()) {
7164         DiagnosticInfoUnsupported
7165           NoFpRet(DAG.getMachineFunction().getFunction(),
7166                   "return versions of fp atomics not supported",
7167                   DL.getDebugLoc(), DS_Error);
7168         DAG.getContext()->diagnose(NoFpRet);
7169         return SDValue();
7170       }
7171       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7172       break;
7173     default:
7174       llvm_unreachable("unhandled atomic opcode");
7175     }
7176 
7177     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7178                                    M->getMemOperand());
7179   }
7180   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7181     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7182   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7183     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7184   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7185     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7186   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7187     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7188   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7189     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7190   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7191     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7192   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7193     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7194   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7195     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7196   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7197     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7198   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7199     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7200   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7201     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7202   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7203     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7204   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7205     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7206   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7207     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7208   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7209     return lowerStructBufferAtomicIntrin(Op, DAG,
7210                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7211   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7212     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7213   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7214     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7215   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7216     return lowerStructBufferAtomicIntrin(Op, DAG,
7217                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7218   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7219     return lowerStructBufferAtomicIntrin(Op, DAG,
7220                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7221   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7222     return lowerStructBufferAtomicIntrin(Op, DAG,
7223                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7224   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7225     return lowerStructBufferAtomicIntrin(Op, DAG,
7226                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7227   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7228     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7229   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7230     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7231   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7232     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7233   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7234     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7235   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7236     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7237 
7238   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7239     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7240     unsigned IdxEn = 1;
7241     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7242       IdxEn = Idx->getZExtValue() != 0;
7243     SDValue Ops[] = {
7244       Op.getOperand(0), // Chain
7245       Op.getOperand(2), // src
7246       Op.getOperand(3), // cmp
7247       Op.getOperand(4), // rsrc
7248       Op.getOperand(5), // vindex
7249       SDValue(),        // voffset -- will be set by setBufferOffsets
7250       SDValue(),        // soffset -- will be set by setBufferOffsets
7251       SDValue(),        // offset -- will be set by setBufferOffsets
7252       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7253       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7254     };
7255     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7256     // We don't know the offset if vindex is non-zero, so clear it.
7257     if (IdxEn)
7258       Offset = 0;
7259     EVT VT = Op.getValueType();
7260     auto *M = cast<MemSDNode>(Op);
7261     M->getMemOperand()->setOffset(Offset);
7262 
7263     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7264                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7265   }
7266   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7267     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7268     SDValue Ops[] = {
7269       Op.getOperand(0), // Chain
7270       Op.getOperand(2), // src
7271       Op.getOperand(3), // cmp
7272       Op.getOperand(4), // rsrc
7273       DAG.getConstant(0, DL, MVT::i32), // vindex
7274       Offsets.first,    // voffset
7275       Op.getOperand(6), // soffset
7276       Offsets.second,   // offset
7277       Op.getOperand(7), // cachepolicy
7278       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7279     };
7280     EVT VT = Op.getValueType();
7281     auto *M = cast<MemSDNode>(Op);
7282     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7283 
7284     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7285                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7286   }
7287   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7288     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7289     SDValue Ops[] = {
7290       Op.getOperand(0), // Chain
7291       Op.getOperand(2), // src
7292       Op.getOperand(3), // cmp
7293       Op.getOperand(4), // rsrc
7294       Op.getOperand(5), // vindex
7295       Offsets.first,    // voffset
7296       Op.getOperand(7), // soffset
7297       Offsets.second,   // offset
7298       Op.getOperand(8), // cachepolicy
7299       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7300     };
7301     EVT VT = Op.getValueType();
7302     auto *M = cast<MemSDNode>(Op);
7303     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7304                                                         Ops[4]));
7305 
7306     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7307                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7308   }
7309   case Intrinsic::amdgcn_global_atomic_fadd: {
7310     if (!Op.getValue(0).use_empty()) {
7311       DiagnosticInfoUnsupported
7312         NoFpRet(DAG.getMachineFunction().getFunction(),
7313                 "return versions of fp atomics not supported",
7314                 DL.getDebugLoc(), DS_Error);
7315       DAG.getContext()->diagnose(NoFpRet);
7316       return SDValue();
7317     }
7318     MemSDNode *M = cast<MemSDNode>(Op);
7319     SDValue Ops[] = {
7320       M->getOperand(0), // Chain
7321       M->getOperand(2), // Ptr
7322       M->getOperand(3)  // Value
7323     };
7324 
7325     EVT VT = Op.getOperand(3).getValueType();
7326     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7327                          DAG.getVTList(VT, MVT::Other), Ops,
7328                          M->getMemOperand());
7329   }
7330   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7331     SDLoc DL(Op);
7332     MemSDNode *M = cast<MemSDNode>(Op);
7333     SDValue NodePtr = M->getOperand(2);
7334     SDValue RayExtent = M->getOperand(3);
7335     SDValue RayOrigin = M->getOperand(4);
7336     SDValue RayDir = M->getOperand(5);
7337     SDValue RayInvDir = M->getOperand(6);
7338     SDValue TDescr = M->getOperand(7);
7339 
7340     assert(NodePtr.getValueType() == MVT::i32 ||
7341            NodePtr.getValueType() == MVT::i64);
7342     assert(RayDir.getValueType() == MVT::v4f16 ||
7343            RayDir.getValueType() == MVT::v4f32);
7344 
7345     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7346     bool Is64 = NodePtr.getValueType() == MVT::i64;
7347     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7348                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7349                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7350                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7351 
7352     SmallVector<SDValue, 16> Ops;
7353 
7354     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7355       SmallVector<SDValue, 3> Lanes;
7356       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7357       if (Lanes[0].getValueSizeInBits() == 32) {
7358         for (unsigned I = 0; I < 3; ++I)
7359           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7360       } else {
7361         if (IsAligned) {
7362           Ops.push_back(
7363             DAG.getBitcast(MVT::i32,
7364                            DAG.getBuildVector(MVT::v2f16, DL,
7365                                               { Lanes[0], Lanes[1] })));
7366           Ops.push_back(Lanes[2]);
7367         } else {
7368           SDValue Elt0 = Ops.pop_back_val();
7369           Ops.push_back(
7370             DAG.getBitcast(MVT::i32,
7371                            DAG.getBuildVector(MVT::v2f16, DL,
7372                                               { Elt0, Lanes[0] })));
7373           Ops.push_back(
7374             DAG.getBitcast(MVT::i32,
7375                            DAG.getBuildVector(MVT::v2f16, DL,
7376                                               { Lanes[1], Lanes[2] })));
7377         }
7378       }
7379     };
7380 
7381     if (Is64)
7382       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7383     else
7384       Ops.push_back(NodePtr);
7385 
7386     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7387     packLanes(RayOrigin, true);
7388     packLanes(RayDir, true);
7389     packLanes(RayInvDir, false);
7390     Ops.push_back(TDescr);
7391     if (IsA16)
7392       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7393     Ops.push_back(M->getChain());
7394 
7395     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7396     MachineMemOperand *MemRef = M->getMemOperand();
7397     DAG.setNodeMemRefs(NewNode, {MemRef});
7398     return SDValue(NewNode, 0);
7399   }
7400   default:
7401     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7402             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7403       return lowerImage(Op, ImageDimIntr, DAG, true);
7404 
7405     return SDValue();
7406   }
7407 }
7408 
7409 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7410 // dwordx4 if on SI.
getMemIntrinsicNode(unsigned Opcode,const SDLoc & DL,SDVTList VTList,ArrayRef<SDValue> Ops,EVT MemVT,MachineMemOperand * MMO,SelectionDAG & DAG) const7411 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7412                                               SDVTList VTList,
7413                                               ArrayRef<SDValue> Ops, EVT MemVT,
7414                                               MachineMemOperand *MMO,
7415                                               SelectionDAG &DAG) const {
7416   EVT VT = VTList.VTs[0];
7417   EVT WidenedVT = VT;
7418   EVT WidenedMemVT = MemVT;
7419   if (!Subtarget->hasDwordx3LoadStores() &&
7420       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7421     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7422                                  WidenedVT.getVectorElementType(), 4);
7423     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7424                                     WidenedMemVT.getVectorElementType(), 4);
7425     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7426   }
7427 
7428   assert(VTList.NumVTs == 2);
7429   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7430 
7431   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7432                                        WidenedMemVT, MMO);
7433   if (WidenedVT != VT) {
7434     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7435                                DAG.getVectorIdxConstant(0, DL));
7436     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7437   }
7438   return NewOp;
7439 }
7440 
handleD16VData(SDValue VData,SelectionDAG & DAG,bool ImageStore) const7441 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7442                                          bool ImageStore) const {
7443   EVT StoreVT = VData.getValueType();
7444 
7445   // No change for f16 and legal vector D16 types.
7446   if (!StoreVT.isVector())
7447     return VData;
7448 
7449   SDLoc DL(VData);
7450   unsigned NumElements = StoreVT.getVectorNumElements();
7451 
7452   if (Subtarget->hasUnpackedD16VMem()) {
7453     // We need to unpack the packed data to store.
7454     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7455     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7456 
7457     EVT EquivStoreVT =
7458         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7459     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7460     return DAG.UnrollVectorOp(ZExt.getNode());
7461   }
7462 
7463   // The sq block of gfx8.1 does not estimate register use correctly for d16
7464   // image store instructions. The data operand is computed as if it were not a
7465   // d16 image instruction.
7466   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7467     // Bitcast to i16
7468     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7469     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7470 
7471     // Decompose into scalars
7472     SmallVector<SDValue, 4> Elts;
7473     DAG.ExtractVectorElements(IntVData, Elts);
7474 
7475     // Group pairs of i16 into v2i16 and bitcast to i32
7476     SmallVector<SDValue, 4> PackedElts;
7477     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7478       SDValue Pair =
7479           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7480       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7481       PackedElts.push_back(IntPair);
7482     }
7483     if ((NumElements % 2) == 1) {
7484       // Handle v3i16
7485       unsigned I = Elts.size() / 2;
7486       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7487                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7488       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7489       PackedElts.push_back(IntPair);
7490     }
7491 
7492     // Pad using UNDEF
7493     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7494 
7495     // Build final vector
7496     EVT VecVT =
7497         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7498     return DAG.getBuildVector(VecVT, DL, PackedElts);
7499   }
7500 
7501   if (NumElements == 3) {
7502     EVT IntStoreVT =
7503         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7504     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7505 
7506     EVT WidenedStoreVT = EVT::getVectorVT(
7507         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7508     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7509                                          WidenedStoreVT.getStoreSizeInBits());
7510     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7511     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7512   }
7513 
7514   assert(isTypeLegal(StoreVT));
7515   return VData;
7516 }
7517 
LowerINTRINSIC_VOID(SDValue Op,SelectionDAG & DAG) const7518 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7519                                               SelectionDAG &DAG) const {
7520   SDLoc DL(Op);
7521   SDValue Chain = Op.getOperand(0);
7522   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7523   MachineFunction &MF = DAG.getMachineFunction();
7524 
7525   switch (IntrinsicID) {
7526   case Intrinsic::amdgcn_exp_compr: {
7527     SDValue Src0 = Op.getOperand(4);
7528     SDValue Src1 = Op.getOperand(5);
7529     // Hack around illegal type on SI by directly selecting it.
7530     if (isTypeLegal(Src0.getValueType()))
7531       return SDValue();
7532 
7533     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7534     SDValue Undef = DAG.getUNDEF(MVT::f32);
7535     const SDValue Ops[] = {
7536       Op.getOperand(2), // tgt
7537       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7538       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7539       Undef, // src2
7540       Undef, // src3
7541       Op.getOperand(7), // vm
7542       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7543       Op.getOperand(3), // en
7544       Op.getOperand(0) // Chain
7545     };
7546 
7547     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7548     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7549   }
7550   case Intrinsic::amdgcn_s_barrier: {
7551     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7552       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7553       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7554       if (WGSize <= ST.getWavefrontSize())
7555         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7556                                           Op.getOperand(0)), 0);
7557     }
7558     return SDValue();
7559   };
7560   case Intrinsic::amdgcn_tbuffer_store: {
7561     SDValue VData = Op.getOperand(2);
7562     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7563     if (IsD16)
7564       VData = handleD16VData(VData, DAG);
7565     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7566     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7567     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7568     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7569     unsigned IdxEn = 1;
7570     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7571       IdxEn = Idx->getZExtValue() != 0;
7572     SDValue Ops[] = {
7573       Chain,
7574       VData,             // vdata
7575       Op.getOperand(3),  // rsrc
7576       Op.getOperand(4),  // vindex
7577       Op.getOperand(5),  // voffset
7578       Op.getOperand(6),  // soffset
7579       Op.getOperand(7),  // offset
7580       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7581       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7582       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7583     };
7584     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7585                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7586     MemSDNode *M = cast<MemSDNode>(Op);
7587     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7588                                    M->getMemoryVT(), M->getMemOperand());
7589   }
7590 
7591   case Intrinsic::amdgcn_struct_tbuffer_store: {
7592     SDValue VData = Op.getOperand(2);
7593     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7594     if (IsD16)
7595       VData = handleD16VData(VData, DAG);
7596     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7597     SDValue Ops[] = {
7598       Chain,
7599       VData,             // vdata
7600       Op.getOperand(3),  // rsrc
7601       Op.getOperand(4),  // vindex
7602       Offsets.first,     // voffset
7603       Op.getOperand(6),  // soffset
7604       Offsets.second,    // offset
7605       Op.getOperand(7),  // format
7606       Op.getOperand(8),  // cachepolicy, swizzled buffer
7607       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7608     };
7609     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7610                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7611     MemSDNode *M = cast<MemSDNode>(Op);
7612     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7613                                    M->getMemoryVT(), M->getMemOperand());
7614   }
7615 
7616   case Intrinsic::amdgcn_raw_tbuffer_store: {
7617     SDValue VData = Op.getOperand(2);
7618     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7619     if (IsD16)
7620       VData = handleD16VData(VData, DAG);
7621     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7622     SDValue Ops[] = {
7623       Chain,
7624       VData,             // vdata
7625       Op.getOperand(3),  // rsrc
7626       DAG.getConstant(0, DL, MVT::i32), // vindex
7627       Offsets.first,     // voffset
7628       Op.getOperand(5),  // soffset
7629       Offsets.second,    // offset
7630       Op.getOperand(6),  // format
7631       Op.getOperand(7),  // cachepolicy, swizzled buffer
7632       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7633     };
7634     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7635                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7636     MemSDNode *M = cast<MemSDNode>(Op);
7637     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7638                                    M->getMemoryVT(), M->getMemOperand());
7639   }
7640 
7641   case Intrinsic::amdgcn_buffer_store:
7642   case Intrinsic::amdgcn_buffer_store_format: {
7643     SDValue VData = Op.getOperand(2);
7644     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7645     if (IsD16)
7646       VData = handleD16VData(VData, DAG);
7647     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7648     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7649     unsigned IdxEn = 1;
7650     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7651       IdxEn = Idx->getZExtValue() != 0;
7652     SDValue Ops[] = {
7653       Chain,
7654       VData,
7655       Op.getOperand(3), // rsrc
7656       Op.getOperand(4), // vindex
7657       SDValue(), // voffset -- will be set by setBufferOffsets
7658       SDValue(), // soffset -- will be set by setBufferOffsets
7659       SDValue(), // offset -- will be set by setBufferOffsets
7660       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7661       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7662     };
7663     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7664     // We don't know the offset if vindex is non-zero, so clear it.
7665     if (IdxEn)
7666       Offset = 0;
7667     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7668                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7669     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7670     MemSDNode *M = cast<MemSDNode>(Op);
7671     M->getMemOperand()->setOffset(Offset);
7672 
7673     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7674     EVT VDataType = VData.getValueType().getScalarType();
7675     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7676       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7677 
7678     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7679                                    M->getMemoryVT(), M->getMemOperand());
7680   }
7681 
7682   case Intrinsic::amdgcn_raw_buffer_store:
7683   case Intrinsic::amdgcn_raw_buffer_store_format: {
7684     const bool IsFormat =
7685         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7686 
7687     SDValue VData = Op.getOperand(2);
7688     EVT VDataVT = VData.getValueType();
7689     EVT EltType = VDataVT.getScalarType();
7690     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7691     if (IsD16) {
7692       VData = handleD16VData(VData, DAG);
7693       VDataVT = VData.getValueType();
7694     }
7695 
7696     if (!isTypeLegal(VDataVT)) {
7697       VData =
7698           DAG.getNode(ISD::BITCAST, DL,
7699                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7700     }
7701 
7702     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7703     SDValue Ops[] = {
7704       Chain,
7705       VData,
7706       Op.getOperand(3), // rsrc
7707       DAG.getConstant(0, DL, MVT::i32), // vindex
7708       Offsets.first,    // voffset
7709       Op.getOperand(5), // soffset
7710       Offsets.second,   // offset
7711       Op.getOperand(6), // cachepolicy, swizzled buffer
7712       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7713     };
7714     unsigned Opc =
7715         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7716     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7717     MemSDNode *M = cast<MemSDNode>(Op);
7718     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7719 
7720     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7721     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7722       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7723 
7724     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7725                                    M->getMemoryVT(), M->getMemOperand());
7726   }
7727 
7728   case Intrinsic::amdgcn_struct_buffer_store:
7729   case Intrinsic::amdgcn_struct_buffer_store_format: {
7730     const bool IsFormat =
7731         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7732 
7733     SDValue VData = Op.getOperand(2);
7734     EVT VDataVT = VData.getValueType();
7735     EVT EltType = VDataVT.getScalarType();
7736     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7737 
7738     if (IsD16) {
7739       VData = handleD16VData(VData, DAG);
7740       VDataVT = VData.getValueType();
7741     }
7742 
7743     if (!isTypeLegal(VDataVT)) {
7744       VData =
7745           DAG.getNode(ISD::BITCAST, DL,
7746                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7747     }
7748 
7749     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7750     SDValue Ops[] = {
7751       Chain,
7752       VData,
7753       Op.getOperand(3), // rsrc
7754       Op.getOperand(4), // vindex
7755       Offsets.first,    // voffset
7756       Op.getOperand(6), // soffset
7757       Offsets.second,   // offset
7758       Op.getOperand(7), // cachepolicy, swizzled buffer
7759       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7760     };
7761     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7762                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7763     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7764     MemSDNode *M = cast<MemSDNode>(Op);
7765     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7766                                                         Ops[3]));
7767 
7768     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7769     EVT VDataType = VData.getValueType().getScalarType();
7770     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7771       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7772 
7773     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7774                                    M->getMemoryVT(), M->getMemOperand());
7775   }
7776   case Intrinsic::amdgcn_end_cf:
7777     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7778                                       Op->getOperand(2), Chain), 0);
7779 
7780   default: {
7781     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7782             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7783       return lowerImage(Op, ImageDimIntr, DAG, true);
7784 
7785     return Op;
7786   }
7787   }
7788 }
7789 
7790 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7791 // offset (the offset that is included in bounds checking and swizzling, to be
7792 // split between the instruction's voffset and immoffset fields) and soffset
7793 // (the offset that is excluded from bounds checking and swizzling, to go in
7794 // the instruction's soffset field).  This function takes the first kind of
7795 // offset and figures out how to split it between voffset and immoffset.
splitBufferOffsets(SDValue Offset,SelectionDAG & DAG) const7796 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7797     SDValue Offset, SelectionDAG &DAG) const {
7798   SDLoc DL(Offset);
7799   const unsigned MaxImm = 4095;
7800   SDValue N0 = Offset;
7801   ConstantSDNode *C1 = nullptr;
7802 
7803   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7804     N0 = SDValue();
7805   else if (DAG.isBaseWithConstantOffset(N0)) {
7806     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7807     N0 = N0.getOperand(0);
7808   }
7809 
7810   if (C1) {
7811     unsigned ImmOffset = C1->getZExtValue();
7812     // If the immediate value is too big for the immoffset field, put the value
7813     // and -4096 into the immoffset field so that the value that is copied/added
7814     // for the voffset field is a multiple of 4096, and it stands more chance
7815     // of being CSEd with the copy/add for another similar load/store.
7816     // However, do not do that rounding down to a multiple of 4096 if that is a
7817     // negative number, as it appears to be illegal to have a negative offset
7818     // in the vgpr, even if adding the immediate offset makes it positive.
7819     unsigned Overflow = ImmOffset & ~MaxImm;
7820     ImmOffset -= Overflow;
7821     if ((int32_t)Overflow < 0) {
7822       Overflow += ImmOffset;
7823       ImmOffset = 0;
7824     }
7825     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7826     if (Overflow) {
7827       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7828       if (!N0)
7829         N0 = OverflowVal;
7830       else {
7831         SDValue Ops[] = { N0, OverflowVal };
7832         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7833       }
7834     }
7835   }
7836   if (!N0)
7837     N0 = DAG.getConstant(0, DL, MVT::i32);
7838   if (!C1)
7839     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7840   return {N0, SDValue(C1, 0)};
7841 }
7842 
7843 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7844 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7845 // pointed to by Offsets.
setBufferOffsets(SDValue CombinedOffset,SelectionDAG & DAG,SDValue * Offsets,Align Alignment) const7846 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7847                                             SelectionDAG &DAG, SDValue *Offsets,
7848                                             Align Alignment) const {
7849   SDLoc DL(CombinedOffset);
7850   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7851     uint32_t Imm = C->getZExtValue();
7852     uint32_t SOffset, ImmOffset;
7853     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7854                                  Alignment)) {
7855       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7856       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7857       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7858       return SOffset + ImmOffset;
7859     }
7860   }
7861   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7862     SDValue N0 = CombinedOffset.getOperand(0);
7863     SDValue N1 = CombinedOffset.getOperand(1);
7864     uint32_t SOffset, ImmOffset;
7865     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7866     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7867                                                 Subtarget, Alignment)) {
7868       Offsets[0] = N0;
7869       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7870       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7871       return 0;
7872     }
7873   }
7874   Offsets[0] = CombinedOffset;
7875   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7876   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7877   return 0;
7878 }
7879 
7880 // Handle 8 bit and 16 bit buffer loads
handleByteShortBufferLoads(SelectionDAG & DAG,EVT LoadVT,SDLoc DL,ArrayRef<SDValue> Ops,MemSDNode * M) const7881 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7882                                                      EVT LoadVT, SDLoc DL,
7883                                                      ArrayRef<SDValue> Ops,
7884                                                      MemSDNode *M) const {
7885   EVT IntVT = LoadVT.changeTypeToInteger();
7886   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7887          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7888 
7889   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7890   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7891                                                Ops, IntVT,
7892                                                M->getMemOperand());
7893   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7894   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7895 
7896   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7897 }
7898 
7899 // Handle 8 bit and 16 bit buffer stores
handleByteShortBufferStores(SelectionDAG & DAG,EVT VDataType,SDLoc DL,SDValue Ops[],MemSDNode * M) const7900 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7901                                                       EVT VDataType, SDLoc DL,
7902                                                       SDValue Ops[],
7903                                                       MemSDNode *M) const {
7904   if (VDataType == MVT::f16)
7905     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7906 
7907   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7908   Ops[1] = BufferStoreExt;
7909   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7910                                  AMDGPUISD::BUFFER_STORE_SHORT;
7911   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7912   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7913                                      M->getMemOperand());
7914 }
7915 
getLoadExtOrTrunc(SelectionDAG & DAG,ISD::LoadExtType ExtType,SDValue Op,const SDLoc & SL,EVT VT)7916 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7917                                  ISD::LoadExtType ExtType, SDValue Op,
7918                                  const SDLoc &SL, EVT VT) {
7919   if (VT.bitsLT(Op.getValueType()))
7920     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7921 
7922   switch (ExtType) {
7923   case ISD::SEXTLOAD:
7924     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7925   case ISD::ZEXTLOAD:
7926     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7927   case ISD::EXTLOAD:
7928     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7929   case ISD::NON_EXTLOAD:
7930     return Op;
7931   }
7932 
7933   llvm_unreachable("invalid ext type");
7934 }
7935 
widenLoad(LoadSDNode * Ld,DAGCombinerInfo & DCI) const7936 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7937   SelectionDAG &DAG = DCI.DAG;
7938   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7939     return SDValue();
7940 
7941   // FIXME: Constant loads should all be marked invariant.
7942   unsigned AS = Ld->getAddressSpace();
7943   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7944       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7945       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7946     return SDValue();
7947 
7948   // Don't do this early, since it may interfere with adjacent load merging for
7949   // illegal types. We can avoid losing alignment information for exotic types
7950   // pre-legalize.
7951   EVT MemVT = Ld->getMemoryVT();
7952   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7953       MemVT.getSizeInBits() >= 32)
7954     return SDValue();
7955 
7956   SDLoc SL(Ld);
7957 
7958   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7959          "unexpected vector extload");
7960 
7961   // TODO: Drop only high part of range.
7962   SDValue Ptr = Ld->getBasePtr();
7963   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7964                                 MVT::i32, SL, Ld->getChain(), Ptr,
7965                                 Ld->getOffset(),
7966                                 Ld->getPointerInfo(), MVT::i32,
7967                                 Ld->getAlignment(),
7968                                 Ld->getMemOperand()->getFlags(),
7969                                 Ld->getAAInfo(),
7970                                 nullptr); // Drop ranges
7971 
7972   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7973   if (MemVT.isFloatingPoint()) {
7974     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7975            "unexpected fp extload");
7976     TruncVT = MemVT.changeTypeToInteger();
7977   }
7978 
7979   SDValue Cvt = NewLoad;
7980   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7981     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7982                       DAG.getValueType(TruncVT));
7983   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7984              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7985     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7986   } else {
7987     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7988   }
7989 
7990   EVT VT = Ld->getValueType(0);
7991   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7992 
7993   DCI.AddToWorklist(Cvt.getNode());
7994 
7995   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7996   // the appropriate extension from the 32-bit load.
7997   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7998   DCI.AddToWorklist(Cvt.getNode());
7999 
8000   // Handle conversion back to floating point if necessary.
8001   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8002 
8003   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8004 }
8005 
LowerLOAD(SDValue Op,SelectionDAG & DAG) const8006 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8007   SDLoc DL(Op);
8008   LoadSDNode *Load = cast<LoadSDNode>(Op);
8009   ISD::LoadExtType ExtType = Load->getExtensionType();
8010   EVT MemVT = Load->getMemoryVT();
8011 
8012   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8013     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8014       return SDValue();
8015 
8016     // FIXME: Copied from PPC
8017     // First, load into 32 bits, then truncate to 1 bit.
8018 
8019     SDValue Chain = Load->getChain();
8020     SDValue BasePtr = Load->getBasePtr();
8021     MachineMemOperand *MMO = Load->getMemOperand();
8022 
8023     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8024 
8025     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8026                                    BasePtr, RealMemVT, MMO);
8027 
8028     if (!MemVT.isVector()) {
8029       SDValue Ops[] = {
8030         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8031         NewLD.getValue(1)
8032       };
8033 
8034       return DAG.getMergeValues(Ops, DL);
8035     }
8036 
8037     SmallVector<SDValue, 3> Elts;
8038     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8039       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8040                                 DAG.getConstant(I, DL, MVT::i32));
8041 
8042       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8043     }
8044 
8045     SDValue Ops[] = {
8046       DAG.getBuildVector(MemVT, DL, Elts),
8047       NewLD.getValue(1)
8048     };
8049 
8050     return DAG.getMergeValues(Ops, DL);
8051   }
8052 
8053   if (!MemVT.isVector())
8054     return SDValue();
8055 
8056   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8057          "Custom lowering for non-i32 vectors hasn't been implemented.");
8058 
8059   unsigned Alignment = Load->getAlignment();
8060   unsigned AS = Load->getAddressSpace();
8061   if (Subtarget->hasLDSMisalignedBug() &&
8062       AS == AMDGPUAS::FLAT_ADDRESS &&
8063       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8064     return SplitVectorLoad(Op, DAG);
8065   }
8066 
8067   MachineFunction &MF = DAG.getMachineFunction();
8068   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8069   // If there is a possibilty that flat instruction access scratch memory
8070   // then we need to use the same legalization rules we use for private.
8071   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8072       !Subtarget->hasMultiDwordFlatScratchAddressing())
8073     AS = MFI->hasFlatScratchInit() ?
8074          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8075 
8076   unsigned NumElements = MemVT.getVectorNumElements();
8077 
8078   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8079       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8080     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8081       if (MemVT.isPow2VectorType())
8082         return SDValue();
8083       return WidenOrSplitVectorLoad(Op, DAG);
8084     }
8085     // Non-uniform loads will be selected to MUBUF instructions, so they
8086     // have the same legalization requirements as global and private
8087     // loads.
8088     //
8089   }
8090 
8091   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8092       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8093       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8094     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8095         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8096         Alignment >= 4 && NumElements < 32) {
8097       if (MemVT.isPow2VectorType())
8098         return SDValue();
8099       return WidenOrSplitVectorLoad(Op, DAG);
8100     }
8101     // Non-uniform loads will be selected to MUBUF instructions, so they
8102     // have the same legalization requirements as global and private
8103     // loads.
8104     //
8105   }
8106   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8107       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8108       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8109       AS == AMDGPUAS::FLAT_ADDRESS) {
8110     if (NumElements > 4)
8111       return SplitVectorLoad(Op, DAG);
8112     // v3 loads not supported on SI.
8113     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8114       return WidenOrSplitVectorLoad(Op, DAG);
8115 
8116     // v3 and v4 loads are supported for private and global memory.
8117     return SDValue();
8118   }
8119   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8120     // Depending on the setting of the private_element_size field in the
8121     // resource descriptor, we can only make private accesses up to a certain
8122     // size.
8123     switch (Subtarget->getMaxPrivateElementSize()) {
8124     case 4: {
8125       SDValue Ops[2];
8126       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8127       return DAG.getMergeValues(Ops, DL);
8128     }
8129     case 8:
8130       if (NumElements > 2)
8131         return SplitVectorLoad(Op, DAG);
8132       return SDValue();
8133     case 16:
8134       // Same as global/flat
8135       if (NumElements > 4)
8136         return SplitVectorLoad(Op, DAG);
8137       // v3 loads not supported on SI.
8138       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8139         return WidenOrSplitVectorLoad(Op, DAG);
8140 
8141       return SDValue();
8142     default:
8143       llvm_unreachable("unsupported private_element_size");
8144     }
8145   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8146     // Use ds_read_b128 or ds_read_b96 when possible.
8147     if (Subtarget->hasDS96AndDS128() &&
8148         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8149          MemVT.getStoreSize() == 12) &&
8150         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8151                                            Load->getAlign()))
8152       return SDValue();
8153 
8154     if (NumElements > 2)
8155       return SplitVectorLoad(Op, DAG);
8156 
8157     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8158     // address is negative, then the instruction is incorrectly treated as
8159     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8160     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8161     // load later in the SILoadStoreOptimizer.
8162     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8163         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8164         Load->getAlignment() < 8) {
8165       return SplitVectorLoad(Op, DAG);
8166     }
8167   }
8168 
8169   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8170                                       MemVT, *Load->getMemOperand())) {
8171     SDValue Ops[2];
8172     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8173     return DAG.getMergeValues(Ops, DL);
8174   }
8175 
8176   return SDValue();
8177 }
8178 
LowerSELECT(SDValue Op,SelectionDAG & DAG) const8179 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8180   EVT VT = Op.getValueType();
8181   assert(VT.getSizeInBits() == 64);
8182 
8183   SDLoc DL(Op);
8184   SDValue Cond = Op.getOperand(0);
8185 
8186   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8187   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8188 
8189   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8190   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8191 
8192   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8193   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8194 
8195   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8196 
8197   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8198   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8199 
8200   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8201 
8202   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8203   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8204 }
8205 
8206 // Catch division cases where we can use shortcuts with rcp and rsq
8207 // instructions.
lowerFastUnsafeFDIV(SDValue Op,SelectionDAG & DAG) const8208 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8209                                               SelectionDAG &DAG) const {
8210   SDLoc SL(Op);
8211   SDValue LHS = Op.getOperand(0);
8212   SDValue RHS = Op.getOperand(1);
8213   EVT VT = Op.getValueType();
8214   const SDNodeFlags Flags = Op->getFlags();
8215 
8216   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
8217                             Flags.hasApproximateFuncs();
8218 
8219   // Without !fpmath accuracy information, we can't do more because we don't
8220   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8221   if (!AllowInaccurateRcp)
8222     return SDValue();
8223 
8224   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8225     if (CLHS->isExactlyValue(1.0)) {
8226       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8227       // the CI documentation has a worst case error of 1 ulp.
8228       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8229       // use it as long as we aren't trying to use denormals.
8230       //
8231       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8232 
8233       // 1.0 / sqrt(x) -> rsq(x)
8234 
8235       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8236       // error seems really high at 2^29 ULP.
8237       if (RHS.getOpcode() == ISD::FSQRT)
8238         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8239 
8240       // 1.0 / x -> rcp(x)
8241       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8242     }
8243 
8244     // Same as for 1.0, but expand the sign out of the constant.
8245     if (CLHS->isExactlyValue(-1.0)) {
8246       // -1.0 / x -> rcp (fneg x)
8247       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8248       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8249     }
8250   }
8251 
8252   // Turn into multiply by the reciprocal.
8253   // x / y -> x * (1.0 / y)
8254   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8255   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8256 }
8257 
getFPBinOp(SelectionDAG & DAG,unsigned Opcode,const SDLoc & SL,EVT VT,SDValue A,SDValue B,SDValue GlueChain,SDNodeFlags Flags)8258 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8259                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8260                           SDNodeFlags Flags) {
8261   if (GlueChain->getNumValues() <= 1) {
8262     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8263   }
8264 
8265   assert(GlueChain->getNumValues() == 3);
8266 
8267   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8268   switch (Opcode) {
8269   default: llvm_unreachable("no chain equivalent for opcode");
8270   case ISD::FMUL:
8271     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8272     break;
8273   }
8274 
8275   return DAG.getNode(Opcode, SL, VTList,
8276                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8277                      Flags);
8278 }
8279 
getFPTernOp(SelectionDAG & DAG,unsigned Opcode,const SDLoc & SL,EVT VT,SDValue A,SDValue B,SDValue C,SDValue GlueChain,SDNodeFlags Flags)8280 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8281                            EVT VT, SDValue A, SDValue B, SDValue C,
8282                            SDValue GlueChain, SDNodeFlags Flags) {
8283   if (GlueChain->getNumValues() <= 1) {
8284     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8285   }
8286 
8287   assert(GlueChain->getNumValues() == 3);
8288 
8289   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8290   switch (Opcode) {
8291   default: llvm_unreachable("no chain equivalent for opcode");
8292   case ISD::FMA:
8293     Opcode = AMDGPUISD::FMA_W_CHAIN;
8294     break;
8295   }
8296 
8297   return DAG.getNode(Opcode, SL, VTList,
8298                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8299                      Flags);
8300 }
8301 
LowerFDIV16(SDValue Op,SelectionDAG & DAG) const8302 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8303   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8304     return FastLowered;
8305 
8306   SDLoc SL(Op);
8307   SDValue Src0 = Op.getOperand(0);
8308   SDValue Src1 = Op.getOperand(1);
8309 
8310   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8311   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8312 
8313   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8314   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8315 
8316   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8317   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8318 
8319   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8320 }
8321 
8322 // Faster 2.5 ULP division that does not support denormals.
lowerFDIV_FAST(SDValue Op,SelectionDAG & DAG) const8323 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8324   SDLoc SL(Op);
8325   SDValue LHS = Op.getOperand(1);
8326   SDValue RHS = Op.getOperand(2);
8327 
8328   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8329 
8330   const APFloat K0Val(BitsToFloat(0x6f800000));
8331   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8332 
8333   const APFloat K1Val(BitsToFloat(0x2f800000));
8334   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8335 
8336   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8337 
8338   EVT SetCCVT =
8339     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8340 
8341   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8342 
8343   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8344 
8345   // TODO: Should this propagate fast-math-flags?
8346   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8347 
8348   // rcp does not support denormals.
8349   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8350 
8351   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8352 
8353   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8354 }
8355 
8356 // Returns immediate value for setting the F32 denorm mode when using the
8357 // S_DENORM_MODE instruction.
getSPDenormModeValue(int SPDenormMode,SelectionDAG & DAG,const SDLoc & SL,const GCNSubtarget * ST)8358 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8359                                           const SDLoc &SL, const GCNSubtarget *ST) {
8360   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8361   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8362                                 ? FP_DENORM_FLUSH_NONE
8363                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8364 
8365   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8366   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8367 }
8368 
LowerFDIV32(SDValue Op,SelectionDAG & DAG) const8369 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8370   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8371     return FastLowered;
8372 
8373   // The selection matcher assumes anything with a chain selecting to a
8374   // mayRaiseFPException machine instruction. Since we're introducing a chain
8375   // here, we need to explicitly report nofpexcept for the regular fdiv
8376   // lowering.
8377   SDNodeFlags Flags = Op->getFlags();
8378   Flags.setNoFPExcept(true);
8379 
8380   SDLoc SL(Op);
8381   SDValue LHS = Op.getOperand(0);
8382   SDValue RHS = Op.getOperand(1);
8383 
8384   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8385 
8386   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8387 
8388   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8389                                           {RHS, RHS, LHS}, Flags);
8390   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8391                                         {LHS, RHS, LHS}, Flags);
8392 
8393   // Denominator is scaled to not be denormal, so using rcp is ok.
8394   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8395                                   DenominatorScaled, Flags);
8396   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8397                                      DenominatorScaled, Flags);
8398 
8399   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8400                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8401                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8402   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8403 
8404   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8405 
8406   if (!HasFP32Denormals) {
8407     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8408     // lowering. The chain dependence is insufficient, and we need glue. We do
8409     // not need the glue variants in a strictfp function.
8410 
8411     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8412 
8413     SDNode *EnableDenorm;
8414     if (Subtarget->hasDenormModeInst()) {
8415       const SDValue EnableDenormValue =
8416           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8417 
8418       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8419                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8420     } else {
8421       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8422                                                         SL, MVT::i32);
8423       EnableDenorm =
8424           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8425                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8426     }
8427 
8428     SDValue Ops[3] = {
8429       NegDivScale0,
8430       SDValue(EnableDenorm, 0),
8431       SDValue(EnableDenorm, 1)
8432     };
8433 
8434     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8435   }
8436 
8437   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8438                              ApproxRcp, One, NegDivScale0, Flags);
8439 
8440   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8441                              ApproxRcp, Fma0, Flags);
8442 
8443   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8444                            Fma1, Fma1, Flags);
8445 
8446   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8447                              NumeratorScaled, Mul, Flags);
8448 
8449   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8450                              Fma2, Fma1, Mul, Fma2, Flags);
8451 
8452   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8453                              NumeratorScaled, Fma3, Flags);
8454 
8455   if (!HasFP32Denormals) {
8456     SDNode *DisableDenorm;
8457     if (Subtarget->hasDenormModeInst()) {
8458       const SDValue DisableDenormValue =
8459           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8460 
8461       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8462                                   Fma4.getValue(1), DisableDenormValue,
8463                                   Fma4.getValue(2)).getNode();
8464     } else {
8465       const SDValue DisableDenormValue =
8466           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8467 
8468       DisableDenorm = DAG.getMachineNode(
8469           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8470           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8471     }
8472 
8473     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8474                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8475     DAG.setRoot(OutputChain);
8476   }
8477 
8478   SDValue Scale = NumeratorScaled.getValue(1);
8479   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8480                              {Fma4, Fma1, Fma3, Scale}, Flags);
8481 
8482   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8483 }
8484 
LowerFDIV64(SDValue Op,SelectionDAG & DAG) const8485 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8486   if (DAG.getTarget().Options.UnsafeFPMath)
8487     return lowerFastUnsafeFDIV(Op, DAG);
8488 
8489   SDLoc SL(Op);
8490   SDValue X = Op.getOperand(0);
8491   SDValue Y = Op.getOperand(1);
8492 
8493   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8494 
8495   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8496 
8497   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8498 
8499   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8500 
8501   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8502 
8503   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8504 
8505   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8506 
8507   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8508 
8509   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8510 
8511   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8512   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8513 
8514   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8515                              NegDivScale0, Mul, DivScale1);
8516 
8517   SDValue Scale;
8518 
8519   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8520     // Workaround a hardware bug on SI where the condition output from div_scale
8521     // is not usable.
8522 
8523     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8524 
8525     // Figure out if the scale to use for div_fmas.
8526     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8527     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8528     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8529     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8530 
8531     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8532     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8533 
8534     SDValue Scale0Hi
8535       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8536     SDValue Scale1Hi
8537       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8538 
8539     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8540     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8541     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8542   } else {
8543     Scale = DivScale1.getValue(1);
8544   }
8545 
8546   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8547                              Fma4, Fma3, Mul, Scale);
8548 
8549   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8550 }
8551 
LowerFDIV(SDValue Op,SelectionDAG & DAG) const8552 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8553   EVT VT = Op.getValueType();
8554 
8555   if (VT == MVT::f32)
8556     return LowerFDIV32(Op, DAG);
8557 
8558   if (VT == MVT::f64)
8559     return LowerFDIV64(Op, DAG);
8560 
8561   if (VT == MVT::f16)
8562     return LowerFDIV16(Op, DAG);
8563 
8564   llvm_unreachable("Unexpected type for fdiv");
8565 }
8566 
LowerSTORE(SDValue Op,SelectionDAG & DAG) const8567 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8568   SDLoc DL(Op);
8569   StoreSDNode *Store = cast<StoreSDNode>(Op);
8570   EVT VT = Store->getMemoryVT();
8571 
8572   if (VT == MVT::i1) {
8573     return DAG.getTruncStore(Store->getChain(), DL,
8574        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8575        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8576   }
8577 
8578   assert(VT.isVector() &&
8579          Store->getValue().getValueType().getScalarType() == MVT::i32);
8580 
8581   unsigned AS = Store->getAddressSpace();
8582   if (Subtarget->hasLDSMisalignedBug() &&
8583       AS == AMDGPUAS::FLAT_ADDRESS &&
8584       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8585     return SplitVectorStore(Op, DAG);
8586   }
8587 
8588   MachineFunction &MF = DAG.getMachineFunction();
8589   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8590   // If there is a possibilty that flat instruction access scratch memory
8591   // then we need to use the same legalization rules we use for private.
8592   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8593       !Subtarget->hasMultiDwordFlatScratchAddressing())
8594     AS = MFI->hasFlatScratchInit() ?
8595          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8596 
8597   unsigned NumElements = VT.getVectorNumElements();
8598   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8599       AS == AMDGPUAS::FLAT_ADDRESS) {
8600     if (NumElements > 4)
8601       return SplitVectorStore(Op, DAG);
8602     // v3 stores not supported on SI.
8603     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8604       return SplitVectorStore(Op, DAG);
8605 
8606     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8607                                         VT, *Store->getMemOperand()))
8608       return expandUnalignedStore(Store, DAG);
8609 
8610     return SDValue();
8611   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8612     switch (Subtarget->getMaxPrivateElementSize()) {
8613     case 4:
8614       return scalarizeVectorStore(Store, DAG);
8615     case 8:
8616       if (NumElements > 2)
8617         return SplitVectorStore(Op, DAG);
8618       return SDValue();
8619     case 16:
8620       if (NumElements > 4 ||
8621           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8622         return SplitVectorStore(Op, DAG);
8623       return SDValue();
8624     default:
8625       llvm_unreachable("unsupported private_element_size");
8626     }
8627   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8628     // Use ds_write_b128 or ds_write_b96 when possible.
8629     if (Subtarget->hasDS96AndDS128() &&
8630         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8631          (VT.getStoreSize() == 12)) &&
8632         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8633                                            Store->getAlign()))
8634       return SDValue();
8635 
8636     if (NumElements > 2)
8637       return SplitVectorStore(Op, DAG);
8638 
8639     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8640     // address is negative, then the instruction is incorrectly treated as
8641     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8642     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8643     // store later in the SILoadStoreOptimizer.
8644     if (!Subtarget->hasUsableDSOffset() &&
8645         NumElements == 2 && VT.getStoreSize() == 8 &&
8646         Store->getAlignment() < 8) {
8647       return SplitVectorStore(Op, DAG);
8648     }
8649 
8650     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8651                                         VT, *Store->getMemOperand())) {
8652       if (VT.isVector())
8653         return SplitVectorStore(Op, DAG);
8654       return expandUnalignedStore(Store, DAG);
8655     }
8656 
8657     return SDValue();
8658   } else {
8659     llvm_unreachable("unhandled address space");
8660   }
8661 }
8662 
LowerTrig(SDValue Op,SelectionDAG & DAG) const8663 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8664   SDLoc DL(Op);
8665   EVT VT = Op.getValueType();
8666   SDValue Arg = Op.getOperand(0);
8667   SDValue TrigVal;
8668 
8669   // Propagate fast-math flags so that the multiply we introduce can be folded
8670   // if Arg is already the result of a multiply by constant.
8671   auto Flags = Op->getFlags();
8672 
8673   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8674 
8675   if (Subtarget->hasTrigReducedRange()) {
8676     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8677     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8678   } else {
8679     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8680   }
8681 
8682   switch (Op.getOpcode()) {
8683   case ISD::FCOS:
8684     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8685   case ISD::FSIN:
8686     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8687   default:
8688     llvm_unreachable("Wrong trig opcode");
8689   }
8690 }
8691 
LowerATOMIC_CMP_SWAP(SDValue Op,SelectionDAG & DAG) const8692 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8693   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8694   assert(AtomicNode->isCompareAndSwap());
8695   unsigned AS = AtomicNode->getAddressSpace();
8696 
8697   // No custom lowering required for local address space
8698   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8699     return Op;
8700 
8701   // Non-local address space requires custom lowering for atomic compare
8702   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8703   SDLoc DL(Op);
8704   SDValue ChainIn = Op.getOperand(0);
8705   SDValue Addr = Op.getOperand(1);
8706   SDValue Old = Op.getOperand(2);
8707   SDValue New = Op.getOperand(3);
8708   EVT VT = Op.getValueType();
8709   MVT SimpleVT = VT.getSimpleVT();
8710   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8711 
8712   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8713   SDValue Ops[] = { ChainIn, Addr, NewOld };
8714 
8715   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8716                                  Ops, VT, AtomicNode->getMemOperand());
8717 }
8718 
8719 //===----------------------------------------------------------------------===//
8720 // Custom DAG optimizations
8721 //===----------------------------------------------------------------------===//
8722 
performUCharToFloatCombine(SDNode * N,DAGCombinerInfo & DCI) const8723 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8724                                                      DAGCombinerInfo &DCI) const {
8725   EVT VT = N->getValueType(0);
8726   EVT ScalarVT = VT.getScalarType();
8727   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8728     return SDValue();
8729 
8730   SelectionDAG &DAG = DCI.DAG;
8731   SDLoc DL(N);
8732 
8733   SDValue Src = N->getOperand(0);
8734   EVT SrcVT = Src.getValueType();
8735 
8736   // TODO: We could try to match extracting the higher bytes, which would be
8737   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8738   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8739   // about in practice.
8740   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8741     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8742       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8743       DCI.AddToWorklist(Cvt.getNode());
8744 
8745       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8746       if (ScalarVT != MVT::f32) {
8747         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8748                           DAG.getTargetConstant(0, DL, MVT::i32));
8749       }
8750       return Cvt;
8751     }
8752   }
8753 
8754   return SDValue();
8755 }
8756 
8757 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8758 
8759 // This is a variant of
8760 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8761 //
8762 // The normal DAG combiner will do this, but only if the add has one use since
8763 // that would increase the number of instructions.
8764 //
8765 // This prevents us from seeing a constant offset that can be folded into a
8766 // memory instruction's addressing mode. If we know the resulting add offset of
8767 // a pointer can be folded into an addressing offset, we can replace the pointer
8768 // operand with the add of new constant offset. This eliminates one of the uses,
8769 // and may allow the remaining use to also be simplified.
8770 //
performSHLPtrCombine(SDNode * N,unsigned AddrSpace,EVT MemVT,DAGCombinerInfo & DCI) const8771 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8772                                                unsigned AddrSpace,
8773                                                EVT MemVT,
8774                                                DAGCombinerInfo &DCI) const {
8775   SDValue N0 = N->getOperand(0);
8776   SDValue N1 = N->getOperand(1);
8777 
8778   // We only do this to handle cases where it's profitable when there are
8779   // multiple uses of the add, so defer to the standard combine.
8780   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8781       N0->hasOneUse())
8782     return SDValue();
8783 
8784   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8785   if (!CN1)
8786     return SDValue();
8787 
8788   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8789   if (!CAdd)
8790     return SDValue();
8791 
8792   // If the resulting offset is too large, we can't fold it into the addressing
8793   // mode offset.
8794   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8795   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8796 
8797   AddrMode AM;
8798   AM.HasBaseReg = true;
8799   AM.BaseOffs = Offset.getSExtValue();
8800   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8801     return SDValue();
8802 
8803   SelectionDAG &DAG = DCI.DAG;
8804   SDLoc SL(N);
8805   EVT VT = N->getValueType(0);
8806 
8807   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8808   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8809 
8810   SDNodeFlags Flags;
8811   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8812                           (N0.getOpcode() == ISD::OR ||
8813                            N0->getFlags().hasNoUnsignedWrap()));
8814 
8815   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8816 }
8817 
8818 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8819 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8820 /// specific intrinsic, but they all place the pointer operand first.
getBasePtrIndex(const MemSDNode * N)8821 static unsigned getBasePtrIndex(const MemSDNode *N) {
8822   switch (N->getOpcode()) {
8823   case ISD::STORE:
8824   case ISD::INTRINSIC_W_CHAIN:
8825   case ISD::INTRINSIC_VOID:
8826     return 2;
8827   default:
8828     return 1;
8829   }
8830 }
8831 
performMemSDNodeCombine(MemSDNode * N,DAGCombinerInfo & DCI) const8832 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8833                                                   DAGCombinerInfo &DCI) const {
8834   SelectionDAG &DAG = DCI.DAG;
8835   SDLoc SL(N);
8836 
8837   unsigned PtrIdx = getBasePtrIndex(N);
8838   SDValue Ptr = N->getOperand(PtrIdx);
8839 
8840   // TODO: We could also do this for multiplies.
8841   if (Ptr.getOpcode() == ISD::SHL) {
8842     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8843                                           N->getMemoryVT(), DCI);
8844     if (NewPtr) {
8845       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8846 
8847       NewOps[PtrIdx] = NewPtr;
8848       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8849     }
8850   }
8851 
8852   return SDValue();
8853 }
8854 
bitOpWithConstantIsReducible(unsigned Opc,uint32_t Val)8855 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8856   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8857          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8858          (Opc == ISD::XOR && Val == 0);
8859 }
8860 
8861 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8862 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8863 // integer combine opportunities since most 64-bit operations are decomposed
8864 // this way.  TODO: We won't want this for SALU especially if it is an inline
8865 // immediate.
splitBinaryBitConstantOp(DAGCombinerInfo & DCI,const SDLoc & SL,unsigned Opc,SDValue LHS,const ConstantSDNode * CRHS) const8866 SDValue SITargetLowering::splitBinaryBitConstantOp(
8867   DAGCombinerInfo &DCI,
8868   const SDLoc &SL,
8869   unsigned Opc, SDValue LHS,
8870   const ConstantSDNode *CRHS) const {
8871   uint64_t Val = CRHS->getZExtValue();
8872   uint32_t ValLo = Lo_32(Val);
8873   uint32_t ValHi = Hi_32(Val);
8874   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8875 
8876     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8877          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8878         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8879     // If we need to materialize a 64-bit immediate, it will be split up later
8880     // anyway. Avoid creating the harder to understand 64-bit immediate
8881     // materialization.
8882     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8883   }
8884 
8885   return SDValue();
8886 }
8887 
8888 // Returns true if argument is a boolean value which is not serialized into
8889 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
isBoolSGPR(SDValue V)8890 static bool isBoolSGPR(SDValue V) {
8891   if (V.getValueType() != MVT::i1)
8892     return false;
8893   switch (V.getOpcode()) {
8894   default: break;
8895   case ISD::SETCC:
8896   case ISD::AND:
8897   case ISD::OR:
8898   case ISD::XOR:
8899   case AMDGPUISD::FP_CLASS:
8900     return true;
8901   }
8902   return false;
8903 }
8904 
8905 // If a constant has all zeroes or all ones within each byte return it.
8906 // Otherwise return 0.
getConstantPermuteMask(uint32_t C)8907 static uint32_t getConstantPermuteMask(uint32_t C) {
8908   // 0xff for any zero byte in the mask
8909   uint32_t ZeroByteMask = 0;
8910   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8911   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8912   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8913   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8914   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8915   if ((NonZeroByteMask & C) != NonZeroByteMask)
8916     return 0; // Partial bytes selected.
8917   return C;
8918 }
8919 
8920 // Check if a node selects whole bytes from its operand 0 starting at a byte
8921 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8922 // or -1 if not succeeded.
8923 // Note byte select encoding:
8924 // value 0-3 selects corresponding source byte;
8925 // value 0xc selects zero;
8926 // value 0xff selects 0xff.
getPermuteMask(SelectionDAG & DAG,SDValue V)8927 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8928   assert(V.getValueSizeInBits() == 32);
8929 
8930   if (V.getNumOperands() != 2)
8931     return ~0;
8932 
8933   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8934   if (!N1)
8935     return ~0;
8936 
8937   uint32_t C = N1->getZExtValue();
8938 
8939   switch (V.getOpcode()) {
8940   default:
8941     break;
8942   case ISD::AND:
8943     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8944       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8945     }
8946     break;
8947 
8948   case ISD::OR:
8949     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8950       return (0x03020100 & ~ConstMask) | ConstMask;
8951     }
8952     break;
8953 
8954   case ISD::SHL:
8955     if (C % 8)
8956       return ~0;
8957 
8958     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8959 
8960   case ISD::SRL:
8961     if (C % 8)
8962       return ~0;
8963 
8964     return uint32_t(0x0c0c0c0c03020100ull >> C);
8965   }
8966 
8967   return ~0;
8968 }
8969 
performAndCombine(SDNode * N,DAGCombinerInfo & DCI) const8970 SDValue SITargetLowering::performAndCombine(SDNode *N,
8971                                             DAGCombinerInfo &DCI) const {
8972   if (DCI.isBeforeLegalize())
8973     return SDValue();
8974 
8975   SelectionDAG &DAG = DCI.DAG;
8976   EVT VT = N->getValueType(0);
8977   SDValue LHS = N->getOperand(0);
8978   SDValue RHS = N->getOperand(1);
8979 
8980 
8981   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8982   if (VT == MVT::i64 && CRHS) {
8983     if (SDValue Split
8984         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8985       return Split;
8986   }
8987 
8988   if (CRHS && VT == MVT::i32) {
8989     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8990     // nb = number of trailing zeroes in mask
8991     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8992     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8993     uint64_t Mask = CRHS->getZExtValue();
8994     unsigned Bits = countPopulation(Mask);
8995     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8996         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8997       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8998         unsigned Shift = CShift->getZExtValue();
8999         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9000         unsigned Offset = NB + Shift;
9001         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9002           SDLoc SL(N);
9003           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9004                                     LHS->getOperand(0),
9005                                     DAG.getConstant(Offset, SL, MVT::i32),
9006                                     DAG.getConstant(Bits, SL, MVT::i32));
9007           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9008           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9009                                     DAG.getValueType(NarrowVT));
9010           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9011                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9012           return Shl;
9013         }
9014       }
9015     }
9016 
9017     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9018     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9019         isa<ConstantSDNode>(LHS.getOperand(2))) {
9020       uint32_t Sel = getConstantPermuteMask(Mask);
9021       if (!Sel)
9022         return SDValue();
9023 
9024       // Select 0xc for all zero bytes
9025       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9026       SDLoc DL(N);
9027       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9028                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9029     }
9030   }
9031 
9032   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9033   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9034   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9035     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9036     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9037 
9038     SDValue X = LHS.getOperand(0);
9039     SDValue Y = RHS.getOperand(0);
9040     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9041       return SDValue();
9042 
9043     if (LCC == ISD::SETO) {
9044       if (X != LHS.getOperand(1))
9045         return SDValue();
9046 
9047       if (RCC == ISD::SETUNE) {
9048         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9049         if (!C1 || !C1->isInfinity() || C1->isNegative())
9050           return SDValue();
9051 
9052         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9053                               SIInstrFlags::N_SUBNORMAL |
9054                               SIInstrFlags::N_ZERO |
9055                               SIInstrFlags::P_ZERO |
9056                               SIInstrFlags::P_SUBNORMAL |
9057                               SIInstrFlags::P_NORMAL;
9058 
9059         static_assert(((~(SIInstrFlags::S_NAN |
9060                           SIInstrFlags::Q_NAN |
9061                           SIInstrFlags::N_INFINITY |
9062                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9063                       "mask not equal");
9064 
9065         SDLoc DL(N);
9066         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9067                            X, DAG.getConstant(Mask, DL, MVT::i32));
9068       }
9069     }
9070   }
9071 
9072   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9073     std::swap(LHS, RHS);
9074 
9075   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9076       RHS.hasOneUse()) {
9077     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9078     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9079     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9080     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9081     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9082         (RHS.getOperand(0) == LHS.getOperand(0) &&
9083          LHS.getOperand(0) == LHS.getOperand(1))) {
9084       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9085       unsigned NewMask = LCC == ISD::SETO ?
9086         Mask->getZExtValue() & ~OrdMask :
9087         Mask->getZExtValue() & OrdMask;
9088 
9089       SDLoc DL(N);
9090       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9091                          DAG.getConstant(NewMask, DL, MVT::i32));
9092     }
9093   }
9094 
9095   if (VT == MVT::i32 &&
9096       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9097     // and x, (sext cc from i1) => select cc, x, 0
9098     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9099       std::swap(LHS, RHS);
9100     if (isBoolSGPR(RHS.getOperand(0)))
9101       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9102                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9103   }
9104 
9105   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9106   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9107   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9108       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9109     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9110     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9111     if (LHSMask != ~0u && RHSMask != ~0u) {
9112       // Canonicalize the expression in an attempt to have fewer unique masks
9113       // and therefore fewer registers used to hold the masks.
9114       if (LHSMask > RHSMask) {
9115         std::swap(LHSMask, RHSMask);
9116         std::swap(LHS, RHS);
9117       }
9118 
9119       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9120       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9121       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9122       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9123 
9124       // Check of we need to combine values from two sources within a byte.
9125       if (!(LHSUsedLanes & RHSUsedLanes) &&
9126           // If we select high and lower word keep it for SDWA.
9127           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9128           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9129         // Each byte in each mask is either selector mask 0-3, or has higher
9130         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9131         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9132         // mask which is not 0xff wins. By anding both masks we have a correct
9133         // result except that 0x0c shall be corrected to give 0x0c only.
9134         uint32_t Mask = LHSMask & RHSMask;
9135         for (unsigned I = 0; I < 32; I += 8) {
9136           uint32_t ByteSel = 0xff << I;
9137           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9138             Mask &= (0x0c << I) & 0xffffffff;
9139         }
9140 
9141         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9142         // or 0x0c.
9143         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9144         SDLoc DL(N);
9145 
9146         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9147                            LHS.getOperand(0), RHS.getOperand(0),
9148                            DAG.getConstant(Sel, DL, MVT::i32));
9149       }
9150     }
9151   }
9152 
9153   return SDValue();
9154 }
9155 
performOrCombine(SDNode * N,DAGCombinerInfo & DCI) const9156 SDValue SITargetLowering::performOrCombine(SDNode *N,
9157                                            DAGCombinerInfo &DCI) const {
9158   SelectionDAG &DAG = DCI.DAG;
9159   SDValue LHS = N->getOperand(0);
9160   SDValue RHS = N->getOperand(1);
9161 
9162   EVT VT = N->getValueType(0);
9163   if (VT == MVT::i1) {
9164     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9165     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9166         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9167       SDValue Src = LHS.getOperand(0);
9168       if (Src != RHS.getOperand(0))
9169         return SDValue();
9170 
9171       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9172       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9173       if (!CLHS || !CRHS)
9174         return SDValue();
9175 
9176       // Only 10 bits are used.
9177       static const uint32_t MaxMask = 0x3ff;
9178 
9179       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9180       SDLoc DL(N);
9181       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9182                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9183     }
9184 
9185     return SDValue();
9186   }
9187 
9188   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9189   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9190       LHS.getOpcode() == AMDGPUISD::PERM &&
9191       isa<ConstantSDNode>(LHS.getOperand(2))) {
9192     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9193     if (!Sel)
9194       return SDValue();
9195 
9196     Sel |= LHS.getConstantOperandVal(2);
9197     SDLoc DL(N);
9198     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9199                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9200   }
9201 
9202   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9203   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9204   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9205       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9206     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9207     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9208     if (LHSMask != ~0u && RHSMask != ~0u) {
9209       // Canonicalize the expression in an attempt to have fewer unique masks
9210       // and therefore fewer registers used to hold the masks.
9211       if (LHSMask > RHSMask) {
9212         std::swap(LHSMask, RHSMask);
9213         std::swap(LHS, RHS);
9214       }
9215 
9216       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9217       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9218       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9219       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9220 
9221       // Check of we need to combine values from two sources within a byte.
9222       if (!(LHSUsedLanes & RHSUsedLanes) &&
9223           // If we select high and lower word keep it for SDWA.
9224           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9225           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9226         // Kill zero bytes selected by other mask. Zero value is 0xc.
9227         LHSMask &= ~RHSUsedLanes;
9228         RHSMask &= ~LHSUsedLanes;
9229         // Add 4 to each active LHS lane
9230         LHSMask |= LHSUsedLanes & 0x04040404;
9231         // Combine masks
9232         uint32_t Sel = LHSMask | RHSMask;
9233         SDLoc DL(N);
9234 
9235         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9236                            LHS.getOperand(0), RHS.getOperand(0),
9237                            DAG.getConstant(Sel, DL, MVT::i32));
9238       }
9239     }
9240   }
9241 
9242   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9243     return SDValue();
9244 
9245   // TODO: This could be a generic combine with a predicate for extracting the
9246   // high half of an integer being free.
9247 
9248   // (or i64:x, (zero_extend i32:y)) ->
9249   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9250   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9251       RHS.getOpcode() != ISD::ZERO_EXTEND)
9252     std::swap(LHS, RHS);
9253 
9254   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9255     SDValue ExtSrc = RHS.getOperand(0);
9256     EVT SrcVT = ExtSrc.getValueType();
9257     if (SrcVT == MVT::i32) {
9258       SDLoc SL(N);
9259       SDValue LowLHS, HiBits;
9260       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9261       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9262 
9263       DCI.AddToWorklist(LowOr.getNode());
9264       DCI.AddToWorklist(HiBits.getNode());
9265 
9266       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9267                                 LowOr, HiBits);
9268       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9269     }
9270   }
9271 
9272   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9273   if (CRHS) {
9274     if (SDValue Split
9275           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9276       return Split;
9277   }
9278 
9279   return SDValue();
9280 }
9281 
performXorCombine(SDNode * N,DAGCombinerInfo & DCI) const9282 SDValue SITargetLowering::performXorCombine(SDNode *N,
9283                                             DAGCombinerInfo &DCI) const {
9284   EVT VT = N->getValueType(0);
9285   if (VT != MVT::i64)
9286     return SDValue();
9287 
9288   SDValue LHS = N->getOperand(0);
9289   SDValue RHS = N->getOperand(1);
9290 
9291   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9292   if (CRHS) {
9293     if (SDValue Split
9294           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9295       return Split;
9296   }
9297 
9298   return SDValue();
9299 }
9300 
9301 // Instructions that will be lowered with a final instruction that zeros the
9302 // high result bits.
9303 // XXX - probably only need to list legal operations.
fp16SrcZerosHighBits(unsigned Opc)9304 static bool fp16SrcZerosHighBits(unsigned Opc) {
9305   switch (Opc) {
9306   case ISD::FADD:
9307   case ISD::FSUB:
9308   case ISD::FMUL:
9309   case ISD::FDIV:
9310   case ISD::FREM:
9311   case ISD::FMA:
9312   case ISD::FMAD:
9313   case ISD::FCANONICALIZE:
9314   case ISD::FP_ROUND:
9315   case ISD::UINT_TO_FP:
9316   case ISD::SINT_TO_FP:
9317   case ISD::FABS:
9318     // Fabs is lowered to a bit operation, but it's an and which will clear the
9319     // high bits anyway.
9320   case ISD::FSQRT:
9321   case ISD::FSIN:
9322   case ISD::FCOS:
9323   case ISD::FPOWI:
9324   case ISD::FPOW:
9325   case ISD::FLOG:
9326   case ISD::FLOG2:
9327   case ISD::FLOG10:
9328   case ISD::FEXP:
9329   case ISD::FEXP2:
9330   case ISD::FCEIL:
9331   case ISD::FTRUNC:
9332   case ISD::FRINT:
9333   case ISD::FNEARBYINT:
9334   case ISD::FROUND:
9335   case ISD::FFLOOR:
9336   case ISD::FMINNUM:
9337   case ISD::FMAXNUM:
9338   case AMDGPUISD::FRACT:
9339   case AMDGPUISD::CLAMP:
9340   case AMDGPUISD::COS_HW:
9341   case AMDGPUISD::SIN_HW:
9342   case AMDGPUISD::FMIN3:
9343   case AMDGPUISD::FMAX3:
9344   case AMDGPUISD::FMED3:
9345   case AMDGPUISD::FMAD_FTZ:
9346   case AMDGPUISD::RCP:
9347   case AMDGPUISD::RSQ:
9348   case AMDGPUISD::RCP_IFLAG:
9349   case AMDGPUISD::LDEXP:
9350     return true;
9351   default:
9352     // fcopysign, select and others may be lowered to 32-bit bit operations
9353     // which don't zero the high bits.
9354     return false;
9355   }
9356 }
9357 
performZeroExtendCombine(SDNode * N,DAGCombinerInfo & DCI) const9358 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9359                                                    DAGCombinerInfo &DCI) const {
9360   if (!Subtarget->has16BitInsts() ||
9361       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9362     return SDValue();
9363 
9364   EVT VT = N->getValueType(0);
9365   if (VT != MVT::i32)
9366     return SDValue();
9367 
9368   SDValue Src = N->getOperand(0);
9369   if (Src.getValueType() != MVT::i16)
9370     return SDValue();
9371 
9372   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9373   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9374   if (Src.getOpcode() == ISD::BITCAST) {
9375     SDValue BCSrc = Src.getOperand(0);
9376     if (BCSrc.getValueType() == MVT::f16 &&
9377         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9378       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9379   }
9380 
9381   return SDValue();
9382 }
9383 
performSignExtendInRegCombine(SDNode * N,DAGCombinerInfo & DCI) const9384 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9385                                                         DAGCombinerInfo &DCI)
9386                                                         const {
9387   SDValue Src = N->getOperand(0);
9388   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9389 
9390   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9391       VTSign->getVT() == MVT::i8) ||
9392       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9393       VTSign->getVT() == MVT::i16)) &&
9394       Src.hasOneUse()) {
9395     auto *M = cast<MemSDNode>(Src);
9396     SDValue Ops[] = {
9397       Src.getOperand(0), // Chain
9398       Src.getOperand(1), // rsrc
9399       Src.getOperand(2), // vindex
9400       Src.getOperand(3), // voffset
9401       Src.getOperand(4), // soffset
9402       Src.getOperand(5), // offset
9403       Src.getOperand(6),
9404       Src.getOperand(7)
9405     };
9406     // replace with BUFFER_LOAD_BYTE/SHORT
9407     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9408                                          Src.getOperand(0).getValueType());
9409     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9410                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9411     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9412                                                           ResList,
9413                                                           Ops, M->getMemoryVT(),
9414                                                           M->getMemOperand());
9415     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9416                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9417   }
9418   return SDValue();
9419 }
9420 
performClassCombine(SDNode * N,DAGCombinerInfo & DCI) const9421 SDValue SITargetLowering::performClassCombine(SDNode *N,
9422                                               DAGCombinerInfo &DCI) const {
9423   SelectionDAG &DAG = DCI.DAG;
9424   SDValue Mask = N->getOperand(1);
9425 
9426   // fp_class x, 0 -> false
9427   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9428     if (CMask->isNullValue())
9429       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9430   }
9431 
9432   if (N->getOperand(0).isUndef())
9433     return DAG.getUNDEF(MVT::i1);
9434 
9435   return SDValue();
9436 }
9437 
performRcpCombine(SDNode * N,DAGCombinerInfo & DCI) const9438 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9439                                             DAGCombinerInfo &DCI) const {
9440   EVT VT = N->getValueType(0);
9441   SDValue N0 = N->getOperand(0);
9442 
9443   if (N0.isUndef())
9444     return N0;
9445 
9446   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9447                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9448     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9449                            N->getFlags());
9450   }
9451 
9452   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9453     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9454                            N0.getOperand(0), N->getFlags());
9455   }
9456 
9457   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9458 }
9459 
isCanonicalized(SelectionDAG & DAG,SDValue Op,unsigned MaxDepth) const9460 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9461                                        unsigned MaxDepth) const {
9462   unsigned Opcode = Op.getOpcode();
9463   if (Opcode == ISD::FCANONICALIZE)
9464     return true;
9465 
9466   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9467     auto F = CFP->getValueAPF();
9468     if (F.isNaN() && F.isSignaling())
9469       return false;
9470     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9471   }
9472 
9473   // If source is a result of another standard FP operation it is already in
9474   // canonical form.
9475   if (MaxDepth == 0)
9476     return false;
9477 
9478   switch (Opcode) {
9479   // These will flush denorms if required.
9480   case ISD::FADD:
9481   case ISD::FSUB:
9482   case ISD::FMUL:
9483   case ISD::FCEIL:
9484   case ISD::FFLOOR:
9485   case ISD::FMA:
9486   case ISD::FMAD:
9487   case ISD::FSQRT:
9488   case ISD::FDIV:
9489   case ISD::FREM:
9490   case ISD::FP_ROUND:
9491   case ISD::FP_EXTEND:
9492   case AMDGPUISD::FMUL_LEGACY:
9493   case AMDGPUISD::FMAD_FTZ:
9494   case AMDGPUISD::RCP:
9495   case AMDGPUISD::RSQ:
9496   case AMDGPUISD::RSQ_CLAMP:
9497   case AMDGPUISD::RCP_LEGACY:
9498   case AMDGPUISD::RCP_IFLAG:
9499   case AMDGPUISD::DIV_SCALE:
9500   case AMDGPUISD::DIV_FMAS:
9501   case AMDGPUISD::DIV_FIXUP:
9502   case AMDGPUISD::FRACT:
9503   case AMDGPUISD::LDEXP:
9504   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9505   case AMDGPUISD::CVT_F32_UBYTE0:
9506   case AMDGPUISD::CVT_F32_UBYTE1:
9507   case AMDGPUISD::CVT_F32_UBYTE2:
9508   case AMDGPUISD::CVT_F32_UBYTE3:
9509     return true;
9510 
9511   // It can/will be lowered or combined as a bit operation.
9512   // Need to check their input recursively to handle.
9513   case ISD::FNEG:
9514   case ISD::FABS:
9515   case ISD::FCOPYSIGN:
9516     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9517 
9518   case ISD::FSIN:
9519   case ISD::FCOS:
9520   case ISD::FSINCOS:
9521     return Op.getValueType().getScalarType() != MVT::f16;
9522 
9523   case ISD::FMINNUM:
9524   case ISD::FMAXNUM:
9525   case ISD::FMINNUM_IEEE:
9526   case ISD::FMAXNUM_IEEE:
9527   case AMDGPUISD::CLAMP:
9528   case AMDGPUISD::FMED3:
9529   case AMDGPUISD::FMAX3:
9530   case AMDGPUISD::FMIN3: {
9531     // FIXME: Shouldn't treat the generic operations different based these.
9532     // However, we aren't really required to flush the result from
9533     // minnum/maxnum..
9534 
9535     // snans will be quieted, so we only need to worry about denormals.
9536     if (Subtarget->supportsMinMaxDenormModes() ||
9537         denormalsEnabledForType(DAG, Op.getValueType()))
9538       return true;
9539 
9540     // Flushing may be required.
9541     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9542     // targets need to check their input recursively.
9543 
9544     // FIXME: Does this apply with clamp? It's implemented with max.
9545     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9546       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9547         return false;
9548     }
9549 
9550     return true;
9551   }
9552   case ISD::SELECT: {
9553     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9554            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9555   }
9556   case ISD::BUILD_VECTOR: {
9557     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9558       SDValue SrcOp = Op.getOperand(i);
9559       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9560         return false;
9561     }
9562 
9563     return true;
9564   }
9565   case ISD::EXTRACT_VECTOR_ELT:
9566   case ISD::EXTRACT_SUBVECTOR: {
9567     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9568   }
9569   case ISD::INSERT_VECTOR_ELT: {
9570     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9571            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9572   }
9573   case ISD::UNDEF:
9574     // Could be anything.
9575     return false;
9576 
9577   case ISD::BITCAST: {
9578     // Hack round the mess we make when legalizing extract_vector_elt
9579     SDValue Src = Op.getOperand(0);
9580     if (Src.getValueType() == MVT::i16 &&
9581         Src.getOpcode() == ISD::TRUNCATE) {
9582       SDValue TruncSrc = Src.getOperand(0);
9583       if (TruncSrc.getValueType() == MVT::i32 &&
9584           TruncSrc.getOpcode() == ISD::BITCAST &&
9585           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9586         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9587       }
9588     }
9589 
9590     return false;
9591   }
9592   case ISD::INTRINSIC_WO_CHAIN: {
9593     unsigned IntrinsicID
9594       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9595     // TODO: Handle more intrinsics
9596     switch (IntrinsicID) {
9597     case Intrinsic::amdgcn_cvt_pkrtz:
9598     case Intrinsic::amdgcn_cubeid:
9599     case Intrinsic::amdgcn_frexp_mant:
9600     case Intrinsic::amdgcn_fdot2:
9601     case Intrinsic::amdgcn_rcp:
9602     case Intrinsic::amdgcn_rsq:
9603     case Intrinsic::amdgcn_rsq_clamp:
9604     case Intrinsic::amdgcn_rcp_legacy:
9605     case Intrinsic::amdgcn_rsq_legacy:
9606     case Intrinsic::amdgcn_trig_preop:
9607       return true;
9608     default:
9609       break;
9610     }
9611 
9612     LLVM_FALLTHROUGH;
9613   }
9614   default:
9615     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9616            DAG.isKnownNeverSNaN(Op);
9617   }
9618 
9619   llvm_unreachable("invalid operation");
9620 }
9621 
9622 // Constant fold canonicalize.
getCanonicalConstantFP(SelectionDAG & DAG,const SDLoc & SL,EVT VT,const APFloat & C) const9623 SDValue SITargetLowering::getCanonicalConstantFP(
9624   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9625   // Flush denormals to 0 if not enabled.
9626   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9627     return DAG.getConstantFP(0.0, SL, VT);
9628 
9629   if (C.isNaN()) {
9630     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9631     if (C.isSignaling()) {
9632       // Quiet a signaling NaN.
9633       // FIXME: Is this supposed to preserve payload bits?
9634       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9635     }
9636 
9637     // Make sure it is the canonical NaN bitpattern.
9638     //
9639     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9640     // immediate?
9641     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9642       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9643   }
9644 
9645   // Already canonical.
9646   return DAG.getConstantFP(C, SL, VT);
9647 }
9648 
vectorEltWillFoldAway(SDValue Op)9649 static bool vectorEltWillFoldAway(SDValue Op) {
9650   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9651 }
9652 
performFCanonicalizeCombine(SDNode * N,DAGCombinerInfo & DCI) const9653 SDValue SITargetLowering::performFCanonicalizeCombine(
9654   SDNode *N,
9655   DAGCombinerInfo &DCI) const {
9656   SelectionDAG &DAG = DCI.DAG;
9657   SDValue N0 = N->getOperand(0);
9658   EVT VT = N->getValueType(0);
9659 
9660   // fcanonicalize undef -> qnan
9661   if (N0.isUndef()) {
9662     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9663     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9664   }
9665 
9666   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9667     EVT VT = N->getValueType(0);
9668     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9669   }
9670 
9671   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9672   //                                                   (fcanonicalize k)
9673   //
9674   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9675 
9676   // TODO: This could be better with wider vectors that will be split to v2f16,
9677   // and to consider uses since there aren't that many packed operations.
9678   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9679       isTypeLegal(MVT::v2f16)) {
9680     SDLoc SL(N);
9681     SDValue NewElts[2];
9682     SDValue Lo = N0.getOperand(0);
9683     SDValue Hi = N0.getOperand(1);
9684     EVT EltVT = Lo.getValueType();
9685 
9686     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9687       for (unsigned I = 0; I != 2; ++I) {
9688         SDValue Op = N0.getOperand(I);
9689         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9690           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9691                                               CFP->getValueAPF());
9692         } else if (Op.isUndef()) {
9693           // Handled below based on what the other operand is.
9694           NewElts[I] = Op;
9695         } else {
9696           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9697         }
9698       }
9699 
9700       // If one half is undef, and one is constant, perfer a splat vector rather
9701       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9702       // cheaper to use and may be free with a packed operation.
9703       if (NewElts[0].isUndef()) {
9704         if (isa<ConstantFPSDNode>(NewElts[1]))
9705           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9706             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9707       }
9708 
9709       if (NewElts[1].isUndef()) {
9710         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9711           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9712       }
9713 
9714       return DAG.getBuildVector(VT, SL, NewElts);
9715     }
9716   }
9717 
9718   unsigned SrcOpc = N0.getOpcode();
9719 
9720   // If it's free to do so, push canonicalizes further up the source, which may
9721   // find a canonical source.
9722   //
9723   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9724   // sNaNs.
9725   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9726     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9727     if (CRHS && N0.hasOneUse()) {
9728       SDLoc SL(N);
9729       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9730                                    N0.getOperand(0));
9731       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9732       DCI.AddToWorklist(Canon0.getNode());
9733 
9734       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9735     }
9736   }
9737 
9738   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9739 }
9740 
minMaxOpcToMin3Max3Opc(unsigned Opc)9741 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9742   switch (Opc) {
9743   case ISD::FMAXNUM:
9744   case ISD::FMAXNUM_IEEE:
9745     return AMDGPUISD::FMAX3;
9746   case ISD::SMAX:
9747     return AMDGPUISD::SMAX3;
9748   case ISD::UMAX:
9749     return AMDGPUISD::UMAX3;
9750   case ISD::FMINNUM:
9751   case ISD::FMINNUM_IEEE:
9752     return AMDGPUISD::FMIN3;
9753   case ISD::SMIN:
9754     return AMDGPUISD::SMIN3;
9755   case ISD::UMIN:
9756     return AMDGPUISD::UMIN3;
9757   default:
9758     llvm_unreachable("Not a min/max opcode");
9759   }
9760 }
9761 
performIntMed3ImmCombine(SelectionDAG & DAG,const SDLoc & SL,SDValue Op0,SDValue Op1,bool Signed) const9762 SDValue SITargetLowering::performIntMed3ImmCombine(
9763   SelectionDAG &DAG, const SDLoc &SL,
9764   SDValue Op0, SDValue Op1, bool Signed) const {
9765   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9766   if (!K1)
9767     return SDValue();
9768 
9769   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9770   if (!K0)
9771     return SDValue();
9772 
9773   if (Signed) {
9774     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9775       return SDValue();
9776   } else {
9777     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9778       return SDValue();
9779   }
9780 
9781   EVT VT = K0->getValueType(0);
9782   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9783   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9784     return DAG.getNode(Med3Opc, SL, VT,
9785                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9786   }
9787 
9788   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9789   MVT NVT = MVT::i32;
9790   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9791 
9792   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9793   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9794   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9795 
9796   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9797   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9798 }
9799 
getSplatConstantFP(SDValue Op)9800 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9801   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9802     return C;
9803 
9804   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9805     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9806       return C;
9807   }
9808 
9809   return nullptr;
9810 }
9811 
performFPMed3ImmCombine(SelectionDAG & DAG,const SDLoc & SL,SDValue Op0,SDValue Op1) const9812 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9813                                                   const SDLoc &SL,
9814                                                   SDValue Op0,
9815                                                   SDValue Op1) const {
9816   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9817   if (!K1)
9818     return SDValue();
9819 
9820   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9821   if (!K0)
9822     return SDValue();
9823 
9824   // Ordered >= (although NaN inputs should have folded away by now).
9825   if (K0->getValueAPF() > K1->getValueAPF())
9826     return SDValue();
9827 
9828   const MachineFunction &MF = DAG.getMachineFunction();
9829   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9830 
9831   // TODO: Check IEEE bit enabled?
9832   EVT VT = Op0.getValueType();
9833   if (Info->getMode().DX10Clamp) {
9834     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9835     // hardware fmed3 behavior converting to a min.
9836     // FIXME: Should this be allowing -0.0?
9837     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9838       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9839   }
9840 
9841   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9842   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9843     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9844     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9845     // then give the other result, which is different from med3 with a NaN
9846     // input.
9847     SDValue Var = Op0.getOperand(0);
9848     if (!DAG.isKnownNeverSNaN(Var))
9849       return SDValue();
9850 
9851     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9852 
9853     if ((!K0->hasOneUse() ||
9854          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9855         (!K1->hasOneUse() ||
9856          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9857       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9858                          Var, SDValue(K0, 0), SDValue(K1, 0));
9859     }
9860   }
9861 
9862   return SDValue();
9863 }
9864 
performMinMaxCombine(SDNode * N,DAGCombinerInfo & DCI) const9865 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9866                                                DAGCombinerInfo &DCI) const {
9867   SelectionDAG &DAG = DCI.DAG;
9868 
9869   EVT VT = N->getValueType(0);
9870   unsigned Opc = N->getOpcode();
9871   SDValue Op0 = N->getOperand(0);
9872   SDValue Op1 = N->getOperand(1);
9873 
9874   // Only do this if the inner op has one use since this will just increases
9875   // register pressure for no benefit.
9876 
9877   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9878       !VT.isVector() &&
9879       (VT == MVT::i32 || VT == MVT::f32 ||
9880        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9881     // max(max(a, b), c) -> max3(a, b, c)
9882     // min(min(a, b), c) -> min3(a, b, c)
9883     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9884       SDLoc DL(N);
9885       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9886                          DL,
9887                          N->getValueType(0),
9888                          Op0.getOperand(0),
9889                          Op0.getOperand(1),
9890                          Op1);
9891     }
9892 
9893     // Try commuted.
9894     // max(a, max(b, c)) -> max3(a, b, c)
9895     // min(a, min(b, c)) -> min3(a, b, c)
9896     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9897       SDLoc DL(N);
9898       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9899                          DL,
9900                          N->getValueType(0),
9901                          Op0,
9902                          Op1.getOperand(0),
9903                          Op1.getOperand(1));
9904     }
9905   }
9906 
9907   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9908   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9909     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9910       return Med3;
9911   }
9912 
9913   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9914     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9915       return Med3;
9916   }
9917 
9918   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9919   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9920        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9921        (Opc == AMDGPUISD::FMIN_LEGACY &&
9922         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9923       (VT == MVT::f32 || VT == MVT::f64 ||
9924        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9925        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9926       Op0.hasOneUse()) {
9927     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9928       return Res;
9929   }
9930 
9931   return SDValue();
9932 }
9933 
isClampZeroToOne(SDValue A,SDValue B)9934 static bool isClampZeroToOne(SDValue A, SDValue B) {
9935   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9936     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9937       // FIXME: Should this be allowing -0.0?
9938       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9939              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9940     }
9941   }
9942 
9943   return false;
9944 }
9945 
9946 // FIXME: Should only worry about snans for version with chain.
performFMed3Combine(SDNode * N,DAGCombinerInfo & DCI) const9947 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9948                                               DAGCombinerInfo &DCI) const {
9949   EVT VT = N->getValueType(0);
9950   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9951   // NaNs. With a NaN input, the order of the operands may change the result.
9952 
9953   SelectionDAG &DAG = DCI.DAG;
9954   SDLoc SL(N);
9955 
9956   SDValue Src0 = N->getOperand(0);
9957   SDValue Src1 = N->getOperand(1);
9958   SDValue Src2 = N->getOperand(2);
9959 
9960   if (isClampZeroToOne(Src0, Src1)) {
9961     // const_a, const_b, x -> clamp is safe in all cases including signaling
9962     // nans.
9963     // FIXME: Should this be allowing -0.0?
9964     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9965   }
9966 
9967   const MachineFunction &MF = DAG.getMachineFunction();
9968   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9969 
9970   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9971   // handling no dx10-clamp?
9972   if (Info->getMode().DX10Clamp) {
9973     // If NaNs is clamped to 0, we are free to reorder the inputs.
9974 
9975     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9976       std::swap(Src0, Src1);
9977 
9978     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9979       std::swap(Src1, Src2);
9980 
9981     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9982       std::swap(Src0, Src1);
9983 
9984     if (isClampZeroToOne(Src1, Src2))
9985       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9986   }
9987 
9988   return SDValue();
9989 }
9990 
performCvtPkRTZCombine(SDNode * N,DAGCombinerInfo & DCI) const9991 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9992                                                  DAGCombinerInfo &DCI) const {
9993   SDValue Src0 = N->getOperand(0);
9994   SDValue Src1 = N->getOperand(1);
9995   if (Src0.isUndef() && Src1.isUndef())
9996     return DCI.DAG.getUNDEF(N->getValueType(0));
9997   return SDValue();
9998 }
9999 
10000 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10001 // expanded into a set of cmp/select instructions.
shouldExpandVectorDynExt(unsigned EltSize,unsigned NumElem,bool IsDivergentIdx)10002 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10003                                                 unsigned NumElem,
10004                                                 bool IsDivergentIdx) {
10005   if (UseDivergentRegisterIndexing)
10006     return false;
10007 
10008   unsigned VecSize = EltSize * NumElem;
10009 
10010   // Sub-dword vectors of size 2 dword or less have better implementation.
10011   if (VecSize <= 64 && EltSize < 32)
10012     return false;
10013 
10014   // Always expand the rest of sub-dword instructions, otherwise it will be
10015   // lowered via memory.
10016   if (EltSize < 32)
10017     return true;
10018 
10019   // Always do this if var-idx is divergent, otherwise it will become a loop.
10020   if (IsDivergentIdx)
10021     return true;
10022 
10023   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10024   unsigned NumInsts = NumElem /* Number of compares */ +
10025                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10026   return NumInsts <= 16;
10027 }
10028 
shouldExpandVectorDynExt(SDNode * N)10029 static bool shouldExpandVectorDynExt(SDNode *N) {
10030   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10031   if (isa<ConstantSDNode>(Idx))
10032     return false;
10033 
10034   SDValue Vec = N->getOperand(0);
10035   EVT VecVT = Vec.getValueType();
10036   EVT EltVT = VecVT.getVectorElementType();
10037   unsigned EltSize = EltVT.getSizeInBits();
10038   unsigned NumElem = VecVT.getVectorNumElements();
10039 
10040   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10041                                                     Idx->isDivergent());
10042 }
10043 
performExtractVectorEltCombine(SDNode * N,DAGCombinerInfo & DCI) const10044 SDValue SITargetLowering::performExtractVectorEltCombine(
10045   SDNode *N, DAGCombinerInfo &DCI) const {
10046   SDValue Vec = N->getOperand(0);
10047   SelectionDAG &DAG = DCI.DAG;
10048 
10049   EVT VecVT = Vec.getValueType();
10050   EVT EltVT = VecVT.getVectorElementType();
10051 
10052   if ((Vec.getOpcode() == ISD::FNEG ||
10053        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10054     SDLoc SL(N);
10055     EVT EltVT = N->getValueType(0);
10056     SDValue Idx = N->getOperand(1);
10057     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10058                               Vec.getOperand(0), Idx);
10059     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10060   }
10061 
10062   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10063   //    =>
10064   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10065   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10066   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10067   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10068     SDLoc SL(N);
10069     EVT EltVT = N->getValueType(0);
10070     SDValue Idx = N->getOperand(1);
10071     unsigned Opc = Vec.getOpcode();
10072 
10073     switch(Opc) {
10074     default:
10075       break;
10076       // TODO: Support other binary operations.
10077     case ISD::FADD:
10078     case ISD::FSUB:
10079     case ISD::FMUL:
10080     case ISD::ADD:
10081     case ISD::UMIN:
10082     case ISD::UMAX:
10083     case ISD::SMIN:
10084     case ISD::SMAX:
10085     case ISD::FMAXNUM:
10086     case ISD::FMINNUM:
10087     case ISD::FMAXNUM_IEEE:
10088     case ISD::FMINNUM_IEEE: {
10089       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10090                                  Vec.getOperand(0), Idx);
10091       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10092                                  Vec.getOperand(1), Idx);
10093 
10094       DCI.AddToWorklist(Elt0.getNode());
10095       DCI.AddToWorklist(Elt1.getNode());
10096       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10097     }
10098     }
10099   }
10100 
10101   unsigned VecSize = VecVT.getSizeInBits();
10102   unsigned EltSize = EltVT.getSizeInBits();
10103 
10104   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10105   if (::shouldExpandVectorDynExt(N)) {
10106     SDLoc SL(N);
10107     SDValue Idx = N->getOperand(1);
10108     SDValue V;
10109     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10110       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10111       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10112       if (I == 0)
10113         V = Elt;
10114       else
10115         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10116     }
10117     return V;
10118   }
10119 
10120   if (!DCI.isBeforeLegalize())
10121     return SDValue();
10122 
10123   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10124   // elements. This exposes more load reduction opportunities by replacing
10125   // multiple small extract_vector_elements with a single 32-bit extract.
10126   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10127   if (isa<MemSDNode>(Vec) &&
10128       EltSize <= 16 &&
10129       EltVT.isByteSized() &&
10130       VecSize > 32 &&
10131       VecSize % 32 == 0 &&
10132       Idx) {
10133     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10134 
10135     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10136     unsigned EltIdx = BitIndex / 32;
10137     unsigned LeftoverBitIdx = BitIndex % 32;
10138     SDLoc SL(N);
10139 
10140     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10141     DCI.AddToWorklist(Cast.getNode());
10142 
10143     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10144                               DAG.getConstant(EltIdx, SL, MVT::i32));
10145     DCI.AddToWorklist(Elt.getNode());
10146     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10147                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10148     DCI.AddToWorklist(Srl.getNode());
10149 
10150     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10151     DCI.AddToWorklist(Trunc.getNode());
10152     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10153   }
10154 
10155   return SDValue();
10156 }
10157 
10158 SDValue
performInsertVectorEltCombine(SDNode * N,DAGCombinerInfo & DCI) const10159 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10160                                                 DAGCombinerInfo &DCI) const {
10161   SDValue Vec = N->getOperand(0);
10162   SDValue Idx = N->getOperand(2);
10163   EVT VecVT = Vec.getValueType();
10164   EVT EltVT = VecVT.getVectorElementType();
10165 
10166   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10167   // => BUILD_VECTOR n x select (e, const-idx)
10168   if (!::shouldExpandVectorDynExt(N))
10169     return SDValue();
10170 
10171   SelectionDAG &DAG = DCI.DAG;
10172   SDLoc SL(N);
10173   SDValue Ins = N->getOperand(1);
10174   EVT IdxVT = Idx.getValueType();
10175 
10176   SmallVector<SDValue, 16> Ops;
10177   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10178     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10179     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10180     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10181     Ops.push_back(V);
10182   }
10183 
10184   return DAG.getBuildVector(VecVT, SL, Ops);
10185 }
10186 
getFusedOpcode(const SelectionDAG & DAG,const SDNode * N0,const SDNode * N1) const10187 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10188                                           const SDNode *N0,
10189                                           const SDNode *N1) const {
10190   EVT VT = N0->getValueType(0);
10191 
10192   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10193   // support denormals ever.
10194   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10195        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10196         getSubtarget()->hasMadF16())) &&
10197        isOperationLegal(ISD::FMAD, VT))
10198     return ISD::FMAD;
10199 
10200   const TargetOptions &Options = DAG.getTarget().Options;
10201   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10202        (N0->getFlags().hasAllowContract() &&
10203         N1->getFlags().hasAllowContract())) &&
10204       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10205     return ISD::FMA;
10206   }
10207 
10208   return 0;
10209 }
10210 
10211 // For a reassociatable opcode perform:
10212 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
reassociateScalarOps(SDNode * N,SelectionDAG & DAG) const10213 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10214                                                SelectionDAG &DAG) const {
10215   EVT VT = N->getValueType(0);
10216   if (VT != MVT::i32 && VT != MVT::i64)
10217     return SDValue();
10218 
10219   unsigned Opc = N->getOpcode();
10220   SDValue Op0 = N->getOperand(0);
10221   SDValue Op1 = N->getOperand(1);
10222 
10223   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10224     return SDValue();
10225 
10226   if (Op0->isDivergent())
10227     std::swap(Op0, Op1);
10228 
10229   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10230     return SDValue();
10231 
10232   SDValue Op2 = Op1.getOperand(1);
10233   Op1 = Op1.getOperand(0);
10234   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10235     return SDValue();
10236 
10237   if (Op1->isDivergent())
10238     std::swap(Op1, Op2);
10239 
10240   // If either operand is constant this will conflict with
10241   // DAGCombiner::ReassociateOps().
10242   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10243       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10244     return SDValue();
10245 
10246   SDLoc SL(N);
10247   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10248   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10249 }
10250 
getMad64_32(SelectionDAG & DAG,const SDLoc & SL,EVT VT,SDValue N0,SDValue N1,SDValue N2,bool Signed)10251 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10252                            EVT VT,
10253                            SDValue N0, SDValue N1, SDValue N2,
10254                            bool Signed) {
10255   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10256   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10257   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10258   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10259 }
10260 
performAddCombine(SDNode * N,DAGCombinerInfo & DCI) const10261 SDValue SITargetLowering::performAddCombine(SDNode *N,
10262                                             DAGCombinerInfo &DCI) const {
10263   SelectionDAG &DAG = DCI.DAG;
10264   EVT VT = N->getValueType(0);
10265   SDLoc SL(N);
10266   SDValue LHS = N->getOperand(0);
10267   SDValue RHS = N->getOperand(1);
10268 
10269   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10270       && Subtarget->hasMad64_32() &&
10271       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10272       VT.getScalarSizeInBits() <= 64) {
10273     if (LHS.getOpcode() != ISD::MUL)
10274       std::swap(LHS, RHS);
10275 
10276     SDValue MulLHS = LHS.getOperand(0);
10277     SDValue MulRHS = LHS.getOperand(1);
10278     SDValue AddRHS = RHS;
10279 
10280     // TODO: Maybe restrict if SGPR inputs.
10281     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10282         numBitsUnsigned(MulRHS, DAG) <= 32) {
10283       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10284       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10285       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10286       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10287     }
10288 
10289     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10290       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10291       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10292       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10293       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10294     }
10295 
10296     return SDValue();
10297   }
10298 
10299   if (SDValue V = reassociateScalarOps(N, DAG)) {
10300     return V;
10301   }
10302 
10303   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10304     return SDValue();
10305 
10306   // add x, zext (setcc) => addcarry x, 0, setcc
10307   // add x, sext (setcc) => subcarry x, 0, setcc
10308   unsigned Opc = LHS.getOpcode();
10309   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10310       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10311     std::swap(RHS, LHS);
10312 
10313   Opc = RHS.getOpcode();
10314   switch (Opc) {
10315   default: break;
10316   case ISD::ZERO_EXTEND:
10317   case ISD::SIGN_EXTEND:
10318   case ISD::ANY_EXTEND: {
10319     auto Cond = RHS.getOperand(0);
10320     // If this won't be a real VOPC output, we would still need to insert an
10321     // extra instruction anyway.
10322     if (!isBoolSGPR(Cond))
10323       break;
10324     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10325     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10326     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10327     return DAG.getNode(Opc, SL, VTList, Args);
10328   }
10329   case ISD::ADDCARRY: {
10330     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10331     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10332     if (!C || C->getZExtValue() != 0) break;
10333     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10334     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10335   }
10336   }
10337   return SDValue();
10338 }
10339 
performSubCombine(SDNode * N,DAGCombinerInfo & DCI) const10340 SDValue SITargetLowering::performSubCombine(SDNode *N,
10341                                             DAGCombinerInfo &DCI) const {
10342   SelectionDAG &DAG = DCI.DAG;
10343   EVT VT = N->getValueType(0);
10344 
10345   if (VT != MVT::i32)
10346     return SDValue();
10347 
10348   SDLoc SL(N);
10349   SDValue LHS = N->getOperand(0);
10350   SDValue RHS = N->getOperand(1);
10351 
10352   // sub x, zext (setcc) => subcarry x, 0, setcc
10353   // sub x, sext (setcc) => addcarry x, 0, setcc
10354   unsigned Opc = RHS.getOpcode();
10355   switch (Opc) {
10356   default: break;
10357   case ISD::ZERO_EXTEND:
10358   case ISD::SIGN_EXTEND:
10359   case ISD::ANY_EXTEND: {
10360     auto Cond = RHS.getOperand(0);
10361     // If this won't be a real VOPC output, we would still need to insert an
10362     // extra instruction anyway.
10363     if (!isBoolSGPR(Cond))
10364       break;
10365     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10366     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10367     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10368     return DAG.getNode(Opc, SL, VTList, Args);
10369   }
10370   }
10371 
10372   if (LHS.getOpcode() == ISD::SUBCARRY) {
10373     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10374     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10375     if (!C || !C->isNullValue())
10376       return SDValue();
10377     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10378     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10379   }
10380   return SDValue();
10381 }
10382 
performAddCarrySubCarryCombine(SDNode * N,DAGCombinerInfo & DCI) const10383 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10384   DAGCombinerInfo &DCI) const {
10385 
10386   if (N->getValueType(0) != MVT::i32)
10387     return SDValue();
10388 
10389   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10390   if (!C || C->getZExtValue() != 0)
10391     return SDValue();
10392 
10393   SelectionDAG &DAG = DCI.DAG;
10394   SDValue LHS = N->getOperand(0);
10395 
10396   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10397   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10398   unsigned LHSOpc = LHS.getOpcode();
10399   unsigned Opc = N->getOpcode();
10400   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10401       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10402     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10403     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10404   }
10405   return SDValue();
10406 }
10407 
performFAddCombine(SDNode * N,DAGCombinerInfo & DCI) const10408 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10409                                              DAGCombinerInfo &DCI) const {
10410   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10411     return SDValue();
10412 
10413   SelectionDAG &DAG = DCI.DAG;
10414   EVT VT = N->getValueType(0);
10415 
10416   SDLoc SL(N);
10417   SDValue LHS = N->getOperand(0);
10418   SDValue RHS = N->getOperand(1);
10419 
10420   // These should really be instruction patterns, but writing patterns with
10421   // source modiifiers is a pain.
10422 
10423   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10424   if (LHS.getOpcode() == ISD::FADD) {
10425     SDValue A = LHS.getOperand(0);
10426     if (A == LHS.getOperand(1)) {
10427       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10428       if (FusedOp != 0) {
10429         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10430         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10431       }
10432     }
10433   }
10434 
10435   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10436   if (RHS.getOpcode() == ISD::FADD) {
10437     SDValue A = RHS.getOperand(0);
10438     if (A == RHS.getOperand(1)) {
10439       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10440       if (FusedOp != 0) {
10441         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10442         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10443       }
10444     }
10445   }
10446 
10447   return SDValue();
10448 }
10449 
performFSubCombine(SDNode * N,DAGCombinerInfo & DCI) const10450 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10451                                              DAGCombinerInfo &DCI) const {
10452   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10453     return SDValue();
10454 
10455   SelectionDAG &DAG = DCI.DAG;
10456   SDLoc SL(N);
10457   EVT VT = N->getValueType(0);
10458   assert(!VT.isVector());
10459 
10460   // Try to get the fneg to fold into the source modifier. This undoes generic
10461   // DAG combines and folds them into the mad.
10462   //
10463   // Only do this if we are not trying to support denormals. v_mad_f32 does
10464   // not support denormals ever.
10465   SDValue LHS = N->getOperand(0);
10466   SDValue RHS = N->getOperand(1);
10467   if (LHS.getOpcode() == ISD::FADD) {
10468     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10469     SDValue A = LHS.getOperand(0);
10470     if (A == LHS.getOperand(1)) {
10471       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10472       if (FusedOp != 0){
10473         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10474         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10475 
10476         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10477       }
10478     }
10479   }
10480 
10481   if (RHS.getOpcode() == ISD::FADD) {
10482     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10483 
10484     SDValue A = RHS.getOperand(0);
10485     if (A == RHS.getOperand(1)) {
10486       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10487       if (FusedOp != 0){
10488         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10489         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10490       }
10491     }
10492   }
10493 
10494   return SDValue();
10495 }
10496 
performFMACombine(SDNode * N,DAGCombinerInfo & DCI) const10497 SDValue SITargetLowering::performFMACombine(SDNode *N,
10498                                             DAGCombinerInfo &DCI) const {
10499   SelectionDAG &DAG = DCI.DAG;
10500   EVT VT = N->getValueType(0);
10501   SDLoc SL(N);
10502 
10503   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10504     return SDValue();
10505 
10506   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10507   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10508   SDValue Op1 = N->getOperand(0);
10509   SDValue Op2 = N->getOperand(1);
10510   SDValue FMA = N->getOperand(2);
10511 
10512   if (FMA.getOpcode() != ISD::FMA ||
10513       Op1.getOpcode() != ISD::FP_EXTEND ||
10514       Op2.getOpcode() != ISD::FP_EXTEND)
10515     return SDValue();
10516 
10517   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10518   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10519   // is sufficient to allow generaing fdot2.
10520   const TargetOptions &Options = DAG.getTarget().Options;
10521   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10522       (N->getFlags().hasAllowContract() &&
10523        FMA->getFlags().hasAllowContract())) {
10524     Op1 = Op1.getOperand(0);
10525     Op2 = Op2.getOperand(0);
10526     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10527         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10528       return SDValue();
10529 
10530     SDValue Vec1 = Op1.getOperand(0);
10531     SDValue Idx1 = Op1.getOperand(1);
10532     SDValue Vec2 = Op2.getOperand(0);
10533 
10534     SDValue FMAOp1 = FMA.getOperand(0);
10535     SDValue FMAOp2 = FMA.getOperand(1);
10536     SDValue FMAAcc = FMA.getOperand(2);
10537 
10538     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10539         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10540       return SDValue();
10541 
10542     FMAOp1 = FMAOp1.getOperand(0);
10543     FMAOp2 = FMAOp2.getOperand(0);
10544     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10545         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10546       return SDValue();
10547 
10548     SDValue Vec3 = FMAOp1.getOperand(0);
10549     SDValue Vec4 = FMAOp2.getOperand(0);
10550     SDValue Idx2 = FMAOp1.getOperand(1);
10551 
10552     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10553         // Idx1 and Idx2 cannot be the same.
10554         Idx1 == Idx2)
10555       return SDValue();
10556 
10557     if (Vec1 == Vec2 || Vec3 == Vec4)
10558       return SDValue();
10559 
10560     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10561       return SDValue();
10562 
10563     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10564         (Vec1 == Vec4 && Vec2 == Vec3)) {
10565       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10566                          DAG.getTargetConstant(0, SL, MVT::i1));
10567     }
10568   }
10569   return SDValue();
10570 }
10571 
performSetCCCombine(SDNode * N,DAGCombinerInfo & DCI) const10572 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10573                                               DAGCombinerInfo &DCI) const {
10574   SelectionDAG &DAG = DCI.DAG;
10575   SDLoc SL(N);
10576 
10577   SDValue LHS = N->getOperand(0);
10578   SDValue RHS = N->getOperand(1);
10579   EVT VT = LHS.getValueType();
10580   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10581 
10582   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10583   if (!CRHS) {
10584     CRHS = dyn_cast<ConstantSDNode>(LHS);
10585     if (CRHS) {
10586       std::swap(LHS, RHS);
10587       CC = getSetCCSwappedOperands(CC);
10588     }
10589   }
10590 
10591   if (CRHS) {
10592     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10593         isBoolSGPR(LHS.getOperand(0))) {
10594       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10595       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10596       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10597       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10598       if ((CRHS->isAllOnesValue() &&
10599            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10600           (CRHS->isNullValue() &&
10601            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10602         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10603                            DAG.getConstant(-1, SL, MVT::i1));
10604       if ((CRHS->isAllOnesValue() &&
10605            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10606           (CRHS->isNullValue() &&
10607            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10608         return LHS.getOperand(0);
10609     }
10610 
10611     uint64_t CRHSVal = CRHS->getZExtValue();
10612     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10613         LHS.getOpcode() == ISD::SELECT &&
10614         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10615         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10616         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10617         isBoolSGPR(LHS.getOperand(0))) {
10618       // Given CT != FT:
10619       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10620       // setcc (select cc, CT, CF), CF, ne => cc
10621       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10622       // setcc (select cc, CT, CF), CT, eq => cc
10623       uint64_t CT = LHS.getConstantOperandVal(1);
10624       uint64_t CF = LHS.getConstantOperandVal(2);
10625 
10626       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10627           (CT == CRHSVal && CC == ISD::SETNE))
10628         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10629                            DAG.getConstant(-1, SL, MVT::i1));
10630       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10631           (CT == CRHSVal && CC == ISD::SETEQ))
10632         return LHS.getOperand(0);
10633     }
10634   }
10635 
10636   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10637                                            VT != MVT::f16))
10638     return SDValue();
10639 
10640   // Match isinf/isfinite pattern
10641   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10642   // (fcmp one (fabs x), inf) -> (fp_class x,
10643   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10644   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10645     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10646     if (!CRHS)
10647       return SDValue();
10648 
10649     const APFloat &APF = CRHS->getValueAPF();
10650     if (APF.isInfinity() && !APF.isNegative()) {
10651       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10652                                  SIInstrFlags::N_INFINITY;
10653       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10654                                     SIInstrFlags::P_ZERO |
10655                                     SIInstrFlags::N_NORMAL |
10656                                     SIInstrFlags::P_NORMAL |
10657                                     SIInstrFlags::N_SUBNORMAL |
10658                                     SIInstrFlags::P_SUBNORMAL;
10659       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10660       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10661                          DAG.getConstant(Mask, SL, MVT::i32));
10662     }
10663   }
10664 
10665   return SDValue();
10666 }
10667 
performCvtF32UByteNCombine(SDNode * N,DAGCombinerInfo & DCI) const10668 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10669                                                      DAGCombinerInfo &DCI) const {
10670   SelectionDAG &DAG = DCI.DAG;
10671   SDLoc SL(N);
10672   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10673 
10674   SDValue Src = N->getOperand(0);
10675   SDValue Shift = N->getOperand(0);
10676 
10677   // TODO: Extend type shouldn't matter (assuming legal types).
10678   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10679     Shift = Shift.getOperand(0);
10680 
10681   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10682     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10683     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10684     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10685     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10686     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10687     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10688       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10689                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10690 
10691       unsigned ShiftOffset = 8 * Offset;
10692       if (Shift.getOpcode() == ISD::SHL)
10693         ShiftOffset -= C->getZExtValue();
10694       else
10695         ShiftOffset += C->getZExtValue();
10696 
10697       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10698         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10699                            MVT::f32, Shift);
10700       }
10701     }
10702   }
10703 
10704   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10705   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10706   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10707     // We simplified Src. If this node is not dead, visit it again so it is
10708     // folded properly.
10709     if (N->getOpcode() != ISD::DELETED_NODE)
10710       DCI.AddToWorklist(N);
10711     return SDValue(N, 0);
10712   }
10713 
10714   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10715   if (SDValue DemandedSrc =
10716           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10717     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10718 
10719   return SDValue();
10720 }
10721 
performClampCombine(SDNode * N,DAGCombinerInfo & DCI) const10722 SDValue SITargetLowering::performClampCombine(SDNode *N,
10723                                               DAGCombinerInfo &DCI) const {
10724   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10725   if (!CSrc)
10726     return SDValue();
10727 
10728   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10729   const APFloat &F = CSrc->getValueAPF();
10730   APFloat Zero = APFloat::getZero(F.getSemantics());
10731   if (F < Zero ||
10732       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10733     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10734   }
10735 
10736   APFloat One(F.getSemantics(), "1.0");
10737   if (F > One)
10738     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10739 
10740   return SDValue(CSrc, 0);
10741 }
10742 
10743 
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const10744 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10745                                             DAGCombinerInfo &DCI) const {
10746   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10747     return SDValue();
10748   switch (N->getOpcode()) {
10749   case ISD::ADD:
10750     return performAddCombine(N, DCI);
10751   case ISD::SUB:
10752     return performSubCombine(N, DCI);
10753   case ISD::ADDCARRY:
10754   case ISD::SUBCARRY:
10755     return performAddCarrySubCarryCombine(N, DCI);
10756   case ISD::FADD:
10757     return performFAddCombine(N, DCI);
10758   case ISD::FSUB:
10759     return performFSubCombine(N, DCI);
10760   case ISD::SETCC:
10761     return performSetCCCombine(N, DCI);
10762   case ISD::FMAXNUM:
10763   case ISD::FMINNUM:
10764   case ISD::FMAXNUM_IEEE:
10765   case ISD::FMINNUM_IEEE:
10766   case ISD::SMAX:
10767   case ISD::SMIN:
10768   case ISD::UMAX:
10769   case ISD::UMIN:
10770   case AMDGPUISD::FMIN_LEGACY:
10771   case AMDGPUISD::FMAX_LEGACY:
10772     return performMinMaxCombine(N, DCI);
10773   case ISD::FMA:
10774     return performFMACombine(N, DCI);
10775   case ISD::AND:
10776     return performAndCombine(N, DCI);
10777   case ISD::OR:
10778     return performOrCombine(N, DCI);
10779   case ISD::XOR:
10780     return performXorCombine(N, DCI);
10781   case ISD::ZERO_EXTEND:
10782     return performZeroExtendCombine(N, DCI);
10783   case ISD::SIGN_EXTEND_INREG:
10784     return performSignExtendInRegCombine(N , DCI);
10785   case AMDGPUISD::FP_CLASS:
10786     return performClassCombine(N, DCI);
10787   case ISD::FCANONICALIZE:
10788     return performFCanonicalizeCombine(N, DCI);
10789   case AMDGPUISD::RCP:
10790     return performRcpCombine(N, DCI);
10791   case AMDGPUISD::FRACT:
10792   case AMDGPUISD::RSQ:
10793   case AMDGPUISD::RCP_LEGACY:
10794   case AMDGPUISD::RCP_IFLAG:
10795   case AMDGPUISD::RSQ_CLAMP:
10796   case AMDGPUISD::LDEXP: {
10797     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10798     SDValue Src = N->getOperand(0);
10799     if (Src.isUndef())
10800       return Src;
10801     break;
10802   }
10803   case ISD::SINT_TO_FP:
10804   case ISD::UINT_TO_FP:
10805     return performUCharToFloatCombine(N, DCI);
10806   case AMDGPUISD::CVT_F32_UBYTE0:
10807   case AMDGPUISD::CVT_F32_UBYTE1:
10808   case AMDGPUISD::CVT_F32_UBYTE2:
10809   case AMDGPUISD::CVT_F32_UBYTE3:
10810     return performCvtF32UByteNCombine(N, DCI);
10811   case AMDGPUISD::FMED3:
10812     return performFMed3Combine(N, DCI);
10813   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10814     return performCvtPkRTZCombine(N, DCI);
10815   case AMDGPUISD::CLAMP:
10816     return performClampCombine(N, DCI);
10817   case ISD::SCALAR_TO_VECTOR: {
10818     SelectionDAG &DAG = DCI.DAG;
10819     EVT VT = N->getValueType(0);
10820 
10821     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10822     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10823       SDLoc SL(N);
10824       SDValue Src = N->getOperand(0);
10825       EVT EltVT = Src.getValueType();
10826       if (EltVT == MVT::f16)
10827         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10828 
10829       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10830       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10831     }
10832 
10833     break;
10834   }
10835   case ISD::EXTRACT_VECTOR_ELT:
10836     return performExtractVectorEltCombine(N, DCI);
10837   case ISD::INSERT_VECTOR_ELT:
10838     return performInsertVectorEltCombine(N, DCI);
10839   case ISD::LOAD: {
10840     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10841       return Widended;
10842     LLVM_FALLTHROUGH;
10843   }
10844   default: {
10845     if (!DCI.isBeforeLegalize()) {
10846       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10847         return performMemSDNodeCombine(MemNode, DCI);
10848     }
10849 
10850     break;
10851   }
10852   }
10853 
10854   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10855 }
10856 
10857 /// Helper function for adjustWritemask
SubIdx2Lane(unsigned Idx)10858 static unsigned SubIdx2Lane(unsigned Idx) {
10859   switch (Idx) {
10860   default: return 0;
10861   case AMDGPU::sub0: return 0;
10862   case AMDGPU::sub1: return 1;
10863   case AMDGPU::sub2: return 2;
10864   case AMDGPU::sub3: return 3;
10865   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10866   }
10867 }
10868 
10869 /// Adjust the writemask of MIMG instructions
adjustWritemask(MachineSDNode * & Node,SelectionDAG & DAG) const10870 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10871                                           SelectionDAG &DAG) const {
10872   unsigned Opcode = Node->getMachineOpcode();
10873 
10874   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10875   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10876   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10877     return Node; // not implemented for D16
10878 
10879   SDNode *Users[5] = { nullptr };
10880   unsigned Lane = 0;
10881   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10882   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10883   unsigned NewDmask = 0;
10884   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10885   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10886   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10887                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10888   unsigned TFCLane = 0;
10889   bool HasChain = Node->getNumValues() > 1;
10890 
10891   if (OldDmask == 0) {
10892     // These are folded out, but on the chance it happens don't assert.
10893     return Node;
10894   }
10895 
10896   unsigned OldBitsSet = countPopulation(OldDmask);
10897   // Work out which is the TFE/LWE lane if that is enabled.
10898   if (UsesTFC) {
10899     TFCLane = OldBitsSet;
10900   }
10901 
10902   // Try to figure out the used register components
10903   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10904        I != E; ++I) {
10905 
10906     // Don't look at users of the chain.
10907     if (I.getUse().getResNo() != 0)
10908       continue;
10909 
10910     // Abort if we can't understand the usage
10911     if (!I->isMachineOpcode() ||
10912         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10913       return Node;
10914 
10915     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10916     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10917     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10918     // set, etc.
10919     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10920 
10921     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10922     if (UsesTFC && Lane == TFCLane) {
10923       Users[Lane] = *I;
10924     } else {
10925       // Set which texture component corresponds to the lane.
10926       unsigned Comp;
10927       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10928         Comp = countTrailingZeros(Dmask);
10929         Dmask &= ~(1 << Comp);
10930       }
10931 
10932       // Abort if we have more than one user per component.
10933       if (Users[Lane])
10934         return Node;
10935 
10936       Users[Lane] = *I;
10937       NewDmask |= 1 << Comp;
10938     }
10939   }
10940 
10941   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10942   bool NoChannels = !NewDmask;
10943   if (NoChannels) {
10944     if (!UsesTFC) {
10945       // No uses of the result and not using TFC. Then do nothing.
10946       return Node;
10947     }
10948     // If the original dmask has one channel - then nothing to do
10949     if (OldBitsSet == 1)
10950       return Node;
10951     // Use an arbitrary dmask - required for the instruction to work
10952     NewDmask = 1;
10953   }
10954   // Abort if there's no change
10955   if (NewDmask == OldDmask)
10956     return Node;
10957 
10958   unsigned BitsSet = countPopulation(NewDmask);
10959 
10960   // Check for TFE or LWE - increase the number of channels by one to account
10961   // for the extra return value
10962   // This will need adjustment for D16 if this is also included in
10963   // adjustWriteMask (this function) but at present D16 are excluded.
10964   unsigned NewChannels = BitsSet + UsesTFC;
10965 
10966   int NewOpcode =
10967       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10968   assert(NewOpcode != -1 &&
10969          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10970          "failed to find equivalent MIMG op");
10971 
10972   // Adjust the writemask in the node
10973   SmallVector<SDValue, 12> Ops;
10974   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10975   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10976   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10977 
10978   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10979 
10980   MVT ResultVT = NewChannels == 1 ?
10981     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10982                            NewChannels == 5 ? 8 : NewChannels);
10983   SDVTList NewVTList = HasChain ?
10984     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10985 
10986 
10987   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10988                                               NewVTList, Ops);
10989 
10990   if (HasChain) {
10991     // Update chain.
10992     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10993     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10994   }
10995 
10996   if (NewChannels == 1) {
10997     assert(Node->hasNUsesOfValue(1, 0));
10998     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10999                                       SDLoc(Node), Users[Lane]->getValueType(0),
11000                                       SDValue(NewNode, 0));
11001     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11002     return nullptr;
11003   }
11004 
11005   // Update the users of the node with the new indices
11006   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11007     SDNode *User = Users[i];
11008     if (!User) {
11009       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11010       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11011       if (i || !NoChannels)
11012         continue;
11013     } else {
11014       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11015       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11016     }
11017 
11018     switch (Idx) {
11019     default: break;
11020     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11021     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11022     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11023     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11024     }
11025   }
11026 
11027   DAG.RemoveDeadNode(Node);
11028   return nullptr;
11029 }
11030 
isFrameIndexOp(SDValue Op)11031 static bool isFrameIndexOp(SDValue Op) {
11032   if (Op.getOpcode() == ISD::AssertZext)
11033     Op = Op.getOperand(0);
11034 
11035   return isa<FrameIndexSDNode>(Op);
11036 }
11037 
11038 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11039 /// with frame index operands.
11040 /// LLVM assumes that inputs are to these instructions are registers.
legalizeTargetIndependentNode(SDNode * Node,SelectionDAG & DAG) const11041 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11042                                                         SelectionDAG &DAG) const {
11043   if (Node->getOpcode() == ISD::CopyToReg) {
11044     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11045     SDValue SrcVal = Node->getOperand(2);
11046 
11047     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11048     // to try understanding copies to physical registers.
11049     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11050       SDLoc SL(Node);
11051       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11052       SDValue VReg = DAG.getRegister(
11053         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11054 
11055       SDNode *Glued = Node->getGluedNode();
11056       SDValue ToVReg
11057         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11058                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11059       SDValue ToResultReg
11060         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11061                            VReg, ToVReg.getValue(1));
11062       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11063       DAG.RemoveDeadNode(Node);
11064       return ToResultReg.getNode();
11065     }
11066   }
11067 
11068   SmallVector<SDValue, 8> Ops;
11069   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11070     if (!isFrameIndexOp(Node->getOperand(i))) {
11071       Ops.push_back(Node->getOperand(i));
11072       continue;
11073     }
11074 
11075     SDLoc DL(Node);
11076     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11077                                      Node->getOperand(i).getValueType(),
11078                                      Node->getOperand(i)), 0));
11079   }
11080 
11081   return DAG.UpdateNodeOperands(Node, Ops);
11082 }
11083 
11084 /// Fold the instructions after selecting them.
11085 /// Returns null if users were already updated.
PostISelFolding(MachineSDNode * Node,SelectionDAG & DAG) const11086 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11087                                           SelectionDAG &DAG) const {
11088   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11089   unsigned Opcode = Node->getMachineOpcode();
11090 
11091   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11092       !TII->isGather4(Opcode) &&
11093       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11094     return adjustWritemask(Node, DAG);
11095   }
11096 
11097   if (Opcode == AMDGPU::INSERT_SUBREG ||
11098       Opcode == AMDGPU::REG_SEQUENCE) {
11099     legalizeTargetIndependentNode(Node, DAG);
11100     return Node;
11101   }
11102 
11103   switch (Opcode) {
11104   case AMDGPU::V_DIV_SCALE_F32:
11105   case AMDGPU::V_DIV_SCALE_F64: {
11106     // Satisfy the operand register constraint when one of the inputs is
11107     // undefined. Ordinarily each undef value will have its own implicit_def of
11108     // a vreg, so force these to use a single register.
11109     SDValue Src0 = Node->getOperand(1);
11110     SDValue Src1 = Node->getOperand(3);
11111     SDValue Src2 = Node->getOperand(5);
11112 
11113     if ((Src0.isMachineOpcode() &&
11114          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11115         (Src0 == Src1 || Src0 == Src2))
11116       break;
11117 
11118     MVT VT = Src0.getValueType().getSimpleVT();
11119     const TargetRegisterClass *RC =
11120         getRegClassFor(VT, Src0.getNode()->isDivergent());
11121 
11122     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11123     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11124 
11125     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11126                                       UndefReg, Src0, SDValue());
11127 
11128     // src0 must be the same register as src1 or src2, even if the value is
11129     // undefined, so make sure we don't violate this constraint.
11130     if (Src0.isMachineOpcode() &&
11131         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11132       if (Src1.isMachineOpcode() &&
11133           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11134         Src0 = Src1;
11135       else if (Src2.isMachineOpcode() &&
11136                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11137         Src0 = Src2;
11138       else {
11139         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11140         Src0 = UndefReg;
11141         Src1 = UndefReg;
11142       }
11143     } else
11144       break;
11145 
11146     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11147     Ops[1] = Src0;
11148     Ops[3] = Src1;
11149     Ops[5] = Src2;
11150     Ops.push_back(ImpDef.getValue(1));
11151     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11152   }
11153   default:
11154     break;
11155   }
11156 
11157   return Node;
11158 }
11159 
11160 /// Assign the register class depending on the number of
11161 /// bits set in the writemask
AdjustInstrPostInstrSelection(MachineInstr & MI,SDNode * Node) const11162 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11163                                                      SDNode *Node) const {
11164   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11165 
11166   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11167 
11168   if (TII->isVOP3(MI.getOpcode())) {
11169     // Make sure constant bus requirements are respected.
11170     TII->legalizeOperandsVOP3(MRI, MI);
11171 
11172     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11173     // This saves a chain-copy of registers and better ballance register
11174     // use between vgpr and agpr as agpr tuples tend to be big.
11175     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11176       unsigned Opc = MI.getOpcode();
11177       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11178       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11179                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11180         if (I == -1)
11181           break;
11182         MachineOperand &Op = MI.getOperand(I);
11183         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11184              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11185             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11186           continue;
11187         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11188         if (!Src || !Src->isCopy() ||
11189             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11190           continue;
11191         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11192         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11193         // All uses of agpr64 and agpr32 can also accept vgpr except for
11194         // v_accvgpr_read, but we do not produce agpr reads during selection,
11195         // so no use checks are needed.
11196         MRI.setRegClass(Op.getReg(), NewRC);
11197       }
11198     }
11199 
11200     return;
11201   }
11202 
11203   // Replace unused atomics with the no return version.
11204   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11205   if (NoRetAtomicOp != -1) {
11206     if (!Node->hasAnyUseOfValue(0)) {
11207       int Glc1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11208                                                AMDGPU::OpName::glc1);
11209       if (Glc1Idx != -1)
11210         MI.RemoveOperand(Glc1Idx);
11211       MI.RemoveOperand(0);
11212       MI.setDesc(TII->get(NoRetAtomicOp));
11213       return;
11214     }
11215 
11216     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11217     // instruction, because the return type of these instructions is a vec2 of
11218     // the memory type, so it can be tied to the input operand.
11219     // This means these instructions always have a use, so we need to add a
11220     // special case to check if the atomic has only one extract_subreg use,
11221     // which itself has no uses.
11222     if ((Node->hasNUsesOfValue(1, 0) &&
11223          Node->use_begin()->isMachineOpcode() &&
11224          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11225          !Node->use_begin()->hasAnyUseOfValue(0))) {
11226       Register Def = MI.getOperand(0).getReg();
11227 
11228       // Change this into a noret atomic.
11229       MI.setDesc(TII->get(NoRetAtomicOp));
11230       MI.RemoveOperand(0);
11231 
11232       // If we only remove the def operand from the atomic instruction, the
11233       // extract_subreg will be left with a use of a vreg without a def.
11234       // So we need to insert an implicit_def to avoid machine verifier
11235       // errors.
11236       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11237               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11238     }
11239     return;
11240   }
11241 }
11242 
buildSMovImm32(SelectionDAG & DAG,const SDLoc & DL,uint64_t Val)11243 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11244                               uint64_t Val) {
11245   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11246   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11247 }
11248 
wrapAddr64Rsrc(SelectionDAG & DAG,const SDLoc & DL,SDValue Ptr) const11249 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11250                                                 const SDLoc &DL,
11251                                                 SDValue Ptr) const {
11252   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11253 
11254   // Build the half of the subregister with the constants before building the
11255   // full 128-bit register. If we are building multiple resource descriptors,
11256   // this will allow CSEing of the 2-component register.
11257   const SDValue Ops0[] = {
11258     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11259     buildSMovImm32(DAG, DL, 0),
11260     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11261     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11262     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11263   };
11264 
11265   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11266                                                 MVT::v2i32, Ops0), 0);
11267 
11268   // Combine the constants and the pointer.
11269   const SDValue Ops1[] = {
11270     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11271     Ptr,
11272     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11273     SubRegHi,
11274     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11275   };
11276 
11277   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11278 }
11279 
11280 /// Return a resource descriptor with the 'Add TID' bit enabled
11281 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11282 ///        of the resource descriptor) to create an offset, which is added to
11283 ///        the resource pointer.
buildRSRC(SelectionDAG & DAG,const SDLoc & DL,SDValue Ptr,uint32_t RsrcDword1,uint64_t RsrcDword2And3) const11284 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11285                                            SDValue Ptr, uint32_t RsrcDword1,
11286                                            uint64_t RsrcDword2And3) const {
11287   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11288   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11289   if (RsrcDword1) {
11290     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11291                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11292                     0);
11293   }
11294 
11295   SDValue DataLo = buildSMovImm32(DAG, DL,
11296                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11297   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11298 
11299   const SDValue Ops[] = {
11300     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11301     PtrLo,
11302     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11303     PtrHi,
11304     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11305     DataLo,
11306     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11307     DataHi,
11308     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11309   };
11310 
11311   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11312 }
11313 
11314 //===----------------------------------------------------------------------===//
11315 //                         SI Inline Assembly Support
11316 //===----------------------------------------------------------------------===//
11317 
11318 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const11319 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11320                                                StringRef Constraint,
11321                                                MVT VT) const {
11322   const TargetRegisterClass *RC = nullptr;
11323   if (Constraint.size() == 1) {
11324     const unsigned BitWidth = VT.getSizeInBits();
11325     switch (Constraint[0]) {
11326     default:
11327       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11328     case 's':
11329     case 'r':
11330       switch (BitWidth) {
11331       case 16:
11332         RC = &AMDGPU::SReg_32RegClass;
11333         break;
11334       case 64:
11335         RC = &AMDGPU::SGPR_64RegClass;
11336         break;
11337       default:
11338         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11339         if (!RC)
11340           return std::make_pair(0U, nullptr);
11341         break;
11342       }
11343       break;
11344     case 'v':
11345       switch (BitWidth) {
11346       case 16:
11347         RC = &AMDGPU::VGPR_32RegClass;
11348         break;
11349       default:
11350         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11351         if (!RC)
11352           return std::make_pair(0U, nullptr);
11353         break;
11354       }
11355       break;
11356     case 'a':
11357       if (!Subtarget->hasMAIInsts())
11358         break;
11359       switch (BitWidth) {
11360       case 16:
11361         RC = &AMDGPU::AGPR_32RegClass;
11362         break;
11363       default:
11364         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11365         if (!RC)
11366           return std::make_pair(0U, nullptr);
11367         break;
11368       }
11369       break;
11370     }
11371     // We actually support i128, i16 and f16 as inline parameters
11372     // even if they are not reported as legal
11373     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11374                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11375       return std::make_pair(0U, RC);
11376   }
11377 
11378   if (Constraint.size() > 1) {
11379     if (Constraint[1] == 'v') {
11380       RC = &AMDGPU::VGPR_32RegClass;
11381     } else if (Constraint[1] == 's') {
11382       RC = &AMDGPU::SGPR_32RegClass;
11383     } else if (Constraint[1] == 'a') {
11384       RC = &AMDGPU::AGPR_32RegClass;
11385     }
11386 
11387     if (RC) {
11388       uint32_t Idx;
11389       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11390       if (!Failed && Idx < RC->getNumRegs())
11391         return std::make_pair(RC->getRegister(Idx), RC);
11392     }
11393   }
11394 
11395   // FIXME: Returns VS_32 for physical SGPR constraints
11396   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11397 }
11398 
isImmConstraint(StringRef Constraint)11399 static bool isImmConstraint(StringRef Constraint) {
11400   if (Constraint.size() == 1) {
11401     switch (Constraint[0]) {
11402     default: break;
11403     case 'I':
11404     case 'J':
11405     case 'A':
11406     case 'B':
11407     case 'C':
11408       return true;
11409     }
11410   } else if (Constraint == "DA" ||
11411              Constraint == "DB") {
11412     return true;
11413   }
11414   return false;
11415 }
11416 
11417 SITargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const11418 SITargetLowering::getConstraintType(StringRef Constraint) const {
11419   if (Constraint.size() == 1) {
11420     switch (Constraint[0]) {
11421     default: break;
11422     case 's':
11423     case 'v':
11424     case 'a':
11425       return C_RegisterClass;
11426     }
11427   }
11428   if (isImmConstraint(Constraint)) {
11429     return C_Other;
11430   }
11431   return TargetLowering::getConstraintType(Constraint);
11432 }
11433 
clearUnusedBits(uint64_t Val,unsigned Size)11434 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11435   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11436     Val = Val & maskTrailingOnes<uint64_t>(Size);
11437   }
11438   return Val;
11439 }
11440 
LowerAsmOperandForConstraint(SDValue Op,std::string & Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const11441 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11442                                                     std::string &Constraint,
11443                                                     std::vector<SDValue> &Ops,
11444                                                     SelectionDAG &DAG) const {
11445   if (isImmConstraint(Constraint)) {
11446     uint64_t Val;
11447     if (getAsmOperandConstVal(Op, Val) &&
11448         checkAsmConstraintVal(Op, Constraint, Val)) {
11449       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11450       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11451     }
11452   } else {
11453     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11454   }
11455 }
11456 
getAsmOperandConstVal(SDValue Op,uint64_t & Val) const11457 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11458   unsigned Size = Op.getScalarValueSizeInBits();
11459   if (Size > 64)
11460     return false;
11461 
11462   if (Size == 16 && !Subtarget->has16BitInsts())
11463     return false;
11464 
11465   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11466     Val = C->getSExtValue();
11467     return true;
11468   }
11469   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11470     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11471     return true;
11472   }
11473   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11474     if (Size != 16 || Op.getNumOperands() != 2)
11475       return false;
11476     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11477       return false;
11478     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11479       Val = C->getSExtValue();
11480       return true;
11481     }
11482     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11483       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11484       return true;
11485     }
11486   }
11487 
11488   return false;
11489 }
11490 
checkAsmConstraintVal(SDValue Op,const std::string & Constraint,uint64_t Val) const11491 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11492                                              const std::string &Constraint,
11493                                              uint64_t Val) const {
11494   if (Constraint.size() == 1) {
11495     switch (Constraint[0]) {
11496     case 'I':
11497       return AMDGPU::isInlinableIntLiteral(Val);
11498     case 'J':
11499       return isInt<16>(Val);
11500     case 'A':
11501       return checkAsmConstraintValA(Op, Val);
11502     case 'B':
11503       return isInt<32>(Val);
11504     case 'C':
11505       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11506              AMDGPU::isInlinableIntLiteral(Val);
11507     default:
11508       break;
11509     }
11510   } else if (Constraint.size() == 2) {
11511     if (Constraint == "DA") {
11512       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11513       int64_t LoBits = static_cast<int32_t>(Val);
11514       return checkAsmConstraintValA(Op, HiBits, 32) &&
11515              checkAsmConstraintValA(Op, LoBits, 32);
11516     }
11517     if (Constraint == "DB") {
11518       return true;
11519     }
11520   }
11521   llvm_unreachable("Invalid asm constraint");
11522 }
11523 
checkAsmConstraintValA(SDValue Op,uint64_t Val,unsigned MaxSize) const11524 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11525                                               uint64_t Val,
11526                                               unsigned MaxSize) const {
11527   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11528   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11529   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11530       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11531       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11532     return true;
11533   }
11534   return false;
11535 }
11536 
11537 // Figure out which registers should be reserved for stack access. Only after
11538 // the function is legalized do we know all of the non-spill stack objects or if
11539 // calls are present.
finalizeLowering(MachineFunction & MF) const11540 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11541   MachineRegisterInfo &MRI = MF.getRegInfo();
11542   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11543   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11544   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11545 
11546   if (Info->isEntryFunction()) {
11547     // Callable functions have fixed registers used for stack access.
11548     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11549   }
11550 
11551   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11552                              Info->getStackPtrOffsetReg()));
11553   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11554     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11555 
11556   // We need to worry about replacing the default register with itself in case
11557   // of MIR testcases missing the MFI.
11558   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11559     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11560 
11561   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11562     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11563 
11564   Info->limitOccupancy(MF);
11565 
11566   if (ST.isWave32() && !MF.empty()) {
11567     const SIInstrInfo *TII = ST.getInstrInfo();
11568     for (auto &MBB : MF) {
11569       for (auto &MI : MBB) {
11570         TII->fixImplicitOperands(MI);
11571       }
11572     }
11573   }
11574 
11575   TargetLoweringBase::finalizeLowering(MF);
11576 
11577   // Allocate a VGPR for future SGPR Spill if
11578   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11579   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11580   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11581       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11582     Info->reserveVGPRforSGPRSpills(MF);
11583 }
11584 
computeKnownBitsForFrameIndex(const int FI,KnownBits & Known,const MachineFunction & MF) const11585 void SITargetLowering::computeKnownBitsForFrameIndex(
11586   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11587   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11588 
11589   // Set the high bits to zero based on the maximum allowed scratch size per
11590   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11591   // calculation won't overflow, so assume the sign bit is never set.
11592   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11593 }
11594 
knownBitsForWorkitemID(const GCNSubtarget & ST,GISelKnownBits & KB,KnownBits & Known,unsigned Dim)11595 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11596                                    KnownBits &Known, unsigned Dim) {
11597   unsigned MaxValue =
11598       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11599   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11600 }
11601 
computeKnownBitsForTargetInstr(GISelKnownBits & KB,Register R,KnownBits & Known,const APInt & DemandedElts,const MachineRegisterInfo & MRI,unsigned Depth) const11602 void SITargetLowering::computeKnownBitsForTargetInstr(
11603     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11604     const MachineRegisterInfo &MRI, unsigned Depth) const {
11605   const MachineInstr *MI = MRI.getVRegDef(R);
11606   switch (MI->getOpcode()) {
11607   case AMDGPU::G_INTRINSIC: {
11608     switch (MI->getIntrinsicID()) {
11609     case Intrinsic::amdgcn_workitem_id_x:
11610       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11611       break;
11612     case Intrinsic::amdgcn_workitem_id_y:
11613       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11614       break;
11615     case Intrinsic::amdgcn_workitem_id_z:
11616       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11617       break;
11618     case Intrinsic::amdgcn_mbcnt_lo:
11619     case Intrinsic::amdgcn_mbcnt_hi: {
11620       // These return at most the wavefront size - 1.
11621       unsigned Size = MRI.getType(R).getSizeInBits();
11622       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11623       break;
11624     }
11625     case Intrinsic::amdgcn_groupstaticsize: {
11626       // We can report everything over the maximum size as 0. We can't report
11627       // based on the actual size because we don't know if it's accurate or not
11628       // at any given point.
11629       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11630       break;
11631     }
11632     }
11633     break;
11634   }
11635   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11636     Known.Zero.setHighBits(24);
11637     break;
11638   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11639     Known.Zero.setHighBits(16);
11640     break;
11641   }
11642 }
11643 
computeKnownAlignForTargetInstr(GISelKnownBits & KB,Register R,const MachineRegisterInfo & MRI,unsigned Depth) const11644 Align SITargetLowering::computeKnownAlignForTargetInstr(
11645   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11646   unsigned Depth) const {
11647   const MachineInstr *MI = MRI.getVRegDef(R);
11648   switch (MI->getOpcode()) {
11649   case AMDGPU::G_INTRINSIC:
11650   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11651     // FIXME: Can this move to generic code? What about the case where the call
11652     // site specifies a lower alignment?
11653     Intrinsic::ID IID = MI->getIntrinsicID();
11654     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11655     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11656     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11657       return *RetAlign;
11658     return Align(1);
11659   }
11660   default:
11661     return Align(1);
11662   }
11663 }
11664 
getPrefLoopAlignment(MachineLoop * ML) const11665 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11666   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11667   const Align CacheLineAlign = Align(64);
11668 
11669   // Pre-GFX10 target did not benefit from loop alignment
11670   if (!ML || DisableLoopAlignment ||
11671       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11672       getSubtarget()->hasInstFwdPrefetchBug())
11673     return PrefAlign;
11674 
11675   // On GFX10 I$ is 4 x 64 bytes cache lines.
11676   // By default prefetcher keeps one cache line behind and reads two ahead.
11677   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11678   // behind and one ahead.
11679   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11680   // If loop fits 64 bytes it always spans no more than two cache lines and
11681   // does not need an alignment.
11682   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11683   // Else if loop is less or equal 192 bytes we need two lines behind.
11684 
11685   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11686   const MachineBasicBlock *Header = ML->getHeader();
11687   if (Header->getAlignment() != PrefAlign)
11688     return Header->getAlignment(); // Already processed.
11689 
11690   unsigned LoopSize = 0;
11691   for (const MachineBasicBlock *MBB : ML->blocks()) {
11692     // If inner loop block is aligned assume in average half of the alignment
11693     // size to be added as nops.
11694     if (MBB != Header)
11695       LoopSize += MBB->getAlignment().value() / 2;
11696 
11697     for (const MachineInstr &MI : *MBB) {
11698       LoopSize += TII->getInstSizeInBytes(MI);
11699       if (LoopSize > 192)
11700         return PrefAlign;
11701     }
11702   }
11703 
11704   if (LoopSize <= 64)
11705     return PrefAlign;
11706 
11707   if (LoopSize <= 128)
11708     return CacheLineAlign;
11709 
11710   // If any of parent loops is surrounded by prefetch instructions do not
11711   // insert new for inner loop, which would reset parent's settings.
11712   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11713     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11714       auto I = Exit->getFirstNonDebugInstr();
11715       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11716         return CacheLineAlign;
11717     }
11718   }
11719 
11720   MachineBasicBlock *Pre = ML->getLoopPreheader();
11721   MachineBasicBlock *Exit = ML->getExitBlock();
11722 
11723   if (Pre && Exit) {
11724     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11725             TII->get(AMDGPU::S_INST_PREFETCH))
11726       .addImm(1); // prefetch 2 lines behind PC
11727 
11728     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11729             TII->get(AMDGPU::S_INST_PREFETCH))
11730       .addImm(2); // prefetch 1 line behind PC
11731   }
11732 
11733   return CacheLineAlign;
11734 }
11735 
11736 LLVM_ATTRIBUTE_UNUSED
isCopyFromRegOfInlineAsm(const SDNode * N)11737 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11738   assert(N->getOpcode() == ISD::CopyFromReg);
11739   do {
11740     // Follow the chain until we find an INLINEASM node.
11741     N = N->getOperand(0).getNode();
11742     if (N->getOpcode() == ISD::INLINEASM ||
11743         N->getOpcode() == ISD::INLINEASM_BR)
11744       return true;
11745   } while (N->getOpcode() == ISD::CopyFromReg);
11746   return false;
11747 }
11748 
isSDNodeSourceOfDivergence(const SDNode * N,FunctionLoweringInfo * FLI,LegacyDivergenceAnalysis * KDA) const11749 bool SITargetLowering::isSDNodeSourceOfDivergence(
11750     const SDNode *N, FunctionLoweringInfo *FLI,
11751     LegacyDivergenceAnalysis *KDA) const {
11752   switch (N->getOpcode()) {
11753   case ISD::CopyFromReg: {
11754     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11755     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11756     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11757     Register Reg = R->getReg();
11758 
11759     // FIXME: Why does this need to consider isLiveIn?
11760     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11761       return !TRI->isSGPRReg(MRI, Reg);
11762 
11763     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11764       return KDA->isDivergent(V);
11765 
11766     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11767     return !TRI->isSGPRReg(MRI, Reg);
11768   }
11769   case ISD::LOAD: {
11770     const LoadSDNode *L = cast<LoadSDNode>(N);
11771     unsigned AS = L->getAddressSpace();
11772     // A flat load may access private memory.
11773     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11774   }
11775   case ISD::CALLSEQ_END:
11776     return true;
11777   case ISD::INTRINSIC_WO_CHAIN:
11778     return AMDGPU::isIntrinsicSourceOfDivergence(
11779         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11780   case ISD::INTRINSIC_W_CHAIN:
11781     return AMDGPU::isIntrinsicSourceOfDivergence(
11782         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11783   }
11784   return false;
11785 }
11786 
denormalsEnabledForType(const SelectionDAG & DAG,EVT VT) const11787 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11788                                                EVT VT) const {
11789   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11790   case MVT::f32:
11791     return hasFP32Denormals(DAG.getMachineFunction());
11792   case MVT::f64:
11793   case MVT::f16:
11794     return hasFP64FP16Denormals(DAG.getMachineFunction());
11795   default:
11796     return false;
11797   }
11798 }
11799 
isKnownNeverNaNForTargetNode(SDValue Op,const SelectionDAG & DAG,bool SNaN,unsigned Depth) const11800 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11801                                                     const SelectionDAG &DAG,
11802                                                     bool SNaN,
11803                                                     unsigned Depth) const {
11804   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11805     const MachineFunction &MF = DAG.getMachineFunction();
11806     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11807 
11808     if (Info->getMode().DX10Clamp)
11809       return true; // Clamped to 0.
11810     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11811   }
11812 
11813   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11814                                                             SNaN, Depth);
11815 }
11816 
11817 // Global FP atomic instructions have a hardcoded FP mode and do not support
11818 // FP32 denormals, and only support v2f16 denormals.
fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst * RMW)11819 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
11820   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
11821   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
11822   if (&Flt == &APFloat::IEEEsingle())
11823     return DenormMode == DenormalMode::getPreserveSign();
11824   return DenormMode == DenormalMode::getIEEE();
11825 }
11826 
11827 TargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * RMW) const11828 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11829   switch (RMW->getOperation()) {
11830   case AtomicRMWInst::FAdd: {
11831     Type *Ty = RMW->getType();
11832 
11833     // We don't have a way to support 16-bit atomics now, so just leave them
11834     // as-is.
11835     if (Ty->isHalfTy())
11836       return AtomicExpansionKind::None;
11837 
11838     if (!Ty->isFloatTy())
11839       return AtomicExpansionKind::CmpXChg;
11840 
11841     // TODO: Do have these for flat. Older targets also had them for buffers.
11842     unsigned AS = RMW->getPointerAddressSpace();
11843 
11844     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11845       if (!fpModeMatchesGlobalFPAtomicMode(RMW))
11846         return AtomicExpansionKind::CmpXChg;
11847 
11848       return RMW->use_empty() ? AtomicExpansionKind::None :
11849                                 AtomicExpansionKind::CmpXChg;
11850     }
11851 
11852     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
11853     // to round-to-nearest-even.
11854     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11855       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11856   }
11857   default:
11858     break;
11859   }
11860 
11861   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11862 }
11863 
11864 const TargetRegisterClass *
getRegClassFor(MVT VT,bool isDivergent) const11865 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11866   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11867   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11868   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11869     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11870                                                : &AMDGPU::SReg_32RegClass;
11871   if (!TRI->isSGPRClass(RC) && !isDivergent)
11872     return TRI->getEquivalentSGPRClass(RC);
11873   else if (TRI->isSGPRClass(RC) && isDivergent)
11874     return TRI->getEquivalentVGPRClass(RC);
11875 
11876   return RC;
11877 }
11878 
11879 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11880 // uniform values (as produced by the mask results of control flow intrinsics)
11881 // used outside of divergent blocks. The phi users need to also be treated as
11882 // always uniform.
hasCFUser(const Value * V,SmallPtrSet<const Value *,16> & Visited,unsigned WaveSize)11883 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11884                       unsigned WaveSize) {
11885   // FIXME: We asssume we never cast the mask results of a control flow
11886   // intrinsic.
11887   // Early exit if the type won't be consistent as a compile time hack.
11888   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11889   if (!IT || IT->getBitWidth() != WaveSize)
11890     return false;
11891 
11892   if (!isa<Instruction>(V))
11893     return false;
11894   if (!Visited.insert(V).second)
11895     return false;
11896   bool Result = false;
11897   for (auto U : V->users()) {
11898     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11899       if (V == U->getOperand(1)) {
11900         switch (Intrinsic->getIntrinsicID()) {
11901         default:
11902           Result = false;
11903           break;
11904         case Intrinsic::amdgcn_if_break:
11905         case Intrinsic::amdgcn_if:
11906         case Intrinsic::amdgcn_else:
11907           Result = true;
11908           break;
11909         }
11910       }
11911       if (V == U->getOperand(0)) {
11912         switch (Intrinsic->getIntrinsicID()) {
11913         default:
11914           Result = false;
11915           break;
11916         case Intrinsic::amdgcn_end_cf:
11917         case Intrinsic::amdgcn_loop:
11918           Result = true;
11919           break;
11920         }
11921       }
11922     } else {
11923       Result = hasCFUser(U, Visited, WaveSize);
11924     }
11925     if (Result)
11926       break;
11927   }
11928   return Result;
11929 }
11930 
requiresUniformRegister(MachineFunction & MF,const Value * V) const11931 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11932                                                const Value *V) const {
11933   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11934     if (CI->isInlineAsm()) {
11935       // FIXME: This cannot give a correct answer. This should only trigger in
11936       // the case where inline asm returns mixed SGPR and VGPR results, used
11937       // outside the defining block. We don't have a specific result to
11938       // consider, so this assumes if any value is SGPR, the overall register
11939       // also needs to be SGPR.
11940       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11941       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11942           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11943       for (auto &TC : TargetConstraints) {
11944         if (TC.Type == InlineAsm::isOutput) {
11945           ComputeConstraintToUse(TC, SDValue());
11946           unsigned AssignedReg;
11947           const TargetRegisterClass *RC;
11948           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11949               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11950           if (RC) {
11951             MachineRegisterInfo &MRI = MF.getRegInfo();
11952             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11953               return true;
11954             else if (SIRI->isSGPRClass(RC))
11955               return true;
11956           }
11957         }
11958       }
11959     }
11960   }
11961   SmallPtrSet<const Value *, 16> Visited;
11962   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11963 }
11964 
11965 std::pair<int, MVT>
getTypeLegalizationCost(const DataLayout & DL,Type * Ty) const11966 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11967                                           Type *Ty) const {
11968   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11969   auto Size = DL.getTypeSizeInBits(Ty);
11970   // Maximum load or store can handle 8 dwords for scalar and 4 for
11971   // vector ALU. Let's assume anything above 8 dwords is expensive
11972   // even if legal.
11973   if (Size <= 256)
11974     return Cost;
11975 
11976   Cost.first = (Size + 255) / 256;
11977   return Cost;
11978 }
11979