blob: 25000506f2ccbacdef2a1232081da57a011e2dfc [file] [log] [blame]
Tom Stellard75aadc22012-12-11 21:25:42 +00001//===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Tom Stellard75aadc22012-12-11 21:25:42 +00006//
7//===----------------------------------------------------------------------===//
8//
9/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010/// Custom DAG lowering for SI
Tom Stellard75aadc22012-12-11 21:25:42 +000011//
12//===----------------------------------------------------------------------===//
13
Sylvestre Ledrudf92dab2018-11-02 17:25:40 +000014#if defined(_MSC_VER) || defined(__MINGW32__)
NAKAMURA Takumi45e0a832014-07-20 11:15:07 +000015// Provide M_PI.
16#define _USE_MATH_DEFINES
NAKAMURA Takumi45e0a832014-07-20 11:15:07 +000017#endif
18
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "SIISelLowering.h"
Christian Konig99ee0f42013-03-07 09:04:14 +000020#include "AMDGPU.h"
Matt Arsenault41e2f2b2014-02-24 21:01:28 +000021#include "AMDGPUSubtarget.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000022#include "AMDGPUTargetMachine.h"
Tom Stellard8485fa02016-12-07 02:42:15 +000023#include "SIDefines.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000024#include "SIInstrInfo.h"
25#include "SIMachineFunctionInfo.h"
26#include "SIRegisterInfo.h"
Tom Stellard44b30b42018-05-22 02:03:23 +000027#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000028#include "Utils/AMDGPUBaseInfo.h"
29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/APInt.h"
31#include "llvm/ADT/ArrayRef.h"
Alexey Samsonova253bf92014-08-27 19:36:53 +000032#include "llvm/ADT/BitVector.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000033#include "llvm/ADT/SmallVector.h"
Matt Arsenault71bcbd42017-08-11 20:42:08 +000034#include "llvm/ADT/Statistic.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000035#include "llvm/ADT/StringRef.h"
Matt Arsenault9a10cea2016-01-26 04:29:24 +000036#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000037#include "llvm/ADT/Twine.h"
Wei Ding07e03712016-07-28 16:42:13 +000038#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000039#include "llvm/CodeGen/CallingConvLower.h"
40#include "llvm/CodeGen/DAGCombine.h"
41#include "llvm/CodeGen/ISDOpcodes.h"
42#include "llvm/CodeGen/MachineBasicBlock.h"
43#include "llvm/CodeGen/MachineFrameInfo.h"
44#include "llvm/CodeGen/MachineFunction.h"
45#include "llvm/CodeGen/MachineInstr.h"
46#include "llvm/CodeGen/MachineInstrBuilder.h"
47#include "llvm/CodeGen/MachineMemOperand.h"
Matt Arsenault8623e8d2017-08-03 23:00:29 +000048#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000049#include "llvm/CodeGen/MachineOperand.h"
50#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000051#include "llvm/CodeGen/SelectionDAG.h"
52#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000053#include "llvm/CodeGen/TargetCallingConv.h"
54#include "llvm/CodeGen/TargetRegisterInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000055#include "llvm/CodeGen/ValueTypes.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000056#include "llvm/IR/Constants.h"
57#include "llvm/IR/DataLayout.h"
58#include "llvm/IR/DebugLoc.h"
59#include "llvm/IR/DerivedTypes.h"
Oliver Stannard7e7d9832016-02-02 13:52:43 +000060#include "llvm/IR/DiagnosticInfo.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000061#include "llvm/IR/Function.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000062#include "llvm/IR/GlobalValue.h"
63#include "llvm/IR/InstrTypes.h"
64#include "llvm/IR/Instruction.h"
65#include "llvm/IR/Instructions.h"
Matt Arsenault7dc01c92017-03-15 23:15:12 +000066#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000067#include "llvm/IR/Type.h"
68#include "llvm/Support/Casting.h"
69#include "llvm/Support/CodeGen.h"
70#include "llvm/Support/CommandLine.h"
71#include "llvm/Support/Compiler.h"
72#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000073#include "llvm/Support/KnownBits.h"
David Blaikie13e77db2018-03-23 23:58:25 +000074#include "llvm/Support/MachineValueType.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000075#include "llvm/Support/MathExtras.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000076#include "llvm/Target/TargetOptions.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000077#include <cassert>
78#include <cmath>
79#include <cstdint>
80#include <iterator>
81#include <tuple>
82#include <utility>
83#include <vector>
Tom Stellard75aadc22012-12-11 21:25:42 +000084
85using namespace llvm;
86
Matt Arsenault71bcbd42017-08-11 20:42:08 +000087#define DEBUG_TYPE "si-lower"
88
89STATISTIC(NumTailCalls, "Number of tail calls");
90
Matt Arsenaultd486d3f2016-10-12 18:49:05 +000091static cl::opt<bool> EnableVGPRIndexMode(
92 "amdgpu-vgpr-index-mode",
93 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
94 cl::init(false));
95
Stanislav Mekhanoshin93f15c92019-05-03 21:17:29 +000096static cl::opt<bool> DisableLoopAlignment(
97 "amdgpu-disable-loop-alignment",
98 cl::desc("Do not align and prefetch loops"),
99 cl::init(false));
100
Tom Stellardf110f8f2016-04-14 16:27:03 +0000101static unsigned findFirstFreeSGPR(CCState &CCInfo) {
102 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
103 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
104 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
105 return AMDGPU::SGPR0 + Reg;
106 }
107 }
108 llvm_unreachable("Cannot allocate sgpr");
109}
110
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000111SITargetLowering::SITargetLowering(const TargetMachine &TM,
Tom Stellard5bfbae52018-07-11 20:59:01 +0000112 const GCNSubtarget &STI)
Tom Stellardc5a154d2018-06-28 23:47:12 +0000113 : AMDGPUTargetLowering(TM, STI),
114 Subtarget(&STI) {
Tom Stellard1bd80722014-04-30 15:31:33 +0000115 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
Tom Stellard436780b2014-05-15 14:41:57 +0000116 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
Christian Konig2214f142013-03-07 09:03:38 +0000117
Marek Olsak79c05872016-11-25 17:37:09 +0000118 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
Tom Stellard45c0b3a2015-01-07 20:59:25 +0000119 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
Tom Stellard75aadc22012-12-11 21:25:42 +0000120
Tom Stellard436780b2014-05-15 14:41:57 +0000121 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
122 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
123 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
Christian Konig2214f142013-03-07 09:03:38 +0000124
Tim Renouf361b5b22019-03-21 12:01:21 +0000125 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
126 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
127
Matt Arsenault61001bb2015-11-25 19:58:34 +0000128 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
129 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
130
Tom Stellard436780b2014-05-15 14:41:57 +0000131 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
132 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
Christian Konig2214f142013-03-07 09:03:38 +0000133
Tim Renouf033f99a2019-03-22 10:11:21 +0000134 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
135 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
136
Tom Stellardf0a21072014-11-18 20:39:39 +0000137 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
Christian Konig2214f142013-03-07 09:03:38 +0000138 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
139
Tom Stellardf0a21072014-11-18 20:39:39 +0000140 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
Christian Konig2214f142013-03-07 09:03:38 +0000141 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
Tom Stellard75aadc22012-12-11 21:25:42 +0000142
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000143 if (Subtarget->has16BitInsts()) {
Marek Olsak79c05872016-11-25 17:37:09 +0000144 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
145 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
Tom Stellard115a6152016-11-10 16:02:37 +0000146
Matt Arsenault1349a042018-05-22 06:32:10 +0000147 // Unless there are also VOP3P operations, not operations are really legal.
Matt Arsenault7596f132017-02-27 20:52:10 +0000148 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
149 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
Matt Arsenault02dc7e12018-06-15 15:15:46 +0000150 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
151 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
Matt Arsenault7596f132017-02-27 20:52:10 +0000152 }
153
Tom Stellardc5a154d2018-06-28 23:47:12 +0000154 computeRegisterProperties(Subtarget->getRegisterInfo());
Tom Stellard75aadc22012-12-11 21:25:42 +0000155
Tom Stellard35bb18c2013-08-26 15:06:04 +0000156 // We need to custom lower vector stores from local memory
Matt Arsenault71e66762016-05-21 02:27:49 +0000157 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
Tim Renouf361b5b22019-03-21 12:01:21 +0000158 setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
Tom Stellard35bb18c2013-08-26 15:06:04 +0000159 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
Tim Renouf033f99a2019-03-22 10:11:21 +0000160 setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
Tom Stellardaf775432013-10-23 00:44:32 +0000161 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
162 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
Matt Arsenault71e66762016-05-21 02:27:49 +0000163 setOperationAction(ISD::LOAD, MVT::i1, Custom);
Stanislav Mekhanoshin44451b32018-08-31 22:43:36 +0000164 setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
Matt Arsenault2b957b52016-05-02 20:07:26 +0000165
Matt Arsenaultbcdfee72016-05-02 20:13:51 +0000166 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
Tim Renouf361b5b22019-03-21 12:01:21 +0000167 setOperationAction(ISD::STORE, MVT::v3i32, Custom);
Matt Arsenault71e66762016-05-21 02:27:49 +0000168 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
Tim Renouf033f99a2019-03-22 10:11:21 +0000169 setOperationAction(ISD::STORE, MVT::v5i32, Custom);
Matt Arsenault71e66762016-05-21 02:27:49 +0000170 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
171 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
172 setOperationAction(ISD::STORE, MVT::i1, Custom);
Stanislav Mekhanoshin44451b32018-08-31 22:43:36 +0000173 setOperationAction(ISD::STORE, MVT::v32i32, Custom);
Matt Arsenaultbcdfee72016-05-02 20:13:51 +0000174
Jan Vesely06200bd2017-01-06 21:00:46 +0000175 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
176 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
177 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
178 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
179 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
180 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
181 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
182 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
183 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
184 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
185
Matt Arsenault71e66762016-05-21 02:27:49 +0000186 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
187 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
Matt Arsenault71e66762016-05-21 02:27:49 +0000188
189 setOperationAction(ISD::SELECT, MVT::i1, Promote);
Tom Stellard0ec134f2014-02-04 17:18:40 +0000190 setOperationAction(ISD::SELECT, MVT::i64, Custom);
Tom Stellardda99c6e2014-03-24 16:07:30 +0000191 setOperationAction(ISD::SELECT, MVT::f64, Promote);
192 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
Tom Stellard81d871d2013-11-13 23:36:50 +0000193
Tom Stellard3ca1bfc2014-06-10 16:01:22 +0000194 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
195 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
196 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
197 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
Matt Arsenault71e66762016-05-21 02:27:49 +0000198 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
Tom Stellard754f80f2013-04-05 23:31:51 +0000199
Tom Stellardd1efda82016-01-20 21:48:24 +0000200 setOperationAction(ISD::SETCC, MVT::i1, Promote);
Tom Stellard83747202013-07-18 21:43:53 +0000201 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
202 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
Matt Arsenault18f56be2016-12-22 16:27:11 +0000203 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
Tom Stellard83747202013-07-18 21:43:53 +0000204
Matt Arsenault71e66762016-05-21 02:27:49 +0000205 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
206 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
Matt Arsenaulte306a322014-10-21 16:25:08 +0000207
Matt Arsenault4e466652014-04-16 01:41:30 +0000208 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
209 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
Matt Arsenault4e466652014-04-16 01:41:30 +0000210 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
211 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
Matt Arsenault4e466652014-04-16 01:41:30 +0000212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
Matt Arsenault4e466652014-04-16 01:41:30 +0000214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
215
Matt Arsenault754dd3e2017-04-03 18:08:08 +0000216 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
Tom Stellard9fa17912013-08-14 23:24:45 +0000217 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
Tom Stellard9fa17912013-08-14 23:24:45 +0000218 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
Matt Arsenaultb3a80e52018-08-15 21:25:20 +0000219 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
220 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
Marek Olsak13e47412018-01-31 20:18:04 +0000221 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
Matt Arsenault754dd3e2017-04-03 18:08:08 +0000222 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
223
Changpeng Fang44dfa1d2018-01-12 21:12:19 +0000224 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
225 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
David Stuttardf77079f2019-01-14 11:55:24 +0000226 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +0000227 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
Ryan Taylor00e063a2019-03-19 16:07:00 +0000228 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
229 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
Matt Arsenault754dd3e2017-04-03 18:08:08 +0000230
231 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
Matt Arsenault4165efd2017-01-17 07:26:53 +0000232 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
233 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
Changpeng Fang44dfa1d2018-01-12 21:12:19 +0000234 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
Ryan Taylor00e063a2019-03-19 16:07:00 +0000235 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
236 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +0000237
Matt Arsenaulte54e1c32014-06-23 18:00:44 +0000238 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
Matt Arsenault71e66762016-05-21 02:27:49 +0000239 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
Tom Stellardbc4497b2016-02-12 23:45:29 +0000240 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
241 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
242 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
243 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
Tom Stellardafcf12f2013-09-12 02:55:14 +0000244
Matt Arsenaultee3f0ac2017-01-30 18:11:38 +0000245 setOperationAction(ISD::UADDO, MVT::i32, Legal);
246 setOperationAction(ISD::USUBO, MVT::i32, Legal);
247
Stanislav Mekhanoshine3eb42c2017-06-21 22:05:06 +0000248 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
249 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
250
Matt Arsenaulte7191392018-08-08 16:58:33 +0000251 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
252 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
253 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
254
Matt Arsenault84445dd2017-11-30 22:51:26 +0000255#if 0
256 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
257 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
258#endif
259
Benjamin Kramer867bfc52015-03-07 17:41:00 +0000260 // We only support LOAD/STORE and vector manipulation ops for vectors
261 // with > 4 elements.
Matt Arsenault7596f132017-02-27 20:52:10 +0000262 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
Stanislav Mekhanoshin44451b32018-08-31 22:43:36 +0000263 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, MVT::v32i32 }) {
Tom Stellard967bf582014-02-13 23:34:15 +0000264 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
Matt Arsenault71e66762016-05-21 02:27:49 +0000265 switch (Op) {
Tom Stellard967bf582014-02-13 23:34:15 +0000266 case ISD::LOAD:
267 case ISD::STORE:
268 case ISD::BUILD_VECTOR:
269 case ISD::BITCAST:
270 case ISD::EXTRACT_VECTOR_ELT:
271 case ISD::INSERT_VECTOR_ELT:
Tom Stellard967bf582014-02-13 23:34:15 +0000272 case ISD::INSERT_SUBVECTOR:
273 case ISD::EXTRACT_SUBVECTOR:
Matt Arsenault61001bb2015-11-25 19:58:34 +0000274 case ISD::SCALAR_TO_VECTOR:
Tom Stellard967bf582014-02-13 23:34:15 +0000275 break;
Tom Stellardc0503db2014-08-09 01:06:56 +0000276 case ISD::CONCAT_VECTORS:
277 setOperationAction(Op, VT, Custom);
278 break;
Tom Stellard967bf582014-02-13 23:34:15 +0000279 default:
Matt Arsenaultd504a742014-05-15 21:44:05 +0000280 setOperationAction(Op, VT, Expand);
Tom Stellard967bf582014-02-13 23:34:15 +0000281 break;
282 }
283 }
284 }
285
Matt Arsenault02dc7e12018-06-15 15:15:46 +0000286 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
287
Matt Arsenaultcb540bc2016-07-19 00:35:03 +0000288 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
289 // is expanded to avoid having two separate loops in case the index is a VGPR.
290
Matt Arsenault61001bb2015-11-25 19:58:34 +0000291 // Most operations are naturally 32-bit vector operations. We only support
292 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
293 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
294 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
295 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
296
297 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
298 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
299
300 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
301 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
302
303 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
304 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
305 }
306
Matt Arsenault71e66762016-05-21 02:27:49 +0000307 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
308 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
309 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
310 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +0000311
Matt Arsenault67a98152018-05-16 11:47:30 +0000312 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
313 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
314
Matt Arsenault3aef8092017-01-23 23:09:58 +0000315 // Avoid stack access for these.
316 // TODO: Generalize to more vector types.
317 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
318 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
Matt Arsenault67a98152018-05-16 11:47:30 +0000319 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
320 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
321
Matt Arsenault3aef8092017-01-23 23:09:58 +0000322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
Matt Arsenault9224c002018-06-05 19:52:46 +0000324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
326 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
327
328 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
329 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
330 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
Matt Arsenault3aef8092017-01-23 23:09:58 +0000331
Matt Arsenault67a98152018-05-16 11:47:30 +0000332 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
334 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
335 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
336
Tim Renouf361b5b22019-03-21 12:01:21 +0000337 // Deal with vec3 vector operations when widened to vec4.
338 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Expand);
339 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Expand);
340 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Expand);
341 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Expand);
342
Tim Renouf033f99a2019-03-22 10:11:21 +0000343 // Deal with vec5 vector operations when widened to vec8.
344 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Expand);
345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Expand);
346 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Expand);
347 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Expand);
348
Tom Stellard354a43c2016-04-01 18:27:37 +0000349 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
350 // and output demarshalling
351 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
352 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
353
354 // We can't return success/failure, only the old value,
355 // let LLVM add the comparison
356 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
357 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
358
Tom Stellardc5a154d2018-06-28 23:47:12 +0000359 if (Subtarget->hasFlatAddressSpace()) {
Matt Arsenault99c14522016-04-25 19:27:24 +0000360 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
361 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
362 }
363
Matt Arsenault71e66762016-05-21 02:27:49 +0000364 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
365 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
366
367 // On SI this is s_memtime and s_memrealtime on VI.
368 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
Matt Arsenault3e025382017-04-24 17:49:13 +0000369 setOperationAction(ISD::TRAP, MVT::Other, Custom);
370 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
Matt Arsenault71e66762016-05-21 02:27:49 +0000371
Tom Stellardc5a154d2018-06-28 23:47:12 +0000372 if (Subtarget->has16BitInsts()) {
373 setOperationAction(ISD::FLOG, MVT::f16, Custom);
Matt Arsenault7121bed2018-08-16 17:07:52 +0000374 setOperationAction(ISD::FEXP, MVT::f16, Custom);
Tom Stellardc5a154d2018-06-28 23:47:12 +0000375 setOperationAction(ISD::FLOG10, MVT::f16, Custom);
376 }
377
378 // v_mad_f32 does not support denormals according to some sources.
379 if (!Subtarget->hasFP32Denormals())
380 setOperationAction(ISD::FMAD, MVT::f32, Legal);
381
382 if (!Subtarget->hasBFI()) {
383 // fcopysign can be done in a single instruction with BFI.
384 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
385 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
386 }
387
388 if (!Subtarget->hasBCNT(32))
389 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
390
391 if (!Subtarget->hasBCNT(64))
392 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
393
394 if (Subtarget->hasFFBH())
395 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
396
397 if (Subtarget->hasFFBL())
398 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
399
400 // We only really have 32-bit BFE instructions (and 16-bit on VI).
401 //
402 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
403 // effort to match them now. We want this to be false for i64 cases when the
404 // extraction isn't restricted to the upper or lower half. Ideally we would
405 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
406 // span the midpoint are probably relatively rare, so don't worry about them
407 // for now.
408 if (Subtarget->hasBFE())
409 setHasExtractBitsInsn(true);
410
Matt Arsenault687ec752018-10-22 16:27:27 +0000411 setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
412 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
413 setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
414 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
415
416
417 // These are really only legal for ieee_mode functions. We should be avoiding
418 // them for functions that don't have ieee_mode enabled, so just say they are
419 // legal.
420 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
421 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
422 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
423 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
424
Matt Arsenault71e66762016-05-21 02:27:49 +0000425
Matt Arsenaulte4c2e9b2019-06-19 23:54:58 +0000426 if (Subtarget->haveRoundOpsF64()) {
Matt Arsenault71e66762016-05-21 02:27:49 +0000427 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
428 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
429 setOperationAction(ISD::FRINT, MVT::f64, Legal);
Tom Stellardc5a154d2018-06-28 23:47:12 +0000430 } else {
431 setOperationAction(ISD::FCEIL, MVT::f64, Custom);
432 setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
433 setOperationAction(ISD::FRINT, MVT::f64, Custom);
434 setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
Matt Arsenault71e66762016-05-21 02:27:49 +0000435 }
436
437 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
438
439 setOperationAction(ISD::FSIN, MVT::f32, Custom);
440 setOperationAction(ISD::FCOS, MVT::f32, Custom);
441 setOperationAction(ISD::FDIV, MVT::f32, Custom);
442 setOperationAction(ISD::FDIV, MVT::f64, Custom);
443
Tom Stellard115a6152016-11-10 16:02:37 +0000444 if (Subtarget->has16BitInsts()) {
445 setOperationAction(ISD::Constant, MVT::i16, Legal);
446
447 setOperationAction(ISD::SMIN, MVT::i16, Legal);
448 setOperationAction(ISD::SMAX, MVT::i16, Legal);
449
450 setOperationAction(ISD::UMIN, MVT::i16, Legal);
451 setOperationAction(ISD::UMAX, MVT::i16, Legal);
452
Tom Stellard115a6152016-11-10 16:02:37 +0000453 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
454 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
455
456 setOperationAction(ISD::ROTR, MVT::i16, Promote);
457 setOperationAction(ISD::ROTL, MVT::i16, Promote);
458
459 setOperationAction(ISD::SDIV, MVT::i16, Promote);
460 setOperationAction(ISD::UDIV, MVT::i16, Promote);
461 setOperationAction(ISD::SREM, MVT::i16, Promote);
462 setOperationAction(ISD::UREM, MVT::i16, Promote);
463
464 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
465 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
466
467 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
468 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
469 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
470 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
Jan Veselyb283ea02018-03-02 02:50:22 +0000471 setOperationAction(ISD::CTPOP, MVT::i16, Promote);
Tom Stellard115a6152016-11-10 16:02:37 +0000472
473 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
474
475 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
476
477 setOperationAction(ISD::LOAD, MVT::i16, Custom);
478
479 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
480
Tom Stellard115a6152016-11-10 16:02:37 +0000481 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
482 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
483 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
484 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
Tom Stellardb4c8e8e2016-11-12 00:19:11 +0000485
Konstantin Zhuravlyov3f0cdc72016-11-17 04:00:46 +0000486 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
487 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
488 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
489 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
Tom Stellardb4c8e8e2016-11-12 00:19:11 +0000490
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000491 // F16 - Constant Actions.
Matt Arsenaulte96d0372016-12-08 20:14:46 +0000492 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000493
494 // F16 - Load/Store Actions.
495 setOperationAction(ISD::LOAD, MVT::f16, Promote);
496 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
497 setOperationAction(ISD::STORE, MVT::f16, Promote);
498 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
499
500 // F16 - VOP1 Actions.
Konstantin Zhuravlyovd709efb2016-11-17 04:28:37 +0000501 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000502 setOperationAction(ISD::FCOS, MVT::f16, Promote);
503 setOperationAction(ISD::FSIN, MVT::f16, Promote);
Konstantin Zhuravlyov3f0cdc72016-11-17 04:00:46 +0000504 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
505 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
506 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
507 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
Matt Arsenaultb5d23272017-03-24 20:04:18 +0000508 setOperationAction(ISD::FROUND, MVT::f16, Custom);
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000509
510 // F16 - VOP2 Actions.
Konstantin Zhuravlyov662e01d2016-11-17 03:49:01 +0000511 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
Konstantin Zhuravlyov2a87a422016-11-16 03:16:26 +0000512 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
Matt Arsenault687ec752018-10-22 16:27:27 +0000513
Matt Arsenault4052a572016-12-22 03:05:41 +0000514 setOperationAction(ISD::FDIV, MVT::f16, Custom);
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000515
516 // F16 - VOP3 Actions.
517 setOperationAction(ISD::FMA, MVT::f16, Legal);
Stanislav Mekhanoshin28a19362019-05-04 04:20:37 +0000518 if (!Subtarget->hasFP16Denormals() && STI.hasMadF16())
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000519 setOperationAction(ISD::FMAD, MVT::f16, Legal);
Tom Stellard115a6152016-11-10 16:02:37 +0000520
Matt Arsenault02dc7e12018-06-15 15:15:46 +0000521 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
Matt Arsenault7596f132017-02-27 20:52:10 +0000522 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
523 switch (Op) {
524 case ISD::LOAD:
525 case ISD::STORE:
526 case ISD::BUILD_VECTOR:
527 case ISD::BITCAST:
528 case ISD::EXTRACT_VECTOR_ELT:
529 case ISD::INSERT_VECTOR_ELT:
530 case ISD::INSERT_SUBVECTOR:
531 case ISD::EXTRACT_SUBVECTOR:
532 case ISD::SCALAR_TO_VECTOR:
533 break;
534 case ISD::CONCAT_VECTORS:
535 setOperationAction(Op, VT, Custom);
536 break;
537 default:
538 setOperationAction(Op, VT, Expand);
539 break;
540 }
541 }
542 }
543
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000544 // XXX - Do these do anything? Vector constants turn into build_vector.
545 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
546 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
547
Matt Arsenaultdfb88df2018-05-13 10:04:38 +0000548 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
549 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
550
Matt Arsenault7596f132017-02-27 20:52:10 +0000551 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
552 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
553 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
554 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
555
556 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
557 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
558 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
559 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000560
561 setOperationAction(ISD::AND, MVT::v2i16, Promote);
562 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
563 setOperationAction(ISD::OR, MVT::v2i16, Promote);
564 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
565 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
566 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000567
Matt Arsenault1349a042018-05-22 06:32:10 +0000568 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
569 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
570 setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
571 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
572
573 setOperationAction(ISD::STORE, MVT::v4i16, Promote);
574 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
575 setOperationAction(ISD::STORE, MVT::v4f16, Promote);
576 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
577
578 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
579 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
580 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
581 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
582
Matt Arsenault02dc7e12018-06-15 15:15:46 +0000583 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
584 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
585 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
586
Matt Arsenault1349a042018-05-22 06:32:10 +0000587 if (!Subtarget->hasVOP3PInsts()) {
588 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
589 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
590 }
591
592 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
593 // This isn't really legal, but this avoids the legalizer unrolling it (and
594 // allows matching fneg (fabs x) patterns)
595 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
Matt Arsenault687ec752018-10-22 16:27:27 +0000596
597 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
598 setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
599 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
600 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
601
602 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
603 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
604
605 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
606 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
Matt Arsenault1349a042018-05-22 06:32:10 +0000607 }
608
609 if (Subtarget->hasVOP3PInsts()) {
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000610 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
611 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
612 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
613 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
614 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
615 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
616 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
617 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
618 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
619 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
620
621 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000622 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
623 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
Matt Arsenault687ec752018-10-22 16:27:27 +0000624
625 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
626 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
627
Matt Arsenault540512c2018-04-26 19:21:37 +0000628 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000629
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000630 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
631 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
Matt Arsenault02dc7e12018-06-15 15:15:46 +0000632
633 setOperationAction(ISD::SHL, MVT::v4i16, Custom);
634 setOperationAction(ISD::SRA, MVT::v4i16, Custom);
635 setOperationAction(ISD::SRL, MVT::v4i16, Custom);
636 setOperationAction(ISD::ADD, MVT::v4i16, Custom);
637 setOperationAction(ISD::SUB, MVT::v4i16, Custom);
638 setOperationAction(ISD::MUL, MVT::v4i16, Custom);
639
640 setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
641 setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
642 setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
643 setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
644
645 setOperationAction(ISD::FADD, MVT::v4f16, Custom);
646 setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
Matt Arsenault687ec752018-10-22 16:27:27 +0000647
648 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
649 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
650
Matt Arsenault02dc7e12018-06-15 15:15:46 +0000651 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
652 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
Matt Arsenault36cdcfa2018-08-02 13:43:42 +0000653 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
Matt Arsenault02dc7e12018-06-15 15:15:46 +0000654
Matt Arsenault7121bed2018-08-16 17:07:52 +0000655 setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
Matt Arsenault02dc7e12018-06-15 15:15:46 +0000656 setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
657 setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
Matt Arsenault1349a042018-05-22 06:32:10 +0000658 }
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000659
Matt Arsenault02dc7e12018-06-15 15:15:46 +0000660 setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
661 setOperationAction(ISD::FABS, MVT::v4f16, Custom);
662
Matt Arsenault1349a042018-05-22 06:32:10 +0000663 if (Subtarget->has16BitInsts()) {
664 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
665 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
666 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
667 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
Matt Arsenault4a486232017-04-19 20:53:07 +0000668 } else {
Matt Arsenault1349a042018-05-22 06:32:10 +0000669 // Legalization hack.
Matt Arsenault4a486232017-04-19 20:53:07 +0000670 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
671 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
Matt Arsenaulte9524f12018-06-06 21:28:11 +0000672
673 setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
674 setOperationAction(ISD::FABS, MVT::v2f16, Custom);
Matt Arsenault4a486232017-04-19 20:53:07 +0000675 }
676
677 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
678 setOperationAction(ISD::SELECT, VT, Custom);
Matt Arsenault7596f132017-02-27 20:52:10 +0000679 }
680
Stanislav Mekhanoshine3eb42c2017-06-21 22:05:06 +0000681 setTargetDAGCombine(ISD::ADD);
Stanislav Mekhanoshina8b26932017-06-21 22:30:01 +0000682 setTargetDAGCombine(ISD::ADDCARRY);
683 setTargetDAGCombine(ISD::SUB);
684 setTargetDAGCombine(ISD::SUBCARRY);
Matt Arsenault02cb0ff2014-09-29 14:59:34 +0000685 setTargetDAGCombine(ISD::FADD);
Matt Arsenault8675db12014-08-29 16:01:14 +0000686 setTargetDAGCombine(ISD::FSUB);
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +0000687 setTargetDAGCombine(ISD::FMINNUM);
688 setTargetDAGCombine(ISD::FMAXNUM);
Matt Arsenault687ec752018-10-22 16:27:27 +0000689 setTargetDAGCombine(ISD::FMINNUM_IEEE);
690 setTargetDAGCombine(ISD::FMAXNUM_IEEE);
Farhana Aleenc370d7b2018-07-16 18:19:59 +0000691 setTargetDAGCombine(ISD::FMA);
Matt Arsenault5881f4e2015-06-09 00:52:37 +0000692 setTargetDAGCombine(ISD::SMIN);
693 setTargetDAGCombine(ISD::SMAX);
694 setTargetDAGCombine(ISD::UMIN);
695 setTargetDAGCombine(ISD::UMAX);
Tom Stellard75aadc22012-12-11 21:25:42 +0000696 setTargetDAGCombine(ISD::SETCC);
Matt Arsenaultd0101a22015-01-06 23:00:46 +0000697 setTargetDAGCombine(ISD::AND);
Matt Arsenaultf2290332015-01-06 23:00:39 +0000698 setTargetDAGCombine(ISD::OR);
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000699 setTargetDAGCombine(ISD::XOR);
Konstantin Zhuravlyovfda33ea2016-10-21 22:10:03 +0000700 setTargetDAGCombine(ISD::SINT_TO_FP);
Matt Arsenault364a6742014-06-11 17:50:44 +0000701 setTargetDAGCombine(ISD::UINT_TO_FP);
Matt Arsenault9cd90712016-04-14 01:42:16 +0000702 setTargetDAGCombine(ISD::FCANONICALIZE);
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000703 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
Matt Arsenault8edfaee2017-03-31 19:53:03 +0000704 setTargetDAGCombine(ISD::ZERO_EXTEND);
Ryan Taylor00e063a2019-03-19 16:07:00 +0000705 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
Matt Arsenaultbf5482e2017-05-11 17:26:25 +0000706 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Stanislav Mekhanoshin054f8102018-11-19 17:39:20 +0000707 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Matt Arsenault364a6742014-06-11 17:50:44 +0000708
Matt Arsenaultb2baffa2014-08-15 17:49:05 +0000709 // All memory operations. Some folding on the pointer operand is done to help
710 // matching the constant offsets in the addressing modes.
711 setTargetDAGCombine(ISD::LOAD);
712 setTargetDAGCombine(ISD::STORE);
713 setTargetDAGCombine(ISD::ATOMIC_LOAD);
714 setTargetDAGCombine(ISD::ATOMIC_STORE);
715 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
716 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
717 setTargetDAGCombine(ISD::ATOMIC_SWAP);
718 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
719 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
720 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
721 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
722 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
723 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
724 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
725 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
726 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
727 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
Matt Arsenaulta5840c32019-01-22 18:36:06 +0000728 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
Matt Arsenaultb2baffa2014-08-15 17:49:05 +0000729
Christian Konigeecebd02013-03-26 14:04:02 +0000730 setSchedulingPreference(Sched::RegPressure);
Tom Stellard75aadc22012-12-11 21:25:42 +0000731}
732
Tom Stellard5bfbae52018-07-11 20:59:01 +0000733const GCNSubtarget *SITargetLowering::getSubtarget() const {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000734 return Subtarget;
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000735}
736
Tom Stellard0125f2a2013-06-25 02:39:35 +0000737//===----------------------------------------------------------------------===//
738// TargetLowering queries
739//===----------------------------------------------------------------------===//
740
Tom Stellardb12f4de2018-05-22 19:37:55 +0000741// v_mad_mix* support a conversion from f16 to f32.
742//
743// There is only one special case when denormals are enabled we don't currently,
744// where this is OK to use.
745bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
746 EVT DestVT, EVT SrcVT) const {
747 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
748 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
749 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
750 SrcVT.getScalarType() == MVT::f16;
751}
752
Zvi Rackover1b736822017-07-26 08:06:58 +0000753bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
Matt Arsenault7dc01c92017-03-15 23:15:12 +0000754 // SI has some legal vector types, but no legal vector operations. Say no
755 // shuffles are legal in order to prefer scalarizing some vector operations.
756 return false;
757}
758
Matt Arsenault8f9dde92018-07-28 14:11:34 +0000759MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
760 CallingConv::ID CC,
761 EVT VT) const {
Matt Arsenault9ced1e02018-07-31 19:05:14 +0000762 // TODO: Consider splitting all arguments into 32-bit pieces.
763 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
Matt Arsenault8f9dde92018-07-28 14:11:34 +0000764 EVT ScalarVT = VT.getScalarType();
Matt Arsenault9ced1e02018-07-31 19:05:14 +0000765 unsigned Size = ScalarVT.getSizeInBits();
Matt Arsenaultfeedabf2018-07-31 19:29:04 +0000766 if (Size == 32)
Matt Arsenault8f9dde92018-07-28 14:11:34 +0000767 return ScalarVT.getSimpleVT();
Matt Arsenault0395da72018-07-31 19:17:47 +0000768
Matt Arsenaultfeedabf2018-07-31 19:29:04 +0000769 if (Size == 64)
770 return MVT::i32;
771
Matt Arsenault57b59662018-09-10 11:49:23 +0000772 if (Size == 16 && Subtarget->has16BitInsts())
Matt Arsenault0395da72018-07-31 19:17:47 +0000773 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
Matt Arsenault8f9dde92018-07-28 14:11:34 +0000774 }
775
776 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
777}
778
779unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
780 CallingConv::ID CC,
781 EVT VT) const {
Matt Arsenault9ced1e02018-07-31 19:05:14 +0000782 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
Matt Arsenault0395da72018-07-31 19:17:47 +0000783 unsigned NumElts = VT.getVectorNumElements();
Matt Arsenault8f9dde92018-07-28 14:11:34 +0000784 EVT ScalarVT = VT.getScalarType();
Matt Arsenault9ced1e02018-07-31 19:05:14 +0000785 unsigned Size = ScalarVT.getSizeInBits();
Matt Arsenault0395da72018-07-31 19:17:47 +0000786
Matt Arsenaultfeedabf2018-07-31 19:29:04 +0000787 if (Size == 32)
Matt Arsenault0395da72018-07-31 19:17:47 +0000788 return NumElts;
789
Matt Arsenaultfeedabf2018-07-31 19:29:04 +0000790 if (Size == 64)
791 return 2 * NumElts;
792
Matt Arsenault57b59662018-09-10 11:49:23 +0000793 if (Size == 16 && Subtarget->has16BitInsts())
794 return (VT.getVectorNumElements() + 1) / 2;
Matt Arsenault8f9dde92018-07-28 14:11:34 +0000795 }
796
797 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
798}
799
800unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
801 LLVMContext &Context, CallingConv::ID CC,
802 EVT VT, EVT &IntermediateVT,
803 unsigned &NumIntermediates, MVT &RegisterVT) const {
Matt Arsenault9ced1e02018-07-31 19:05:14 +0000804 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
Matt Arsenault0395da72018-07-31 19:17:47 +0000805 unsigned NumElts = VT.getVectorNumElements();
Matt Arsenault8f9dde92018-07-28 14:11:34 +0000806 EVT ScalarVT = VT.getScalarType();
Matt Arsenault9ced1e02018-07-31 19:05:14 +0000807 unsigned Size = ScalarVT.getSizeInBits();
Matt Arsenaultfeedabf2018-07-31 19:29:04 +0000808 if (Size == 32) {
Matt Arsenault8f9dde92018-07-28 14:11:34 +0000809 RegisterVT = ScalarVT.getSimpleVT();
810 IntermediateVT = RegisterVT;
Matt Arsenault0395da72018-07-31 19:17:47 +0000811 NumIntermediates = NumElts;
812 return NumIntermediates;
813 }
814
Matt Arsenaultfeedabf2018-07-31 19:29:04 +0000815 if (Size == 64) {
816 RegisterVT = MVT::i32;
817 IntermediateVT = RegisterVT;
818 NumIntermediates = 2 * NumElts;
819 return NumIntermediates;
820 }
821
Matt Arsenault0395da72018-07-31 19:17:47 +0000822 // FIXME: We should fix the ABI to be the same on targets without 16-bit
823 // support, but unless we can properly handle 3-vectors, it will be still be
824 // inconsistent.
Matt Arsenault57b59662018-09-10 11:49:23 +0000825 if (Size == 16 && Subtarget->has16BitInsts()) {
Matt Arsenault0395da72018-07-31 19:17:47 +0000826 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
827 IntermediateVT = RegisterVT;
Matt Arsenault57b59662018-09-10 11:49:23 +0000828 NumIntermediates = (NumElts + 1) / 2;
Matt Arsenault8f9dde92018-07-28 14:11:34 +0000829 return NumIntermediates;
830 }
831 }
832
833 return TargetLowering::getVectorTypeBreakdownForCallingConv(
834 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
835}
836
David Stuttardf77079f2019-01-14 11:55:24 +0000837static MVT memVTFromAggregate(Type *Ty) {
838 // Only limited forms of aggregate type currently expected.
839 assert(Ty->isStructTy() && "Expected struct type");
840
841
842 Type *ElementType = nullptr;
843 unsigned NumElts;
844 if (Ty->getContainedType(0)->isVectorTy()) {
845 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0));
846 ElementType = VecComponent->getElementType();
847 NumElts = VecComponent->getNumElements();
848 } else {
849 ElementType = Ty->getContainedType(0);
850 NumElts = 1;
851 }
852
853 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type");
854
855 // Calculate the size of the memVT type from the aggregate
856 unsigned Pow2Elts = 0;
857 unsigned ElementSize;
858 switch (ElementType->getTypeID()) {
859 default:
860 llvm_unreachable("Unknown type!");
861 case Type::IntegerTyID:
862 ElementSize = cast<IntegerType>(ElementType)->getBitWidth();
863 break;
864 case Type::HalfTyID:
865 ElementSize = 16;
866 break;
867 case Type::FloatTyID:
868 ElementSize = 32;
869 break;
870 }
871 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1;
872 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts);
873
874 return MVT::getVectorVT(MVT::getVT(ElementType, false),
875 Pow2Elts);
876}
877
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +0000878bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
879 const CallInst &CI,
Matt Arsenault7d7adf42017-12-14 22:34:10 +0000880 MachineFunction &MF,
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +0000881 unsigned IntrID) const {
Nicolai Haehnle5d0d3032018-04-01 17:09:07 +0000882 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
Nicolai Haehnlee741d7e2018-06-21 13:36:33 +0000883 AMDGPU::lookupRsrcIntrinsic(IntrID)) {
Nicolai Haehnle5d0d3032018-04-01 17:09:07 +0000884 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
885 (Intrinsic::ID)IntrID);
886 if (Attr.hasFnAttribute(Attribute::ReadNone))
887 return false;
888
889 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
890
891 if (RsrcIntr->IsImage) {
892 Info.ptrVal = MFI->getImagePSV(
Tom Stellard5bfbae52018-07-11 20:59:01 +0000893 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
Nicolai Haehnle5d0d3032018-04-01 17:09:07 +0000894 CI.getArgOperand(RsrcIntr->RsrcArg));
895 Info.align = 0;
896 } else {
897 Info.ptrVal = MFI->getBufferPSV(
Tom Stellard5bfbae52018-07-11 20:59:01 +0000898 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
Nicolai Haehnle5d0d3032018-04-01 17:09:07 +0000899 CI.getArgOperand(RsrcIntr->RsrcArg));
900 }
901
902 Info.flags = MachineMemOperand::MODereferenceable;
903 if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
904 Info.opc = ISD::INTRINSIC_W_CHAIN;
David Stuttardf77079f2019-01-14 11:55:24 +0000905 Info.memVT = MVT::getVT(CI.getType(), true);
906 if (Info.memVT == MVT::Other) {
907 // Some intrinsics return an aggregate type - special case to work out
908 // the correct memVT
909 Info.memVT = memVTFromAggregate(CI.getType());
910 }
Nicolai Haehnle5d0d3032018-04-01 17:09:07 +0000911 Info.flags |= MachineMemOperand::MOLoad;
912 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
913 Info.opc = ISD::INTRINSIC_VOID;
914 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
915 Info.flags |= MachineMemOperand::MOStore;
916 } else {
917 // Atomic
918 Info.opc = ISD::INTRINSIC_W_CHAIN;
919 Info.memVT = MVT::getVT(CI.getType());
920 Info.flags = MachineMemOperand::MOLoad |
921 MachineMemOperand::MOStore |
922 MachineMemOperand::MODereferenceable;
923
924 // XXX - Should this be volatile without known ordering?
925 Info.flags |= MachineMemOperand::MOVolatile;
926 }
927 return true;
928 }
929
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +0000930 switch (IntrID) {
931 case Intrinsic::amdgcn_atomic_inc:
Daniil Fukalovd5fca552018-01-17 14:05:05 +0000932 case Intrinsic::amdgcn_atomic_dec:
Marek Olsakc5cec5e2019-01-16 15:43:53 +0000933 case Intrinsic::amdgcn_ds_ordered_add:
934 case Intrinsic::amdgcn_ds_ordered_swap:
Daniil Fukalov6e1dc682018-01-26 11:09:38 +0000935 case Intrinsic::amdgcn_ds_fadd:
936 case Intrinsic::amdgcn_ds_fmin:
937 case Intrinsic::amdgcn_ds_fmax: {
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +0000938 Info.opc = ISD::INTRINSIC_W_CHAIN;
939 Info.memVT = MVT::getVT(CI.getType());
940 Info.ptrVal = CI.getOperand(0);
941 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +0000942 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
Matt Arsenault79f837c2017-03-30 22:21:40 +0000943
Matt Arsenaultcaf13162019-03-12 21:02:54 +0000944 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
945 if (!Vol->isZero())
Matt Arsenault11171332017-12-14 21:39:51 +0000946 Info.flags |= MachineMemOperand::MOVolatile;
947
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +0000948 return true;
Matt Arsenault79f837c2017-03-30 22:21:40 +0000949 }
Matt Arsenaultcdd191d2019-01-28 20:14:49 +0000950 case Intrinsic::amdgcn_ds_append:
951 case Intrinsic::amdgcn_ds_consume: {
952 Info.opc = ISD::INTRINSIC_W_CHAIN;
953 Info.memVT = MVT::getVT(CI.getType());
954 Info.ptrVal = CI.getOperand(0);
955 Info.align = 0;
956 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
Matt Arsenault905f3512017-12-29 17:18:14 +0000957
Matt Arsenaultcaf13162019-03-12 21:02:54 +0000958 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
959 if (!Vol->isZero())
Matt Arsenaultcdd191d2019-01-28 20:14:49 +0000960 Info.flags |= MachineMemOperand::MOVolatile;
961
962 return true;
963 }
Matt Arsenault4d55d022019-06-19 19:55:27 +0000964 case Intrinsic::amdgcn_ds_gws_init:
Matt Arsenault740322f2019-06-20 21:11:42 +0000965 case Intrinsic::amdgcn_ds_gws_barrier:
966 case Intrinsic::amdgcn_ds_gws_sema_v:
967 case Intrinsic::amdgcn_ds_gws_sema_br:
968 case Intrinsic::amdgcn_ds_gws_sema_p:
969 case Intrinsic::amdgcn_ds_gws_sema_release_all: {
Matt Arsenault4d55d022019-06-19 19:55:27 +0000970 Info.opc = ISD::INTRINSIC_VOID;
971
972 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
973 Info.ptrVal =
974 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
975
976 // This is an abstract access, but we need to specify a type and size.
977 Info.memVT = MVT::i32;
978 Info.size = 4;
979 Info.align = 4;
980
981 Info.flags = MachineMemOperand::MOStore;
982 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
983 Info.flags = MachineMemOperand::MOLoad;
984 return true;
985 }
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +0000986 default:
987 return false;
988 }
989}
990
Matt Arsenault7dc01c92017-03-15 23:15:12 +0000991bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
992 SmallVectorImpl<Value*> &Ops,
993 Type *&AccessTy) const {
994 switch (II->getIntrinsicID()) {
995 case Intrinsic::amdgcn_atomic_inc:
Daniil Fukalovd5fca552018-01-17 14:05:05 +0000996 case Intrinsic::amdgcn_atomic_dec:
Marek Olsakc5cec5e2019-01-16 15:43:53 +0000997 case Intrinsic::amdgcn_ds_ordered_add:
998 case Intrinsic::amdgcn_ds_ordered_swap:
Daniil Fukalov6e1dc682018-01-26 11:09:38 +0000999 case Intrinsic::amdgcn_ds_fadd:
1000 case Intrinsic::amdgcn_ds_fmin:
1001 case Intrinsic::amdgcn_ds_fmax: {
Matt Arsenault7dc01c92017-03-15 23:15:12 +00001002 Value *Ptr = II->getArgOperand(0);
1003 AccessTy = II->getType();
1004 Ops.push_back(Ptr);
1005 return true;
1006 }
1007 default:
1008 return false;
1009 }
Matt Arsenaulte306a322014-10-21 16:25:08 +00001010}
1011
Tom Stellard70580f82015-07-20 14:28:41 +00001012bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
Matt Arsenaultd9b77842017-06-12 17:06:35 +00001013 if (!Subtarget->hasFlatInstOffsets()) {
1014 // Flat instructions do not have offsets, and only have the register
1015 // address.
1016 return AM.BaseOffs == 0 && AM.Scale == 0;
1017 }
1018
1019 // GFX9 added a 13-bit signed offset. When using regular flat instructions,
1020 // the sign bit is ignored and is treated as a 12-bit unsigned offset.
1021
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00001022 // GFX10 shrinked signed offset to 12 bits. When using regular flat
1023 // instructions, the sign bit is also ignored and is treated as 11-bit
1024 // unsigned offset.
1025
1026 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
1027 return isUInt<11>(AM.BaseOffs) && AM.Scale == 0;
1028
Matt Arsenaultd9b77842017-06-12 17:06:35 +00001029 // Just r + i
1030 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
Tom Stellard70580f82015-07-20 14:28:41 +00001031}
1032
Matt Arsenaultdc8f5cc2017-07-29 01:12:31 +00001033bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1034 if (Subtarget->hasFlatGlobalInsts())
1035 return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
1036
1037 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1038 // Assume the we will use FLAT for all global memory accesses
1039 // on VI.
1040 // FIXME: This assumption is currently wrong. On VI we still use
1041 // MUBUF instructions for the r + i addressing mode. As currently
1042 // implemented, the MUBUF instructions only work on buffer < 4GB.
1043 // It may be possible to support > 4GB buffers with MUBUF instructions,
1044 // by setting the stride value in the resource descriptor which would
1045 // increase the size limit to (stride * 4GB). However, this is risky,
1046 // because it has never been validated.
1047 return isLegalFlatAddressingMode(AM);
1048 }
1049
1050 return isLegalMUBUFAddressingMode(AM);
1051}
1052
Matt Arsenault711b3902015-08-07 20:18:34 +00001053bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1054 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1055 // additionally can do r + r + i with addr64. 32-bit has more addressing
1056 // mode options. Depending on the resource constant, it can also do
1057 // (i64 r0) + (i32 r1) * (i14 i).
1058 //
1059 // Private arrays end up using a scratch buffer most of the time, so also
1060 // assume those use MUBUF instructions. Scratch loads / stores are currently
1061 // implemented as mubuf instructions with offen bit set, so slightly
1062 // different than the normal addr64.
1063 if (!isUInt<12>(AM.BaseOffs))
1064 return false;
1065
1066 // FIXME: Since we can split immediate into soffset and immediate offset,
1067 // would it make sense to allow any immediate?
1068
1069 switch (AM.Scale) {
1070 case 0: // r + i or just i, depending on HasBaseReg.
1071 return true;
1072 case 1:
1073 return true; // We have r + r or r + i.
1074 case 2:
1075 if (AM.HasBaseReg) {
1076 // Reject 2 * r + r.
1077 return false;
1078 }
1079
1080 // Allow 2 * r as r + r
1081 // Or 2 * r + i is allowed as r + r + i.
1082 return true;
1083 default: // Don't allow n * r
1084 return false;
1085 }
1086}
1087
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00001088bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1089 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00001090 unsigned AS, Instruction *I) const {
Matt Arsenault5015a892014-08-15 17:17:07 +00001091 // No global is ever allowed as a base.
1092 if (AM.BaseGV)
1093 return false;
1094
Matt Arsenault0da63502018-08-31 05:49:54 +00001095 if (AS == AMDGPUAS::GLOBAL_ADDRESS)
Matt Arsenaultdc8f5cc2017-07-29 01:12:31 +00001096 return isLegalGlobalAddressingMode(AM);
Matt Arsenault5015a892014-08-15 17:17:07 +00001097
Matt Arsenault0da63502018-08-31 05:49:54 +00001098 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
Neil Henning523dab02019-03-18 14:44:28 +00001099 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1100 AS == AMDGPUAS::BUFFER_FAT_POINTER) {
Matt Arsenault711b3902015-08-07 20:18:34 +00001101 // If the offset isn't a multiple of 4, it probably isn't going to be
1102 // correctly aligned.
Matt Arsenault3cc1e002016-08-13 01:43:51 +00001103 // FIXME: Can we get the real alignment here?
Matt Arsenault711b3902015-08-07 20:18:34 +00001104 if (AM.BaseOffs % 4 != 0)
1105 return isLegalMUBUFAddressingMode(AM);
1106
1107 // There are no SMRD extloads, so if we have to do a small type access we
1108 // will use a MUBUF load.
1109 // FIXME?: We also need to do this if unaligned, but we don't know the
1110 // alignment here.
Stanislav Mekhanoshin57d341c2018-05-15 22:07:51 +00001111 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
Matt Arsenaultdc8f5cc2017-07-29 01:12:31 +00001112 return isLegalGlobalAddressingMode(AM);
Matt Arsenault711b3902015-08-07 20:18:34 +00001113
Tom Stellard5bfbae52018-07-11 20:59:01 +00001114 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
Matt Arsenault711b3902015-08-07 20:18:34 +00001115 // SMRD instructions have an 8-bit, dword offset on SI.
1116 if (!isUInt<8>(AM.BaseOffs / 4))
1117 return false;
Tom Stellard5bfbae52018-07-11 20:59:01 +00001118 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
Matt Arsenault711b3902015-08-07 20:18:34 +00001119 // On CI+, this can also be a 32-bit literal constant offset. If it fits
1120 // in 8-bits, it can use a smaller encoding.
1121 if (!isUInt<32>(AM.BaseOffs / 4))
1122 return false;
Tom Stellard5bfbae52018-07-11 20:59:01 +00001123 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
Matt Arsenault711b3902015-08-07 20:18:34 +00001124 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1125 if (!isUInt<20>(AM.BaseOffs))
1126 return false;
1127 } else
1128 llvm_unreachable("unhandled generation");
1129
1130 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1131 return true;
1132
1133 if (AM.Scale == 1 && AM.HasBaseReg)
1134 return true;
1135
1136 return false;
Matt Arsenault711b3902015-08-07 20:18:34 +00001137
Matt Arsenault0da63502018-08-31 05:49:54 +00001138 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
Matt Arsenault711b3902015-08-07 20:18:34 +00001139 return isLegalMUBUFAddressingMode(AM);
Matt Arsenault0da63502018-08-31 05:49:54 +00001140 } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1141 AS == AMDGPUAS::REGION_ADDRESS) {
Matt Arsenault73e06fa2015-06-04 16:17:42 +00001142 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1143 // field.
1144 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1145 // an 8-bit dword offset but we don't know the alignment here.
1146 if (!isUInt<16>(AM.BaseOffs))
Matt Arsenault5015a892014-08-15 17:17:07 +00001147 return false;
Matt Arsenault73e06fa2015-06-04 16:17:42 +00001148
1149 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1150 return true;
1151
1152 if (AM.Scale == 1 && AM.HasBaseReg)
1153 return true;
1154
Matt Arsenault5015a892014-08-15 17:17:07 +00001155 return false;
Matt Arsenault0da63502018-08-31 05:49:54 +00001156 } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1157 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
Matt Arsenault7d1b6c82016-04-29 06:25:10 +00001158 // For an unknown address space, this usually means that this is for some
1159 // reason being used for pure arithmetic, and not based on some addressing
1160 // computation. We don't have instructions that compute pointers with any
1161 // addressing modes, so treat them as having no offset like flat
1162 // instructions.
Tom Stellard70580f82015-07-20 14:28:41 +00001163 return isLegalFlatAddressingMode(AM);
Yaxun Liu1a14bfa2017-03-27 14:04:01 +00001164 } else {
Matt Arsenault73e06fa2015-06-04 16:17:42 +00001165 llvm_unreachable("unhandled address space");
1166 }
Matt Arsenault5015a892014-08-15 17:17:07 +00001167}
1168
Nirav Dave4dcad5d2017-07-10 20:25:54 +00001169bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1170 const SelectionDAG &DAG) const {
Matt Arsenault0da63502018-08-31 05:49:54 +00001171 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
Nirav Daved20066c2017-05-24 15:59:09 +00001172 return (MemVT.getSizeInBits() <= 4 * 32);
Matt Arsenault0da63502018-08-31 05:49:54 +00001173 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
Nirav Daved20066c2017-05-24 15:59:09 +00001174 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1175 return (MemVT.getSizeInBits() <= MaxPrivateBits);
Matt Arsenault0da63502018-08-31 05:49:54 +00001176 } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
Nirav Daved20066c2017-05-24 15:59:09 +00001177 return (MemVT.getSizeInBits() <= 2 * 32);
1178 }
1179 return true;
1180}
1181
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00001182bool SITargetLowering::allowsMisalignedMemoryAccesses(
1183 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1184 bool *IsFast) const {
Matt Arsenault1018c892014-04-24 17:08:26 +00001185 if (IsFast)
1186 *IsFast = false;
1187
Matt Arsenault1018c892014-04-24 17:08:26 +00001188 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1189 // which isn't a simple VT.
Alina Sbirlea6f937b12016-08-04 16:38:44 +00001190 // Until MVT is extended to handle this, simply check for the size and
1191 // rely on the condition below: allow accesses if the size is a multiple of 4.
1192 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1193 VT.getStoreSize() > 16)) {
Tom Stellard81d871d2013-11-13 23:36:50 +00001194 return false;
Alina Sbirlea6f937b12016-08-04 16:38:44 +00001195 }
Matt Arsenault1018c892014-04-24 17:08:26 +00001196
Matt Arsenault0da63502018-08-31 05:49:54 +00001197 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1198 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
Matt Arsenault6f2a5262014-07-27 17:46:40 +00001199 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1200 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1201 // with adjacent offsets.
Sanjay Patelce74db92015-09-03 15:03:19 +00001202 bool AlignedBy4 = (Align % 4 == 0);
1203 if (IsFast)
1204 *IsFast = AlignedBy4;
Matt Arsenault7f681ac2016-07-01 23:03:44 +00001205
Sanjay Patelce74db92015-09-03 15:03:19 +00001206 return AlignedBy4;
Matt Arsenault6f2a5262014-07-27 17:46:40 +00001207 }
Matt Arsenault1018c892014-04-24 17:08:26 +00001208
Tom Stellard64a9d082016-10-14 18:10:39 +00001209 // FIXME: We have to be conservative here and assume that flat operations
1210 // will access scratch. If we had access to the IR function, then we
1211 // could determine if any private memory was used in the function.
1212 if (!Subtarget->hasUnalignedScratchAccess() &&
Matt Arsenault0da63502018-08-31 05:49:54 +00001213 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1214 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
Matt Arsenaultf4320112018-09-24 13:18:15 +00001215 bool AlignedBy4 = Align >= 4;
1216 if (IsFast)
1217 *IsFast = AlignedBy4;
1218
1219 return AlignedBy4;
Tom Stellard64a9d082016-10-14 18:10:39 +00001220 }
1221
Matt Arsenault7f681ac2016-07-01 23:03:44 +00001222 if (Subtarget->hasUnalignedBufferAccess()) {
1223 // If we have an uniform constant load, it still requires using a slow
1224 // buffer instruction if unaligned.
1225 if (IsFast) {
Matt Arsenault0da63502018-08-31 05:49:54 +00001226 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1227 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
Matt Arsenault7f681ac2016-07-01 23:03:44 +00001228 (Align % 4 == 0) : true;
1229 }
1230
1231 return true;
1232 }
1233
Tom Stellard33e64c62015-02-04 20:49:52 +00001234 // Smaller than dword value must be aligned.
Tom Stellard33e64c62015-02-04 20:49:52 +00001235 if (VT.bitsLT(MVT::i32))
1236 return false;
1237
Matt Arsenault1018c892014-04-24 17:08:26 +00001238 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1239 // byte-address are ignored, thus forcing Dword alignment.
Tom Stellarde812f2f2014-07-21 15:45:06 +00001240 // This applies to private, global, and constant memory.
Matt Arsenault1018c892014-04-24 17:08:26 +00001241 if (IsFast)
1242 *IsFast = true;
Tom Stellardc6b299c2015-02-02 18:02:28 +00001243
1244 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
Tom Stellard0125f2a2013-06-25 02:39:35 +00001245}
1246
Sjoerd Meijer180f1ae2019-04-30 08:38:12 +00001247EVT SITargetLowering::getOptimalMemOpType(
1248 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
1249 bool ZeroMemset, bool MemcpyStrSrc,
1250 const AttributeList &FuncAttributes) const {
Matt Arsenault46645fa2014-07-28 17:49:26 +00001251 // FIXME: Should account for address space here.
1252
1253 // The default fallback uses the private pointer size as a guess for a type to
1254 // use. Make sure we switch these to 64-bit accesses.
1255
1256 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1257 return MVT::v4i32;
1258
1259 if (Size >= 8 && DstAlign >= 4)
1260 return MVT::v2i32;
1261
1262 // Use the default.
1263 return MVT::Other;
1264}
1265
Matt Arsenault0da63502018-08-31 05:49:54 +00001266static bool isFlatGlobalAddrSpace(unsigned AS) {
1267 return AS == AMDGPUAS::GLOBAL_ADDRESS ||
1268 AS == AMDGPUAS::FLAT_ADDRESS ||
Matt Arsenaulta8b43392019-02-08 02:40:47 +00001269 AS == AMDGPUAS::CONSTANT_ADDRESS ||
1270 AS > AMDGPUAS::MAX_AMDGPU_ADDRESS;
Matt Arsenaultf9bfeaf2015-12-01 23:04:00 +00001271}
1272
1273bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1274 unsigned DestAS) const {
Matt Arsenault0da63502018-08-31 05:49:54 +00001275 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
Matt Arsenaultf9bfeaf2015-12-01 23:04:00 +00001276}
1277
Alexander Timofeev18009562016-12-08 17:28:47 +00001278bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1279 const MemSDNode *MemNode = cast<MemSDNode>(N);
1280 const Value *Ptr = MemNode->getMemOperand()->getValue();
Matt Arsenault0a0c8712018-03-27 18:39:45 +00001281 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
Alexander Timofeev18009562016-12-08 17:28:47 +00001282 return I && I->getMetadata("amdgpu.noclobber");
1283}
1284
Matt Arsenault8dbeb922019-06-03 18:41:34 +00001285bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1286 unsigned DestAS) const {
Matt Arsenaultd4da0ed2016-12-02 18:12:53 +00001287 // Flat -> private/local is a simple truncate.
1288 // Flat -> global is no-op
Matt Arsenault0da63502018-08-31 05:49:54 +00001289 if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
Matt Arsenaultd4da0ed2016-12-02 18:12:53 +00001290 return true;
1291
1292 return isNoopAddrSpaceCast(SrcAS, DestAS);
1293}
1294
Tom Stellarda6f24c62015-12-15 20:55:55 +00001295bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1296 const MemSDNode *MemNode = cast<MemSDNode>(N);
Tom Stellarda6f24c62015-12-15 20:55:55 +00001297
Matt Arsenaultbcf7bec2018-02-09 16:57:48 +00001298 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
Tom Stellarda6f24c62015-12-15 20:55:55 +00001299}
1300
Chandler Carruth9d010ff2014-07-03 00:23:43 +00001301TargetLoweringBase::LegalizeTypeAction
Craig Topper0b5f8162018-11-05 23:26:13 +00001302SITargetLowering::getPreferredVectorAction(MVT VT) const {
Chandler Carruth9d010ff2014-07-03 00:23:43 +00001303 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1304 return TypeSplitVector;
1305
1306 return TargetLoweringBase::getPreferredVectorAction(VT);
Tom Stellardd86003e2013-08-14 23:25:00 +00001307}
Tom Stellard0125f2a2013-06-25 02:39:35 +00001308
Matt Arsenaultd7bdcc42014-03-31 19:54:27 +00001309bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1310 Type *Ty) const {
Matt Arsenault749035b2016-07-30 01:40:36 +00001311 // FIXME: Could be smarter if called for vector constants.
1312 return true;
Matt Arsenaultd7bdcc42014-03-31 19:54:27 +00001313}
1314
Tom Stellard2e045bb2016-01-20 00:13:22 +00001315bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
Matt Arsenault7b00cf42016-12-09 17:57:43 +00001316 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1317 switch (Op) {
1318 case ISD::LOAD:
1319 case ISD::STORE:
Tom Stellard2e045bb2016-01-20 00:13:22 +00001320
Matt Arsenault7b00cf42016-12-09 17:57:43 +00001321 // These operations are done with 32-bit instructions anyway.
1322 case ISD::AND:
1323 case ISD::OR:
1324 case ISD::XOR:
1325 case ISD::SELECT:
1326 // TODO: Extensions?
1327 return true;
1328 default:
1329 return false;
1330 }
1331 }
Konstantin Zhuravlyove14df4b2016-09-28 20:05:39 +00001332
Tom Stellard2e045bb2016-01-20 00:13:22 +00001333 // SimplifySetCC uses this function to determine whether or not it should
1334 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1335 if (VT == MVT::i1 && Op == ISD::SETCC)
1336 return false;
1337
1338 return TargetLowering::isTypeDesirableForOp(Op, VT);
1339}
1340
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001341SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1342 const SDLoc &SL,
1343 SDValue Chain,
1344 uint64_t Offset) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00001345 const DataLayout &DL = DAG.getDataLayout();
Tom Stellardec2e43c2014-09-22 15:35:29 +00001346 MachineFunction &MF = DAG.getMachineFunction();
Matt Arsenault8623e8d2017-08-03 23:00:29 +00001347 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1348
1349 const ArgDescriptor *InputPtrReg;
1350 const TargetRegisterClass *RC;
1351
1352 std::tie(InputPtrReg, RC)
1353 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
Tom Stellard94593ee2013-06-03 17:40:18 +00001354
Matt Arsenault86033ca2014-07-28 17:31:39 +00001355 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
Matt Arsenault0da63502018-08-31 05:49:54 +00001356 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
Matt Arsenaulta0269b62015-06-01 21:58:24 +00001357 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
Matt Arsenault8623e8d2017-08-03 23:00:29 +00001358 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1359
Matt Arsenault2fb9ccf2018-05-29 17:42:38 +00001360 return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
Jan Veselyfea814d2016-06-21 20:46:20 +00001361}
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +00001362
Matt Arsenault9166ce82017-07-28 15:52:08 +00001363SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1364 const SDLoc &SL) const {
Matt Arsenault75e71922018-06-28 10:18:55 +00001365 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1366 FIRST_IMPLICIT);
Matt Arsenault9166ce82017-07-28 15:52:08 +00001367 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1368}
1369
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001370SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1371 const SDLoc &SL, SDValue Val,
1372 bool Signed,
Matt Arsenault6dca5422017-01-09 18:52:39 +00001373 const ISD::InputArg *Arg) const {
Tim Renouf361b5b22019-03-21 12:01:21 +00001374 // First, if it is a widened vector, narrow it.
1375 if (VT.isVector() &&
1376 VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1377 EVT NarrowedVT =
1378 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1379 VT.getVectorNumElements());
1380 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1381 DAG.getConstant(0, SL, MVT::i32));
1382 }
1383
1384 // Then convert the vector elements or scalar value.
Matt Arsenault6dca5422017-01-09 18:52:39 +00001385 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1386 VT.bitsLT(MemVT)) {
1387 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1388 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1389 }
1390
Tom Stellardbc6c5232016-10-17 16:21:45 +00001391 if (MemVT.isFloatingPoint())
Matt Arsenault6dca5422017-01-09 18:52:39 +00001392 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
Tom Stellardbc6c5232016-10-17 16:21:45 +00001393 else if (Signed)
Matt Arsenault6dca5422017-01-09 18:52:39 +00001394 Val = DAG.getSExtOrTrunc(Val, SL, VT);
Tom Stellardbc6c5232016-10-17 16:21:45 +00001395 else
Matt Arsenault6dca5422017-01-09 18:52:39 +00001396 Val = DAG.getZExtOrTrunc(Val, SL, VT);
Tom Stellardbc6c5232016-10-17 16:21:45 +00001397
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001398 return Val;
1399}
1400
1401SDValue SITargetLowering::lowerKernargMemParameter(
1402 SelectionDAG &DAG, EVT VT, EVT MemVT,
1403 const SDLoc &SL, SDValue Chain,
Matt Arsenault7b4826e2018-05-30 16:17:51 +00001404 uint64_t Offset, unsigned Align, bool Signed,
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001405 const ISD::InputArg *Arg) const {
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001406 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
Matt Arsenault0da63502018-08-31 05:49:54 +00001407 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001408 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1409
Matt Arsenault90083d32018-06-07 09:54:49 +00001410 // Try to avoid using an extload by loading earlier than the argument address,
1411 // and extracting the relevant bits. The load should hopefully be merged with
1412 // the previous argument.
Matt Arsenault4bec7d42018-07-20 09:05:08 +00001413 if (MemVT.getStoreSize() < 4 && Align < 4) {
1414 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
Matt Arsenault90083d32018-06-07 09:54:49 +00001415 int64_t AlignDownOffset = alignDown(Offset, 4);
1416 int64_t OffsetDiff = Offset - AlignDownOffset;
1417
1418 EVT IntVT = MemVT.changeTypeToInteger();
1419
1420 // TODO: If we passed in the base kernel offset we could have a better
1421 // alignment than 4, but we don't really need it.
1422 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1423 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1424 MachineMemOperand::MODereferenceable |
1425 MachineMemOperand::MOInvariant);
1426
1427 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1428 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1429
1430 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1431 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1432 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1433
1434
1435 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1436 }
1437
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001438 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1439 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001440 MachineMemOperand::MODereferenceable |
1441 MachineMemOperand::MOInvariant);
1442
1443 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
Matt Arsenault6dca5422017-01-09 18:52:39 +00001444 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
Tom Stellard94593ee2013-06-03 17:40:18 +00001445}
1446
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00001447SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1448 const SDLoc &SL, SDValue Chain,
1449 const ISD::InputArg &Arg) const {
1450 MachineFunction &MF = DAG.getMachineFunction();
1451 MachineFrameInfo &MFI = MF.getFrameInfo();
1452
1453 if (Arg.Flags.isByVal()) {
1454 unsigned Size = Arg.Flags.getByValSize();
1455 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1456 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1457 }
1458
1459 unsigned ArgOffset = VA.getLocMemOffset();
1460 unsigned ArgSize = VA.getValVT().getStoreSize();
1461
1462 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1463
1464 // Create load nodes to retrieve arguments from the stack.
1465 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1466 SDValue ArgValue;
1467
1468 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1469 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1470 MVT MemVT = VA.getValVT();
1471
1472 switch (VA.getLocInfo()) {
1473 default:
1474 break;
1475 case CCValAssign::BCvt:
1476 MemVT = VA.getLocVT();
1477 break;
1478 case CCValAssign::SExt:
1479 ExtType = ISD::SEXTLOAD;
1480 break;
1481 case CCValAssign::ZExt:
1482 ExtType = ISD::ZEXTLOAD;
1483 break;
1484 case CCValAssign::AExt:
1485 ExtType = ISD::EXTLOAD;
1486 break;
1487 }
1488
1489 ArgValue = DAG.getExtLoad(
1490 ExtType, SL, VA.getLocVT(), Chain, FIN,
1491 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1492 MemVT);
1493 return ArgValue;
1494}
1495
Matt Arsenault8623e8d2017-08-03 23:00:29 +00001496SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1497 const SIMachineFunctionInfo &MFI,
1498 EVT VT,
1499 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1500 const ArgDescriptor *Reg;
1501 const TargetRegisterClass *RC;
1502
1503 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1504 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1505}
1506
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001507static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1508 CallingConv::ID CallConv,
1509 ArrayRef<ISD::InputArg> Ins,
1510 BitVector &Skipped,
1511 FunctionType *FType,
1512 SIMachineFunctionInfo *Info) {
1513 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
Matt Arsenaultd362b6a2018-07-13 16:40:37 +00001514 const ISD::InputArg *Arg = &Ins[I];
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001515
Matt Arsenault55ab9212018-08-01 19:57:34 +00001516 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1517 "vector type argument should have been split");
Matt Arsenault9ced1e02018-07-31 19:05:14 +00001518
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001519 // First check if it's a PS input addr.
Matt Arsenaultd362b6a2018-07-13 16:40:37 +00001520 if (CallConv == CallingConv::AMDGPU_PS &&
1521 !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) {
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001522
Matt Arsenaultd362b6a2018-07-13 16:40:37 +00001523 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1524
1525 // Inconveniently only the first part of the split is marked as isSplit,
1526 // so skip to the end. We only want to increment PSInputNum once for the
1527 // entire split argument.
1528 if (Arg->Flags.isSplit()) {
1529 while (!Arg->Flags.isSplitEnd()) {
1530 assert(!Arg->VT.isVector() &&
1531 "unexpected vector split in ps argument type");
1532 if (!SkipArg)
1533 Splits.push_back(*Arg);
1534 Arg = &Ins[++I];
1535 }
1536 }
1537
1538 if (SkipArg) {
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001539 // We can safely skip PS inputs.
Matt Arsenaultd362b6a2018-07-13 16:40:37 +00001540 Skipped.set(Arg->getOrigArgIndex());
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001541 ++PSInputNum;
1542 continue;
1543 }
1544
1545 Info->markPSInputAllocated(PSInputNum);
Matt Arsenaultd362b6a2018-07-13 16:40:37 +00001546 if (Arg->Used)
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001547 Info->markPSInputEnabled(PSInputNum);
1548
1549 ++PSInputNum;
1550 }
1551
Matt Arsenault9ced1e02018-07-31 19:05:14 +00001552 Splits.push_back(*Arg);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001553 }
1554}
1555
1556// Allocate special inputs passed in VGPRs.
Matt Arsenault8623e8d2017-08-03 23:00:29 +00001557static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1558 MachineFunction &MF,
1559 const SIRegisterInfo &TRI,
1560 SIMachineFunctionInfo &Info) {
1561 if (Info.hasWorkItemIDX()) {
1562 unsigned Reg = AMDGPU::VGPR0;
1563 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
Matt Arsenault8623e8d2017-08-03 23:00:29 +00001564
1565 CCInfo.AllocateReg(Reg);
1566 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1567 }
1568
1569 if (Info.hasWorkItemIDY()) {
1570 unsigned Reg = AMDGPU::VGPR1;
1571 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1572
Matt Arsenault8623e8d2017-08-03 23:00:29 +00001573 CCInfo.AllocateReg(Reg);
1574 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1575 }
1576
1577 if (Info.hasWorkItemIDZ()) {
1578 unsigned Reg = AMDGPU::VGPR2;
1579 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1580
Matt Arsenault8623e8d2017-08-03 23:00:29 +00001581 CCInfo.AllocateReg(Reg);
1582 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1583 }
1584}
1585
1586// Try to allocate a VGPR at the end of the argument list, or if no argument
1587// VGPRs are left allocating a stack slot.
1588static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1589 ArrayRef<MCPhysReg> ArgVGPRs
1590 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1591 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1592 if (RegIdx == ArgVGPRs.size()) {
1593 // Spill to stack required.
1594 int64_t Offset = CCInfo.AllocateStack(4, 4);
1595
1596 return ArgDescriptor::createStack(Offset);
1597 }
1598
1599 unsigned Reg = ArgVGPRs[RegIdx];
1600 Reg = CCInfo.AllocateReg(Reg);
1601 assert(Reg != AMDGPU::NoRegister);
1602
1603 MachineFunction &MF = CCInfo.getMachineFunction();
1604 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1605 return ArgDescriptor::createRegister(Reg);
1606}
1607
1608static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1609 const TargetRegisterClass *RC,
1610 unsigned NumArgRegs) {
1611 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1612 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1613 if (RegIdx == ArgSGPRs.size())
1614 report_fatal_error("ran out of SGPRs for arguments");
1615
1616 unsigned Reg = ArgSGPRs[RegIdx];
1617 Reg = CCInfo.AllocateReg(Reg);
1618 assert(Reg != AMDGPU::NoRegister);
1619
1620 MachineFunction &MF = CCInfo.getMachineFunction();
1621 MF.addLiveIn(Reg, RC);
1622 return ArgDescriptor::createRegister(Reg);
1623}
1624
1625static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1626 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1627}
1628
1629static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1630 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1631}
1632
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001633static void allocateSpecialInputVGPRs(CCState &CCInfo,
1634 MachineFunction &MF,
1635 const SIRegisterInfo &TRI,
1636 SIMachineFunctionInfo &Info) {
Matt Arsenault8623e8d2017-08-03 23:00:29 +00001637 if (Info.hasWorkItemIDX())
1638 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001639
Matt Arsenault8623e8d2017-08-03 23:00:29 +00001640 if (Info.hasWorkItemIDY())
1641 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001642
Matt Arsenault8623e8d2017-08-03 23:00:29 +00001643 if (Info.hasWorkItemIDZ())
1644 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1645}
1646
1647static void allocateSpecialInputSGPRs(CCState &CCInfo,
1648 MachineFunction &MF,
1649 const SIRegisterInfo &TRI,
1650 SIMachineFunctionInfo &Info) {
1651 auto &ArgInfo = Info.getArgInfo();
1652
1653 // TODO: Unify handling with private memory pointers.
1654
1655 if (Info.hasDispatchPtr())
1656 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1657
1658 if (Info.hasQueuePtr())
1659 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1660
1661 if (Info.hasKernargSegmentPtr())
1662 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1663
1664 if (Info.hasDispatchID())
1665 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1666
1667 // flat_scratch_init is not applicable for non-kernel functions.
1668
1669 if (Info.hasWorkGroupIDX())
1670 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1671
1672 if (Info.hasWorkGroupIDY())
1673 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1674
1675 if (Info.hasWorkGroupIDZ())
1676 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
Matt Arsenault817c2532017-08-03 23:12:44 +00001677
1678 if (Info.hasImplicitArgPtr())
1679 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001680}
1681
1682// Allocate special inputs passed in user SGPRs.
1683static void allocateHSAUserSGPRs(CCState &CCInfo,
1684 MachineFunction &MF,
1685 const SIRegisterInfo &TRI,
1686 SIMachineFunctionInfo &Info) {
Matt Arsenault10fc0622017-06-26 03:01:31 +00001687 if (Info.hasImplicitBufferPtr()) {
1688 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1689 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1690 CCInfo.AllocateReg(ImplicitBufferPtrReg);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001691 }
1692
1693 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1694 if (Info.hasPrivateSegmentBuffer()) {
1695 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1696 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1697 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1698 }
1699
1700 if (Info.hasDispatchPtr()) {
1701 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1702 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1703 CCInfo.AllocateReg(DispatchPtrReg);
1704 }
1705
1706 if (Info.hasQueuePtr()) {
1707 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1708 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1709 CCInfo.AllocateReg(QueuePtrReg);
1710 }
1711
1712 if (Info.hasKernargSegmentPtr()) {
1713 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1714 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1715 CCInfo.AllocateReg(InputPtrReg);
1716 }
1717
1718 if (Info.hasDispatchID()) {
1719 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1720 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1721 CCInfo.AllocateReg(DispatchIDReg);
1722 }
1723
1724 if (Info.hasFlatScratchInit()) {
1725 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1726 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1727 CCInfo.AllocateReg(FlatScratchInitReg);
1728 }
1729
1730 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1731 // these from the dispatch pointer.
1732}
1733
1734// Allocate special input registers that are initialized per-wave.
1735static void allocateSystemSGPRs(CCState &CCInfo,
1736 MachineFunction &MF,
1737 SIMachineFunctionInfo &Info,
Marek Olsak584d2c02017-05-04 22:25:20 +00001738 CallingConv::ID CallConv,
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001739 bool IsShader) {
1740 if (Info.hasWorkGroupIDX()) {
1741 unsigned Reg = Info.addWorkGroupIDX();
1742 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1743 CCInfo.AllocateReg(Reg);
1744 }
1745
1746 if (Info.hasWorkGroupIDY()) {
1747 unsigned Reg = Info.addWorkGroupIDY();
1748 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1749 CCInfo.AllocateReg(Reg);
1750 }
1751
1752 if (Info.hasWorkGroupIDZ()) {
1753 unsigned Reg = Info.addWorkGroupIDZ();
1754 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1755 CCInfo.AllocateReg(Reg);
1756 }
1757
1758 if (Info.hasWorkGroupInfo()) {
1759 unsigned Reg = Info.addWorkGroupInfo();
1760 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1761 CCInfo.AllocateReg(Reg);
1762 }
1763
1764 if (Info.hasPrivateSegmentWaveByteOffset()) {
1765 // Scratch wave offset passed in system SGPR.
1766 unsigned PrivateSegmentWaveByteOffsetReg;
1767
1768 if (IsShader) {
Marek Olsak584d2c02017-05-04 22:25:20 +00001769 PrivateSegmentWaveByteOffsetReg =
1770 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1771
1772 // This is true if the scratch wave byte offset doesn't have a fixed
1773 // location.
1774 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1775 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1776 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1777 }
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001778 } else
1779 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1780
1781 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1782 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1783 }
1784}
1785
1786static void reservePrivateMemoryRegs(const TargetMachine &TM,
1787 MachineFunction &MF,
1788 const SIRegisterInfo &TRI,
Matt Arsenault1cc47f82017-07-18 16:44:56 +00001789 SIMachineFunctionInfo &Info) {
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001790 // Now that we've figured out where the scratch register inputs are, see if
1791 // should reserve the arguments and use them directly.
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00001792 MachineFrameInfo &MFI = MF.getFrameInfo();
1793 bool HasStackObjects = MFI.hasStackObjects();
Matt Arsenaultb812b7a2019-06-05 22:20:47 +00001794 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001795
1796 // Record that we know we have non-spill stack objects so we don't need to
1797 // check all stack objects later.
1798 if (HasStackObjects)
1799 Info.setHasNonSpillStackObjects(true);
1800
1801 // Everything live out of a block is spilled with fast regalloc, so it's
1802 // almost certain that spilling will be required.
1803 if (TM.getOptLevel() == CodeGenOpt::None)
1804 HasStackObjects = true;
1805
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00001806 // For now assume stack access is needed in any callee functions, so we need
1807 // the scratch registers to pass in.
1808 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1809
Matt Arsenaultb812b7a2019-06-05 22:20:47 +00001810 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1811 // If we have stack objects, we unquestionably need the private buffer
1812 // resource. For the Code Object V2 ABI, this will be the first 4 user
1813 // SGPR inputs. We can reserve those and use them directly.
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001814
Matt Arsenaultb812b7a2019-06-05 22:20:47 +00001815 unsigned PrivateSegmentBufferReg =
1816 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1817 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001818 } else {
1819 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
Matt Arsenaultb812b7a2019-06-05 22:20:47 +00001820 // We tentatively reserve the last registers (skipping the last registers
1821 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1822 // we'll replace these with the ones immediately after those which were
1823 // really allocated. In the prologue copies will be inserted from the
1824 // argument to these reserved registers.
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001825
1826 // Without HSA, relocations are used for the scratch pointer and the
1827 // buffer resource setup is always inserted in the prologue. Scratch wave
1828 // offset is still in an input SGPR.
1829 Info.setScratchRSrcReg(ReservedBufferReg);
Matt Arsenaultb812b7a2019-06-05 22:20:47 +00001830 }
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001831
Matt Arsenault22e3dc62019-06-21 20:04:02 +00001832 // hasFP should be accurate for kernels even before the frame is finalized.
1833 if (ST.getFrameLowering()->hasFP(MF)) {
Matt Arsenaultb812b7a2019-06-05 22:20:47 +00001834 MachineRegisterInfo &MRI = MF.getRegInfo();
1835
1836 // Try to use s32 as the SP, but move it if it would interfere with input
1837 // arguments. This won't work with calls though.
1838 //
1839 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1840 // registers.
1841 if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1842 Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001843 } else {
Matt Arsenaultb812b7a2019-06-05 22:20:47 +00001844 assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1845
1846 if (MFI.hasCalls())
1847 report_fatal_error("call in graphics shader with too many input SGPRs");
1848
1849 for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1850 if (!MRI.isLiveIn(Reg)) {
1851 Info.setStackPtrOffsetReg(Reg);
1852 break;
1853 }
1854 }
1855
1856 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1857 report_fatal_error("failed to find register for SP");
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001858 }
Matt Arsenaultb812b7a2019-06-05 22:20:47 +00001859
Matt Arsenault22e3dc62019-06-21 20:04:02 +00001860 if (MFI.hasCalls()) {
1861 Info.setScratchWaveOffsetReg(AMDGPU::SGPR33);
1862 Info.setFrameOffsetReg(AMDGPU::SGPR33);
1863 } else {
1864 unsigned ReservedOffsetReg =
1865 TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1866 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1867 Info.setFrameOffsetReg(ReservedOffsetReg);
1868 }
Matt Arsenaultb812b7a2019-06-05 22:20:47 +00001869 } else if (RequiresStackAccess) {
1870 assert(!MFI.hasCalls());
1871 // We know there are accesses and they will be done relative to SP, so just
1872 // pin it to the input.
1873 //
1874 // FIXME: Should not do this if inline asm is reading/writing these
1875 // registers.
1876 unsigned PreloadedSP = Info.getPreloadedReg(
1877 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1878
1879 Info.setStackPtrOffsetReg(PreloadedSP);
1880 Info.setScratchWaveOffsetReg(PreloadedSP);
1881 Info.setFrameOffsetReg(PreloadedSP);
1882 } else {
1883 assert(!MFI.hasCalls());
1884
1885 // There may not be stack access at all. There may still be spills, or
1886 // access of a constant pointer (in which cases an extra copy will be
1887 // emitted in the prolog).
1888 unsigned ReservedOffsetReg
1889 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1890 Info.setStackPtrOffsetReg(ReservedOffsetReg);
1891 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1892 Info.setFrameOffsetReg(ReservedOffsetReg);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001893 }
1894}
1895
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00001896bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1897 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1898 return !Info->isEntryFunction();
1899}
1900
1901void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1902
1903}
1904
1905void SITargetLowering::insertCopiesSplitCSR(
1906 MachineBasicBlock *Entry,
1907 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1908 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1909
1910 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1911 if (!IStart)
1912 return;
1913
1914 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1915 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1916 MachineBasicBlock::iterator MBBI = Entry->begin();
1917 for (const MCPhysReg *I = IStart; *I; ++I) {
1918 const TargetRegisterClass *RC = nullptr;
1919 if (AMDGPU::SReg_64RegClass.contains(*I))
1920 RC = &AMDGPU::SGPR_64RegClass;
1921 else if (AMDGPU::SReg_32RegClass.contains(*I))
1922 RC = &AMDGPU::SGPR_32RegClass;
1923 else
1924 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1925
1926 unsigned NewVR = MRI->createVirtualRegister(RC);
1927 // Create copy from CSR to a virtual register.
1928 Entry->addLiveIn(*I);
1929 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1930 .addReg(*I);
1931
1932 // Insert the copy-back instructions right before the terminator.
1933 for (auto *Exit : Exits)
1934 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1935 TII->get(TargetOpcode::COPY), *I)
1936 .addReg(NewVR);
1937 }
1938}
1939
Christian Konig2c8f6d52013-03-07 09:03:52 +00001940SDValue SITargetLowering::LowerFormalArguments(
Eric Christopher7792e322015-01-30 23:24:40 +00001941 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001942 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1943 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Matt Arsenault43e92fe2016-06-24 06:30:11 +00001944 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
Christian Konig2c8f6d52013-03-07 09:03:52 +00001945
1946 MachineFunction &MF = DAG.getMachineFunction();
Matt Arsenaultceafc552018-05-29 17:42:50 +00001947 const Function &Fn = MF.getFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00001948 FunctionType *FType = MF.getFunction().getFunctionType();
Christian Konig99ee0f42013-03-07 09:04:14 +00001949 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
Christian Konig2c8f6d52013-03-07 09:03:52 +00001950
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001951 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
Oliver Stannard7e7d9832016-02-02 13:52:43 +00001952 DiagnosticInfoUnsupported NoGraphicsHSA(
Matthias Braunf1caa282017-12-15 22:22:58 +00001953 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
Matt Arsenaultd48da142015-11-02 23:23:02 +00001954 DAG.getContext()->diagnose(NoGraphicsHSA);
Diana Picus81bc3172016-05-26 15:24:55 +00001955 return DAG.getEntryNode();
Matt Arsenaultd48da142015-11-02 23:23:02 +00001956 }
1957
Christian Konig2c8f6d52013-03-07 09:03:52 +00001958 SmallVector<ISD::InputArg, 16> Splits;
Christian Konig2c8f6d52013-03-07 09:03:52 +00001959 SmallVector<CCValAssign, 16> ArgLocs;
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001960 BitVector Skipped(Ins.size());
Eric Christopherb5217502014-08-06 18:45:26 +00001961 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1962 *DAG.getContext());
Christian Konig2c8f6d52013-03-07 09:03:52 +00001963
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001964 bool IsShader = AMDGPU::isShader(CallConv);
Matt Arsenaultefa9f4b2017-04-11 22:29:28 +00001965 bool IsKernel = AMDGPU::isKernel(CallConv);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001966 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
Christian Konig99ee0f42013-03-07 09:04:14 +00001967
Matt Arsenaulte622dc32017-04-11 22:29:24 +00001968 if (IsShader) {
1969 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1970
1971 // At least one interpolation mode must be enabled or else the GPU will
1972 // hang.
1973 //
1974 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1975 // set PSInputAddr, the user wants to enable some bits after the compilation
1976 // based on run-time states. Since we can't know what the final PSInputEna
1977 // will look like, so we shouldn't do anything here and the user should take
1978 // responsibility for the correct programming.
1979 //
1980 // Otherwise, the following restrictions apply:
1981 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1982 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1983 // enabled too.
Tim Renoufc8ffffe2017-10-12 16:16:41 +00001984 if (CallConv == CallingConv::AMDGPU_PS) {
1985 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1986 ((Info->getPSInputAddr() & 0xF) == 0 &&
1987 Info->isPSInputAllocated(11))) {
1988 CCInfo.AllocateReg(AMDGPU::VGPR0);
1989 CCInfo.AllocateReg(AMDGPU::VGPR1);
1990 Info->markPSInputAllocated(0);
1991 Info->markPSInputEnabled(0);
1992 }
1993 if (Subtarget->isAmdPalOS()) {
1994 // For isAmdPalOS, the user does not enable some bits after compilation
1995 // based on run-time states; the register values being generated here are
1996 // the final ones set in hardware. Therefore we need to apply the
1997 // workaround to PSInputAddr and PSInputEnable together. (The case where
1998 // a bit is set in PSInputAddr but not PSInputEnable is where the
1999 // frontend set up an input arg for a particular interpolation mode, but
2000 // nothing uses that input arg. Really we should have an earlier pass
2001 // that removes such an arg.)
2002 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2003 if ((PsInputBits & 0x7F) == 0 ||
2004 ((PsInputBits & 0xF) == 0 &&
2005 (PsInputBits >> 11 & 1)))
2006 Info->markPSInputEnabled(
2007 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2008 }
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002009 }
2010
Tom Stellard2f3f9852017-01-25 01:25:13 +00002011 assert(!Info->hasDispatchPtr() &&
Tom Stellardf110f8f2016-04-14 16:27:03 +00002012 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2013 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2014 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2015 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2016 !Info->hasWorkItemIDZ());
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002017 } else if (IsKernel) {
2018 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002019 } else {
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002020 Splits.append(Ins.begin(), Ins.end());
Tom Stellardaf775432013-10-23 00:44:32 +00002021 }
2022
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002023 if (IsEntryFunc) {
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002024 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002025 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
Tom Stellard2f3f9852017-01-25 01:25:13 +00002026 }
2027
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002028 if (IsKernel) {
Tom Stellardbbeb45a2016-09-16 21:53:00 +00002029 analyzeFormalArgumentsCompute(CCInfo, Ins);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002030 } else {
2031 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2032 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2033 }
Christian Konig2c8f6d52013-03-07 09:03:52 +00002034
Matt Arsenaultcf13d182015-07-10 22:51:36 +00002035 SmallVector<SDValue, 16> Chains;
2036
Matt Arsenault7b4826e2018-05-30 16:17:51 +00002037 // FIXME: This is the minimum kernel argument alignment. We should improve
2038 // this to the maximum alignment of the arguments.
2039 //
2040 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2041 // kern arg offset.
2042 const unsigned KernelArgBaseAlign = 16;
Matt Arsenault7b4826e2018-05-30 16:17:51 +00002043
2044 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
Christian Konigb7be72d2013-05-17 09:46:48 +00002045 const ISD::InputArg &Arg = Ins[i];
Matt Arsenaultd362b6a2018-07-13 16:40:37 +00002046 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
Christian Konigb7be72d2013-05-17 09:46:48 +00002047 InVals.push_back(DAG.getUNDEF(Arg.VT));
Christian Konig99ee0f42013-03-07 09:04:14 +00002048 continue;
2049 }
2050
Christian Konig2c8f6d52013-03-07 09:03:52 +00002051 CCValAssign &VA = ArgLocs[ArgIdx++];
Craig Topper7f416c82014-11-16 21:17:18 +00002052 MVT VT = VA.getLocVT();
Tom Stellarded882c22013-06-03 17:40:11 +00002053
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002054 if (IsEntryFunc && VA.isMemLoc()) {
Tom Stellardaf775432013-10-23 00:44:32 +00002055 VT = Ins[i].VT;
Tom Stellardbbeb45a2016-09-16 21:53:00 +00002056 EVT MemVT = VA.getLocVT();
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002057
Matt Arsenault4bec7d42018-07-20 09:05:08 +00002058 const uint64_t Offset = VA.getLocMemOffset();
Matt Arsenault7b4826e2018-05-30 16:17:51 +00002059 unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002060
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002061 SDValue Arg = lowerKernargMemParameter(
Matt Arsenault7b4826e2018-05-30 16:17:51 +00002062 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
Matt Arsenaultcf13d182015-07-10 22:51:36 +00002063 Chains.push_back(Arg.getValue(1));
Tom Stellardca7ecf32014-08-22 18:49:31 +00002064
Craig Toppere3dcce92015-08-01 22:20:21 +00002065 auto *ParamTy =
Andrew Trick05938a52015-02-16 18:10:47 +00002066 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
Tom Stellard5bfbae52018-07-11 20:59:01 +00002067 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
Matt Arsenaultcdd191d2019-01-28 20:14:49 +00002068 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2069 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
Tom Stellardca7ecf32014-08-22 18:49:31 +00002070 // On SI local pointers are just offsets into LDS, so they are always
2071 // less than 16-bits. On CI and newer they could potentially be
2072 // real pointers, so we can't guarantee their size.
2073 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2074 DAG.getValueType(MVT::i16));
2075 }
2076
Tom Stellarded882c22013-06-03 17:40:11 +00002077 InVals.push_back(Arg);
2078 continue;
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002079 } else if (!IsEntryFunc && VA.isMemLoc()) {
2080 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2081 InVals.push_back(Val);
2082 if (!Arg.Flags.isByVal())
2083 Chains.push_back(Val.getValue(1));
2084 continue;
Tom Stellarded882c22013-06-03 17:40:11 +00002085 }
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002086
Christian Konig2c8f6d52013-03-07 09:03:52 +00002087 assert(VA.isRegLoc() && "Parameter must be in a register!");
2088
2089 unsigned Reg = VA.getLocReg();
Christian Konig2c8f6d52013-03-07 09:03:52 +00002090 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
Matt Arsenaultb3463552017-07-15 05:52:59 +00002091 EVT ValVT = VA.getValVT();
Christian Konig2c8f6d52013-03-07 09:03:52 +00002092
2093 Reg = MF.addLiveIn(Reg, RC);
2094 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2095
Matt Arsenault5c714cb2019-05-23 19:38:14 +00002096 if (Arg.Flags.isSRet()) {
Matt Arsenault45b98182017-11-15 00:45:43 +00002097 // The return object should be reasonably addressable.
2098
2099 // FIXME: This helps when the return is a real sret. If it is a
2100 // automatically inserted sret (i.e. CanLowerReturn returns false), an
2101 // extra copy is inserted in SelectionDAGBuilder which obscures this.
Matt Arsenault5c714cb2019-05-23 19:38:14 +00002102 unsigned NumBits
2103 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
Matt Arsenault45b98182017-11-15 00:45:43 +00002104 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2105 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2106 }
2107
Matt Arsenaultb3463552017-07-15 05:52:59 +00002108 // If this is an 8 or 16-bit value, it is really passed promoted
2109 // to 32 bits. Insert an assert[sz]ext to capture this, then
2110 // truncate to the right size.
2111 switch (VA.getLocInfo()) {
2112 case CCValAssign::Full:
2113 break;
2114 case CCValAssign::BCvt:
2115 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2116 break;
2117 case CCValAssign::SExt:
2118 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2119 DAG.getValueType(ValVT));
2120 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2121 break;
2122 case CCValAssign::ZExt:
2123 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2124 DAG.getValueType(ValVT));
2125 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2126 break;
2127 case CCValAssign::AExt:
2128 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2129 break;
2130 default:
2131 llvm_unreachable("Unknown loc info!");
2132 }
2133
Christian Konig2c8f6d52013-03-07 09:03:52 +00002134 InVals.push_back(Val);
2135 }
Tom Stellarde99fb652015-01-20 19:33:04 +00002136
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002137 if (!IsEntryFunc) {
2138 // Special inputs come after user arguments.
2139 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2140 }
2141
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002142 // Start adding system SGPRs.
2143 if (IsEntryFunc) {
2144 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002145 } else {
2146 CCInfo.AllocateReg(Info->getScratchRSrcReg());
2147 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2148 CCInfo.AllocateReg(Info->getFrameOffsetReg());
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002149 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002150 }
Matt Arsenaultcf13d182015-07-10 22:51:36 +00002151
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002152 auto &ArgUsageInfo =
2153 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
Matt Arsenaultceafc552018-05-29 17:42:50 +00002154 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002155
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002156 unsigned StackArgSize = CCInfo.getNextStackOffset();
2157 Info->setBytesInStackArgArea(StackArgSize);
2158
Matt Arsenaulte622dc32017-04-11 22:29:24 +00002159 return Chains.empty() ? Chain :
2160 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
Christian Konig2c8f6d52013-03-07 09:03:52 +00002161}
2162
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002163// TODO: If return values can't fit in registers, we should return as many as
2164// possible in registers before passing on stack.
2165bool SITargetLowering::CanLowerReturn(
2166 CallingConv::ID CallConv,
2167 MachineFunction &MF, bool IsVarArg,
2168 const SmallVectorImpl<ISD::OutputArg> &Outs,
2169 LLVMContext &Context) const {
2170 // Replacing returns with sret/stack usage doesn't make sense for shaders.
2171 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2172 // for shaders. Vector types should be explicitly handled by CC.
2173 if (AMDGPU::isEntryFunctionCC(CallConv))
2174 return true;
2175
2176 SmallVector<CCValAssign, 16> RVLocs;
2177 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2178 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2179}
2180
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002181SDValue
2182SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2183 bool isVarArg,
2184 const SmallVectorImpl<ISD::OutputArg> &Outs,
2185 const SmallVectorImpl<SDValue> &OutVals,
2186 const SDLoc &DL, SelectionDAG &DAG) const {
Marek Olsak8a0f3352016-01-13 17:23:04 +00002187 MachineFunction &MF = DAG.getMachineFunction();
2188 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2189
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002190 if (AMDGPU::isKernel(CallConv)) {
Marek Olsak8a0f3352016-01-13 17:23:04 +00002191 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2192 OutVals, DL, DAG);
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002193 }
2194
2195 bool IsShader = AMDGPU::isShader(CallConv);
Marek Olsak8a0f3352016-01-13 17:23:04 +00002196
Matt Arsenault55ab9212018-08-01 19:57:34 +00002197 Info->setIfReturnsVoid(Outs.empty());
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002198 bool IsWaveEnd = Info->returnsVoid() && IsShader;
Marek Olsak8e9cc632016-01-13 17:23:09 +00002199
Marek Olsak8a0f3352016-01-13 17:23:04 +00002200 // CCValAssign - represent the assignment of the return value to a location.
2201 SmallVector<CCValAssign, 48> RVLocs;
Matt Arsenault55ab9212018-08-01 19:57:34 +00002202 SmallVector<ISD::OutputArg, 48> Splits;
Marek Olsak8a0f3352016-01-13 17:23:04 +00002203
2204 // CCState - Info about the registers and stack slots.
2205 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2206 *DAG.getContext());
2207
2208 // Analyze outgoing return values.
Matt Arsenault55ab9212018-08-01 19:57:34 +00002209 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
Marek Olsak8a0f3352016-01-13 17:23:04 +00002210
2211 SDValue Flag;
2212 SmallVector<SDValue, 48> RetOps;
2213 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2214
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002215 // Add return address for callable functions.
2216 if (!Info->isEntryFunction()) {
2217 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2218 SDValue ReturnAddrReg = CreateLiveInRegister(
2219 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2220
2221 // FIXME: Should be able to use a vreg here, but need a way to prevent it
2222 // from being allcoated to a CSR.
2223
2224 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2225 MVT::i64);
2226
2227 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
2228 Flag = Chain.getValue(1);
2229
2230 RetOps.push_back(PhysReturnAddrReg);
2231 }
2232
Marek Olsak8a0f3352016-01-13 17:23:04 +00002233 // Copy the result values into the output registers.
Matt Arsenault55ab9212018-08-01 19:57:34 +00002234 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2235 ++I, ++RealRVLocIdx) {
2236 CCValAssign &VA = RVLocs[I];
Marek Olsak8a0f3352016-01-13 17:23:04 +00002237 assert(VA.isRegLoc() && "Can only return in registers!");
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002238 // TODO: Partially return in registers if return values don't fit.
Matt Arsenault55ab9212018-08-01 19:57:34 +00002239 SDValue Arg = OutVals[RealRVLocIdx];
Marek Olsak8a0f3352016-01-13 17:23:04 +00002240
2241 // Copied from other backends.
2242 switch (VA.getLocInfo()) {
Marek Olsak8a0f3352016-01-13 17:23:04 +00002243 case CCValAssign::Full:
2244 break;
2245 case CCValAssign::BCvt:
2246 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2247 break;
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002248 case CCValAssign::SExt:
2249 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2250 break;
2251 case CCValAssign::ZExt:
2252 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2253 break;
2254 case CCValAssign::AExt:
2255 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2256 break;
2257 default:
2258 llvm_unreachable("Unknown loc info!");
Marek Olsak8a0f3352016-01-13 17:23:04 +00002259 }
2260
2261 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2262 Flag = Chain.getValue(1);
2263 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2264 }
2265
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002266 // FIXME: Does sret work properly?
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002267 if (!Info->isEntryFunction()) {
Tom Stellardc5a154d2018-06-28 23:47:12 +00002268 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002269 const MCPhysReg *I =
2270 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2271 if (I) {
2272 for (; *I; ++I) {
2273 if (AMDGPU::SReg_64RegClass.contains(*I))
2274 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2275 else if (AMDGPU::SReg_32RegClass.contains(*I))
2276 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2277 else
2278 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2279 }
2280 }
2281 }
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002282
Marek Olsak8a0f3352016-01-13 17:23:04 +00002283 // Update chain and glue.
2284 RetOps[0] = Chain;
2285 if (Flag.getNode())
2286 RetOps.push_back(Flag);
2287
Matt Arsenault2b1f9aa2017-05-17 21:56:25 +00002288 unsigned Opc = AMDGPUISD::ENDPGM;
2289 if (!IsWaveEnd)
2290 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
Matt Arsenault9babdf42016-06-22 20:15:28 +00002291 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
Marek Olsak8a0f3352016-01-13 17:23:04 +00002292}
2293
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002294SDValue SITargetLowering::LowerCallResult(
2295 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2296 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2297 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2298 SDValue ThisVal) const {
2299 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2300
2301 // Assign locations to each value returned by this call.
2302 SmallVector<CCValAssign, 16> RVLocs;
2303 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2304 *DAG.getContext());
2305 CCInfo.AnalyzeCallResult(Ins, RetCC);
2306
2307 // Copy all of the result registers out of their specified physreg.
2308 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2309 CCValAssign VA = RVLocs[i];
2310 SDValue Val;
2311
2312 if (VA.isRegLoc()) {
2313 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2314 Chain = Val.getValue(1);
2315 InFlag = Val.getValue(2);
2316 } else if (VA.isMemLoc()) {
2317 report_fatal_error("TODO: return values in memory");
2318 } else
2319 llvm_unreachable("unknown argument location type");
2320
2321 switch (VA.getLocInfo()) {
2322 case CCValAssign::Full:
2323 break;
2324 case CCValAssign::BCvt:
2325 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2326 break;
2327 case CCValAssign::ZExt:
2328 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2329 DAG.getValueType(VA.getValVT()));
2330 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2331 break;
2332 case CCValAssign::SExt:
2333 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2334 DAG.getValueType(VA.getValVT()));
2335 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2336 break;
2337 case CCValAssign::AExt:
2338 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2339 break;
2340 default:
2341 llvm_unreachable("Unknown loc info!");
2342 }
2343
2344 InVals.push_back(Val);
2345 }
2346
2347 return Chain;
2348}
2349
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002350// Add code to pass special inputs required depending on used features separate
2351// from the explicit user arguments present in the IR.
2352void SITargetLowering::passSpecialInputs(
2353 CallLoweringInfo &CLI,
Matt Arsenaultbb8e64e2018-08-22 11:09:45 +00002354 CCState &CCInfo,
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002355 const SIMachineFunctionInfo &Info,
2356 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2357 SmallVectorImpl<SDValue> &MemOpChains,
Matt Arsenaultbb8e64e2018-08-22 11:09:45 +00002358 SDValue Chain) const {
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002359 // If we don't have a call site, this was a call inserted by
2360 // legalization. These can never use special inputs.
2361 if (!CLI.CS)
2362 return;
2363
2364 const Function *CalleeFunc = CLI.CS.getCalledFunction();
Matt Arsenaulta176cc52017-08-03 23:32:41 +00002365 assert(CalleeFunc);
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002366
2367 SelectionDAG &DAG = CLI.DAG;
2368 const SDLoc &DL = CLI.DL;
2369
Tom Stellardc5a154d2018-06-28 23:47:12 +00002370 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002371
2372 auto &ArgUsageInfo =
2373 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2374 const AMDGPUFunctionArgInfo &CalleeArgInfo
2375 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2376
2377 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2378
2379 // TODO: Unify with private memory register handling. This is complicated by
2380 // the fact that at least in kernels, the input argument is not necessarily
2381 // in the same location as the input.
2382 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2383 AMDGPUFunctionArgInfo::DISPATCH_PTR,
2384 AMDGPUFunctionArgInfo::QUEUE_PTR,
2385 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2386 AMDGPUFunctionArgInfo::DISPATCH_ID,
2387 AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2388 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2389 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2390 AMDGPUFunctionArgInfo::WORKITEM_ID_X,
2391 AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
Matt Arsenault817c2532017-08-03 23:12:44 +00002392 AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
2393 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002394 };
2395
2396 for (auto InputID : InputRegs) {
2397 const ArgDescriptor *OutgoingArg;
2398 const TargetRegisterClass *ArgRC;
2399
2400 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2401 if (!OutgoingArg)
2402 continue;
2403
2404 const ArgDescriptor *IncomingArg;
2405 const TargetRegisterClass *IncomingArgRC;
2406 std::tie(IncomingArg, IncomingArgRC)
2407 = CallerArgInfo.getPreloadedValue(InputID);
2408 assert(IncomingArgRC == ArgRC);
2409
2410 // All special arguments are ints for now.
2411 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
Matt Arsenault817c2532017-08-03 23:12:44 +00002412 SDValue InputReg;
2413
2414 if (IncomingArg) {
2415 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2416 } else {
2417 // The implicit arg ptr is special because it doesn't have a corresponding
2418 // input for kernels, and is computed from the kernarg segment pointer.
2419 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2420 InputReg = getImplicitArgPtr(DAG, DL);
2421 }
2422
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002423 if (OutgoingArg->isRegister()) {
2424 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2425 } else {
Matt Arsenaultbb8e64e2018-08-22 11:09:45 +00002426 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2427 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2428 SpecialArgOffset);
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002429 MemOpChains.push_back(ArgStore);
2430 }
2431 }
2432}
2433
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002434static bool canGuaranteeTCO(CallingConv::ID CC) {
2435 return CC == CallingConv::Fast;
2436}
2437
2438/// Return true if we might ever do TCO for calls with this calling convention.
2439static bool mayTailCallThisCC(CallingConv::ID CC) {
2440 switch (CC) {
2441 case CallingConv::C:
2442 return true;
2443 default:
2444 return canGuaranteeTCO(CC);
2445 }
2446}
2447
2448bool SITargetLowering::isEligibleForTailCallOptimization(
2449 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2450 const SmallVectorImpl<ISD::OutputArg> &Outs,
2451 const SmallVectorImpl<SDValue> &OutVals,
2452 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2453 if (!mayTailCallThisCC(CalleeCC))
2454 return false;
2455
2456 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00002457 const Function &CallerF = MF.getFunction();
2458 CallingConv::ID CallerCC = CallerF.getCallingConv();
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002459 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2460 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2461
2462 // Kernels aren't callable, and don't have a live in return address so it
2463 // doesn't make sense to do a tail call with entry functions.
2464 if (!CallerPreserved)
2465 return false;
2466
2467 bool CCMatch = CallerCC == CalleeCC;
2468
2469 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2470 if (canGuaranteeTCO(CalleeCC) && CCMatch)
2471 return true;
2472 return false;
2473 }
2474
2475 // TODO: Can we handle var args?
2476 if (IsVarArg)
2477 return false;
2478
Matthias Braunf1caa282017-12-15 22:22:58 +00002479 for (const Argument &Arg : CallerF.args()) {
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002480 if (Arg.hasByValAttr())
2481 return false;
2482 }
2483
2484 LLVMContext &Ctx = *DAG.getContext();
2485
2486 // Check that the call results are passed in the same way.
2487 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2488 CCAssignFnForCall(CalleeCC, IsVarArg),
2489 CCAssignFnForCall(CallerCC, IsVarArg)))
2490 return false;
2491
2492 // The callee has to preserve all registers the caller needs to preserve.
2493 if (!CCMatch) {
2494 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2495 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2496 return false;
2497 }
2498
2499 // Nothing more to check if the callee is taking no arguments.
2500 if (Outs.empty())
2501 return true;
2502
2503 SmallVector<CCValAssign, 16> ArgLocs;
2504 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2505
2506 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2507
2508 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2509 // If the stack arguments for this call do not fit into our own save area then
2510 // the call cannot be made tail.
2511 // TODO: Is this really necessary?
2512 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2513 return false;
2514
2515 const MachineRegisterInfo &MRI = MF.getRegInfo();
2516 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2517}
2518
2519bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2520 if (!CI->isTailCall())
2521 return false;
2522
2523 const Function *ParentFn = CI->getParent()->getParent();
2524 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2525 return false;
2526
2527 auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2528 return (Attr.getValueAsString() != "true");
2529}
2530
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002531// The wave scratch offset register is used as the global base pointer.
2532SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2533 SmallVectorImpl<SDValue> &InVals) const {
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002534 SelectionDAG &DAG = CLI.DAG;
2535 const SDLoc &DL = CLI.DL;
2536 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2537 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2538 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2539 SDValue Chain = CLI.Chain;
2540 SDValue Callee = CLI.Callee;
2541 bool &IsTailCall = CLI.IsTailCall;
2542 CallingConv::ID CallConv = CLI.CallConv;
2543 bool IsVarArg = CLI.IsVarArg;
2544 bool IsSibCall = false;
2545 bool IsThisReturn = false;
2546 MachineFunction &MF = DAG.getMachineFunction();
2547
Matt Arsenaulta176cc52017-08-03 23:32:41 +00002548 if (IsVarArg) {
2549 return lowerUnhandledCall(CLI, InVals,
2550 "unsupported call to variadic function ");
2551 }
2552
Matt Arsenault935f3b72018-08-08 16:58:39 +00002553 if (!CLI.CS.getInstruction())
2554 report_fatal_error("unsupported libcall legalization");
2555
Matt Arsenaulta176cc52017-08-03 23:32:41 +00002556 if (!CLI.CS.getCalledFunction()) {
2557 return lowerUnhandledCall(CLI, InVals,
2558 "unsupported indirect call to function ");
2559 }
2560
2561 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2562 return lowerUnhandledCall(CLI, InVals,
2563 "unsupported required tail call to function ");
2564 }
2565
Matt Arsenault1fb90132018-06-28 10:18:36 +00002566 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2567 // Note the issue is with the CC of the calling function, not of the call
2568 // itself.
2569 return lowerUnhandledCall(CLI, InVals,
2570 "unsupported call from graphics shader of function ");
2571 }
2572
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002573 if (IsTailCall) {
2574 IsTailCall = isEligibleForTailCallOptimization(
2575 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2576 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2577 report_fatal_error("failed to perform tail call elimination on a call "
2578 "site marked musttail");
2579 }
2580
2581 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2582
2583 // A sibling call is one where we're under the usual C ABI and not planning
2584 // to change that but can still do a tail call:
2585 if (!TailCallOpt && IsTailCall)
2586 IsSibCall = true;
2587
2588 if (IsTailCall)
2589 ++NumTailCalls;
2590 }
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002591
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002592 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2593
2594 // Analyze operands of the call, assigning locations to each operand.
2595 SmallVector<CCValAssign, 16> ArgLocs;
2596 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2597 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
Matt Arsenaultbb8e64e2018-08-22 11:09:45 +00002598
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002599 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2600
2601 // Get a count of how many bytes are to be pushed on the stack.
2602 unsigned NumBytes = CCInfo.getNextStackOffset();
2603
2604 if (IsSibCall) {
2605 // Since we're not changing the ABI to make this a tail call, the memory
2606 // operands are already available in the caller's incoming argument space.
2607 NumBytes = 0;
2608 }
2609
2610 // FPDiff is the byte offset of the call's argument area from the callee's.
2611 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2612 // by this amount for a tail call. In a sibling call it must be 0 because the
2613 // caller will deallocate the entire stack and the callee still expects its
2614 // arguments to begin at SP+0. Completely unused for non-tail calls.
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002615 int32_t FPDiff = 0;
2616 MachineFrameInfo &MFI = MF.getFrameInfo();
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002617 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2618
Matt Arsenault6efd0822017-09-14 17:14:57 +00002619 SDValue CallerSavedFP;
2620
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002621 // Adjust the stack pointer for the new arguments...
2622 // These operations are automatically eliminated by the prolog/epilog pass
2623 if (!IsSibCall) {
Matt Arsenaultdefe3712017-09-14 17:37:40 +00002624 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002625
Matt Arsenault99e6f4d2019-05-16 15:10:27 +00002626 SmallVector<SDValue, 4> CopyFromChains;
2627
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002628 // In the HSA case, this should be an identity copy.
2629 SDValue ScratchRSrcReg
2630 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2631 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
Matt Arsenault99e6f4d2019-05-16 15:10:27 +00002632 CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002633
Matt Arsenault6efd0822017-09-14 17:14:57 +00002634 if (!Info->isEntryFunction()) {
2635 // Avoid clobbering this function's FP value. In the current convention
2636 // callee will overwrite this, so do save/restore around the call site.
2637 CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2638 Info->getFrameOffsetReg(), MVT::i32);
Matt Arsenault99e6f4d2019-05-16 15:10:27 +00002639 CopyFromChains.push_back(CallerSavedFP.getValue(1));
Matt Arsenault6efd0822017-09-14 17:14:57 +00002640 }
Matt Arsenault99e6f4d2019-05-16 15:10:27 +00002641
2642 Chain = DAG.getTokenFactor(DL, CopyFromChains);
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002643 }
2644
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002645 SmallVector<SDValue, 8> MemOpChains;
2646 MVT PtrVT = MVT::i32;
2647
2648 // Walk the register/memloc assignments, inserting copies/loads.
2649 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2650 ++i, ++realArgIdx) {
2651 CCValAssign &VA = ArgLocs[i];
2652 SDValue Arg = OutVals[realArgIdx];
2653
2654 // Promote the value if needed.
2655 switch (VA.getLocInfo()) {
2656 case CCValAssign::Full:
2657 break;
2658 case CCValAssign::BCvt:
2659 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2660 break;
2661 case CCValAssign::ZExt:
2662 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2663 break;
2664 case CCValAssign::SExt:
2665 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2666 break;
2667 case CCValAssign::AExt:
2668 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2669 break;
2670 case CCValAssign::FPExt:
2671 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2672 break;
2673 default:
2674 llvm_unreachable("Unknown loc info!");
2675 }
2676
2677 if (VA.isRegLoc()) {
2678 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2679 } else {
2680 assert(VA.isMemLoc());
2681
2682 SDValue DstAddr;
2683 MachinePointerInfo DstInfo;
2684
2685 unsigned LocMemOffset = VA.getLocMemOffset();
2686 int32_t Offset = LocMemOffset;
Matt Arsenaultb655fa92017-11-29 01:25:12 +00002687
Matt Arsenaultbb8e64e2018-08-22 11:09:45 +00002688 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
Matt Arsenaultff987ac2018-09-13 12:14:31 +00002689 unsigned Align = 0;
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002690
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002691 if (IsTailCall) {
2692 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2693 unsigned OpSize = Flags.isByVal() ?
2694 Flags.getByValSize() : VA.getValVT().getStoreSize();
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002695
Matt Arsenaultff987ac2018-09-13 12:14:31 +00002696 // FIXME: We can have better than the minimum byval required alignment.
2697 Align = Flags.isByVal() ? Flags.getByValAlign() :
2698 MinAlign(Subtarget->getStackAlignment(), Offset);
2699
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002700 Offset = Offset + FPDiff;
2701 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2702
Matt Arsenaultbb8e64e2018-08-22 11:09:45 +00002703 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002704 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2705
2706 // Make sure any stack arguments overlapping with where we're storing
2707 // are loaded before this eventual operation. Otherwise they'll be
2708 // clobbered.
2709
2710 // FIXME: Why is this really necessary? This seems to just result in a
2711 // lot of code to copy the stack and write them back to the same
2712 // locations, which are supposed to be immutable?
2713 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2714 } else {
2715 DstAddr = PtrOff;
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002716 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
Matt Arsenaultff987ac2018-09-13 12:14:31 +00002717 Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset);
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002718 }
2719
2720 if (Outs[i].Flags.isByVal()) {
2721 SDValue SizeNode =
2722 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2723 SDValue Cpy = DAG.getMemcpy(
2724 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2725 /*isVol = */ false, /*AlwaysInline = */ true,
Yaxun Liuc5962262017-11-22 16:13:35 +00002726 /*isTailCall = */ false, DstInfo,
2727 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
Matt Arsenault0da63502018-08-31 05:49:54 +00002728 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS))));
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002729
2730 MemOpChains.push_back(Cpy);
2731 } else {
Matt Arsenaultff987ac2018-09-13 12:14:31 +00002732 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align);
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002733 MemOpChains.push_back(Store);
2734 }
2735 }
2736 }
2737
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002738 // Copy special input registers after user input arguments.
Matt Arsenaultbb8e64e2018-08-22 11:09:45 +00002739 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
Matt Arsenault8623e8d2017-08-03 23:00:29 +00002740
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002741 if (!MemOpChains.empty())
2742 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2743
2744 // Build a sequence of copy-to-reg nodes chained together with token chain
2745 // and flag operands which copy the outgoing args into the appropriate regs.
2746 SDValue InFlag;
2747 for (auto &RegToPass : RegsToPass) {
2748 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2749 RegToPass.second, InFlag);
2750 InFlag = Chain.getValue(1);
2751 }
2752
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002753
2754 SDValue PhysReturnAddrReg;
2755 if (IsTailCall) {
2756 // Since the return is being combined with the call, we need to pass on the
2757 // return address.
2758
2759 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2760 SDValue ReturnAddrReg = CreateLiveInRegister(
2761 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2762
2763 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2764 MVT::i64);
2765 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2766 InFlag = Chain.getValue(1);
2767 }
2768
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002769 // We don't usually want to end the call-sequence here because we would tidy
2770 // the frame up *after* the call, however in the ABI-changing tail-call case
2771 // we've carefully laid out the parameters so that when sp is reset they'll be
2772 // in the correct location.
2773 if (IsTailCall && !IsSibCall) {
2774 Chain = DAG.getCALLSEQ_END(Chain,
2775 DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2776 DAG.getTargetConstant(0, DL, MVT::i32),
2777 InFlag, DL);
2778 InFlag = Chain.getValue(1);
2779 }
2780
2781 std::vector<SDValue> Ops;
2782 Ops.push_back(Chain);
2783 Ops.push_back(Callee);
Scott Linderd19d1972019-02-04 20:00:07 +00002784 // Add a redundant copy of the callee global which will not be legalized, as
2785 // we need direct access to the callee later.
2786 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
2787 const GlobalValue *GV = GSD->getGlobal();
2788 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002789
2790 if (IsTailCall) {
2791 // Each tail call may have to adjust the stack by a different amount, so
2792 // this information must travel along with the operation for eventual
2793 // consumption by emitEpilogue.
2794 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002795
2796 Ops.push_back(PhysReturnAddrReg);
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002797 }
2798
2799 // Add argument registers to the end of the list so that they are known live
2800 // into the call.
2801 for (auto &RegToPass : RegsToPass) {
2802 Ops.push_back(DAG.getRegister(RegToPass.first,
2803 RegToPass.second.getValueType()));
2804 }
2805
2806 // Add a register mask operand representing the call-preserved registers.
2807
Tom Stellardc5a154d2018-06-28 23:47:12 +00002808 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002809 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2810 assert(Mask && "Missing call preserved mask for calling convention");
2811 Ops.push_back(DAG.getRegisterMask(Mask));
2812
2813 if (InFlag.getNode())
2814 Ops.push_back(InFlag);
2815
2816 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2817
2818 // If we're doing a tall call, use a TC_RETURN here rather than an
2819 // actual call instruction.
2820 if (IsTailCall) {
Matt Arsenault71bcbd42017-08-11 20:42:08 +00002821 MFI.setHasTailCall();
2822 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002823 }
2824
2825 // Returns a chain and a flag for retval copy to use.
2826 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2827 Chain = Call.getValue(0);
2828 InFlag = Call.getValue(1);
2829
Matt Arsenault6efd0822017-09-14 17:14:57 +00002830 if (CallerSavedFP) {
2831 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2832 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2833 InFlag = Chain.getValue(1);
2834 }
2835
Matt Arsenaultdefe3712017-09-14 17:37:40 +00002836 uint64_t CalleePopBytes = NumBytes;
2837 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00002838 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2839 InFlag, DL);
2840 if (!Ins.empty())
2841 InFlag = Chain.getValue(1);
2842
2843 // Handle result values, copying them out of physregs into vregs that we
2844 // return.
2845 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2846 InVals, IsThisReturn,
2847 IsThisReturn ? OutVals[0] : SDValue());
2848}
2849
Matt Arsenault9a10cea2016-01-26 04:29:24 +00002850unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2851 SelectionDAG &DAG) const {
2852 unsigned Reg = StringSwitch<unsigned>(RegName)
2853 .Case("m0", AMDGPU::M0)
2854 .Case("exec", AMDGPU::EXEC)
2855 .Case("exec_lo", AMDGPU::EXEC_LO)
2856 .Case("exec_hi", AMDGPU::EXEC_HI)
2857 .Case("flat_scratch", AMDGPU::FLAT_SCR)
2858 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2859 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2860 .Default(AMDGPU::NoRegister);
2861
2862 if (Reg == AMDGPU::NoRegister) {
2863 report_fatal_error(Twine("invalid register name \""
2864 + StringRef(RegName) + "\"."));
2865
2866 }
2867
Matt Arsenaulte4c2e9b2019-06-19 23:54:58 +00002868 if (!Subtarget->hasFlatScrRegister() &&
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00002869 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
Matt Arsenault9a10cea2016-01-26 04:29:24 +00002870 report_fatal_error(Twine("invalid register \""
2871 + StringRef(RegName) + "\" for subtarget."));
2872 }
2873
2874 switch (Reg) {
2875 case AMDGPU::M0:
2876 case AMDGPU::EXEC_LO:
2877 case AMDGPU::EXEC_HI:
2878 case AMDGPU::FLAT_SCR_LO:
2879 case AMDGPU::FLAT_SCR_HI:
2880 if (VT.getSizeInBits() == 32)
2881 return Reg;
2882 break;
2883 case AMDGPU::EXEC:
2884 case AMDGPU::FLAT_SCR:
2885 if (VT.getSizeInBits() == 64)
2886 return Reg;
2887 break;
2888 default:
2889 llvm_unreachable("missing register type checking");
2890 }
2891
2892 report_fatal_error(Twine("invalid type for register \""
2893 + StringRef(RegName) + "\"."));
2894}
2895
Matt Arsenault786724a2016-07-12 21:41:32 +00002896// If kill is not the last instruction, split the block so kill is always a
2897// proper terminator.
2898MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2899 MachineBasicBlock *BB) const {
2900 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2901
2902 MachineBasicBlock::iterator SplitPoint(&MI);
2903 ++SplitPoint;
2904
2905 if (SplitPoint == BB->end()) {
2906 // Don't bother with a new block.
Marek Olsakce76ea02017-10-24 10:27:13 +00002907 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
Matt Arsenault786724a2016-07-12 21:41:32 +00002908 return BB;
2909 }
2910
2911 MachineFunction *MF = BB->getParent();
2912 MachineBasicBlock *SplitBB
2913 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2914
Matt Arsenault786724a2016-07-12 21:41:32 +00002915 MF->insert(++MachineFunction::iterator(BB), SplitBB);
2916 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2917
Matt Arsenaultd40ded62016-07-22 17:01:15 +00002918 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
Matt Arsenault786724a2016-07-12 21:41:32 +00002919 BB->addSuccessor(SplitBB);
2920
Marek Olsakce76ea02017-10-24 10:27:13 +00002921 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
Matt Arsenault786724a2016-07-12 21:41:32 +00002922 return SplitBB;
2923}
2924
Matt Arsenault8ad1dec2019-06-20 20:54:32 +00002925// Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
2926// \p MI will be the only instruction in the loop body block. Otherwise, it will
2927// be the first instruction in the remainder block.
2928//
2929/// \returns { LoopBody, Remainder }
2930static std::pair<MachineBasicBlock *, MachineBasicBlock *>
2931splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
2932 MachineFunction *MF = MBB.getParent();
2933 MachineBasicBlock::iterator I(&MI);
2934
2935 // To insert the loop we need to split the block. Move everything after this
2936 // point to a new block, and insert a new empty block between the two.
2937 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2938 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2939 MachineFunction::iterator MBBI(MBB);
2940 ++MBBI;
2941
2942 MF->insert(MBBI, LoopBB);
2943 MF->insert(MBBI, RemainderBB);
2944
2945 LoopBB->addSuccessor(LoopBB);
2946 LoopBB->addSuccessor(RemainderBB);
2947
2948 // Move the rest of the block into a new block.
2949 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2950
2951 if (InstInLoop) {
2952 auto Next = std::next(I);
2953
2954 // Move instruction to loop body.
2955 LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
2956
2957 // Move the rest of the block.
2958 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
2959 } else {
2960 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2961 }
2962
2963 MBB.addSuccessor(LoopBB);
2964
2965 return std::make_pair(LoopBB, RemainderBB);
2966}
2967
2968MachineBasicBlock *
2969SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
2970 MachineBasicBlock *BB) const {
2971 const DebugLoc &DL = MI.getDebugLoc();
2972
2973 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
2974
2975 MachineBasicBlock *LoopBB;
2976 MachineBasicBlock *RemainderBB;
2977 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2978
2979 MachineBasicBlock::iterator Prev = std::prev(MI.getIterator());
2980
2981 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
2982
2983 MachineBasicBlock::iterator I = LoopBB->end();
Matt Arsenault8ad1dec2019-06-20 20:54:32 +00002984 MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
Matt Arsenault8ad1dec2019-06-20 20:54:32 +00002985
2986 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
2987 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
2988
2989 // Clear TRAP_STS.MEM_VIOL
2990 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
2991 .addImm(0)
2992 .addImm(EncodedReg);
2993
2994 // This is a pain, but we're not allowed to have physical register live-ins
2995 // yet. Insert a pair of copies if the VGPR0 hack is necessary.
Matt Arsenault740322f2019-06-20 21:11:42 +00002996 if (Src && TargetRegisterInfo::isPhysicalRegister(Src->getReg())) {
Matt Arsenault8ad1dec2019-06-20 20:54:32 +00002997 unsigned Data0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2998 BuildMI(*BB, std::next(Prev), DL, TII->get(AMDGPU::COPY), Data0)
2999 .add(*Src);
3000
3001 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::COPY), Src->getReg())
3002 .addReg(Data0);
3003
3004 MRI.setSimpleHint(Data0, Src->getReg());
3005 }
3006
3007 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_WAITCNT))
3008 .addImm(0);
3009
3010 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3011
3012 // Load and check TRAP_STS.MEM_VIOL
3013 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3014 .addImm(EncodedReg);
3015
3016 // FIXME: Do we need to use an isel pseudo that may clobber scc?
3017 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3018 .addReg(Reg, RegState::Kill)
3019 .addImm(0);
3020 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3021 .addMBB(LoopBB);
3022
3023 return RemainderBB;
3024}
3025
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003026// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3027// wavefront. If the value is uniform and just happens to be in a VGPR, this
3028// will only do one iteration. In the worst case, this will loop 64 times.
3029//
3030// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
Matt Arsenaultdcf0cfc2016-10-04 01:41:05 +00003031static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3032 const SIInstrInfo *TII,
3033 MachineRegisterInfo &MRI,
3034 MachineBasicBlock &OrigBB,
3035 MachineBasicBlock &LoopBB,
3036 const DebugLoc &DL,
3037 const MachineOperand &IdxReg,
3038 unsigned InitReg,
3039 unsigned ResultReg,
3040 unsigned PhiReg,
3041 unsigned InitSaveExecReg,
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003042 int Offset,
Changpeng Fangda38b5f2018-02-16 16:31:30 +00003043 bool UseGPRIdxMode,
3044 bool IsIndirectSrc) {
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003045 MachineFunction *MF = OrigBB.getParent();
3046 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3047 const SIRegisterInfo *TRI = ST.getRegisterInfo();
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003048 MachineBasicBlock::iterator I = LoopBB.begin();
3049
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003050 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3051 unsigned PhiExec = MRI.createVirtualRegister(BoolRC);
3052 unsigned NewExec = MRI.createVirtualRegister(BoolRC);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003053 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003054 unsigned CondReg = MRI.createVirtualRegister(BoolRC);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003055
3056 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3057 .addReg(InitReg)
3058 .addMBB(&OrigBB)
3059 .addReg(ResultReg)
3060 .addMBB(&LoopBB);
3061
3062 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3063 .addReg(InitSaveExecReg)
3064 .addMBB(&OrigBB)
3065 .addReg(NewExec)
3066 .addMBB(&LoopBB);
3067
3068 // Read the next variant <- also loop target.
3069 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3070 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3071
3072 // Compare the just read M0 value to all possible Idx values.
3073 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3074 .addReg(CurrentIdxReg)
Matt Arsenaultf0ba86a2016-07-21 09:40:57 +00003075 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003076
Changpeng Fangda38b5f2018-02-16 16:31:30 +00003077 // Update EXEC, save the original EXEC value to VCC.
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003078 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3079 : AMDGPU::S_AND_SAVEEXEC_B64),
3080 NewExec)
Changpeng Fangda38b5f2018-02-16 16:31:30 +00003081 .addReg(CondReg, RegState::Kill);
3082
3083 MRI.setSimpleHint(NewExec, CondReg);
3084
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003085 if (UseGPRIdxMode) {
3086 unsigned IdxReg;
3087 if (Offset == 0) {
3088 IdxReg = CurrentIdxReg;
3089 } else {
3090 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3091 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3092 .addReg(CurrentIdxReg, RegState::Kill)
3093 .addImm(Offset);
3094 }
Changpeng Fangda38b5f2018-02-16 16:31:30 +00003095 unsigned IdxMode = IsIndirectSrc ?
Dmitry Preobrazhenskyef920352019-02-27 13:12:12 +00003096 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
Changpeng Fangda38b5f2018-02-16 16:31:30 +00003097 MachineInstr *SetOn =
3098 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3099 .addReg(IdxReg, RegState::Kill)
3100 .addImm(IdxMode);
3101 SetOn->getOperand(3).setIsUndef();
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003102 } else {
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003103 // Move index from VCC into M0
3104 if (Offset == 0) {
3105 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3106 .addReg(CurrentIdxReg, RegState::Kill);
3107 } else {
3108 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3109 .addReg(CurrentIdxReg, RegState::Kill)
3110 .addImm(Offset);
3111 }
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003112 }
3113
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003114 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003115 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
Matt Arsenaultdcf0cfc2016-10-04 01:41:05 +00003116 MachineInstr *InsertPt =
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003117 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3118 : AMDGPU::S_XOR_B64_term), Exec)
3119 .addReg(Exec)
3120 .addReg(NewExec);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003121
3122 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3123 // s_cbranch_scc0?
3124
3125 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3126 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3127 .addMBB(&LoopBB);
Matt Arsenaultdcf0cfc2016-10-04 01:41:05 +00003128
3129 return InsertPt->getIterator();
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003130}
3131
3132// This has slightly sub-optimal regalloc when the source vector is killed by
3133// the read. The register allocator does not understand that the kill is
3134// per-workitem, so is kept alive for the whole loop so we end up not re-using a
3135// subregister from it, using 1 more VGPR than necessary. This was saved when
3136// this was expanded after register allocation.
Matt Arsenaultdcf0cfc2016-10-04 01:41:05 +00003137static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3138 MachineBasicBlock &MBB,
3139 MachineInstr &MI,
3140 unsigned InitResultReg,
3141 unsigned PhiReg,
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003142 int Offset,
Changpeng Fangda38b5f2018-02-16 16:31:30 +00003143 bool UseGPRIdxMode,
3144 bool IsIndirectSrc) {
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003145 MachineFunction *MF = MBB.getParent();
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003146 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3147 const SIRegisterInfo *TRI = ST.getRegisterInfo();
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003148 MachineRegisterInfo &MRI = MF->getRegInfo();
3149 const DebugLoc &DL = MI.getDebugLoc();
3150 MachineBasicBlock::iterator I(&MI);
3151
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003152 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003153 unsigned DstReg = MI.getOperand(0).getReg();
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003154 unsigned SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3155 unsigned TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3156 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3157 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003158
3159 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3160
3161 // Save the EXEC mask
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003162 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3163 .addReg(Exec);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003164
Matt Arsenault8ad1dec2019-06-20 20:54:32 +00003165 MachineBasicBlock *LoopBB;
3166 MachineBasicBlock *RemainderBB;
3167 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003168
3169 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3170
Matt Arsenaultdcf0cfc2016-10-04 01:41:05 +00003171 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3172 InitResultReg, DstReg, PhiReg, TmpExec,
Changpeng Fangda38b5f2018-02-16 16:31:30 +00003173 Offset, UseGPRIdxMode, IsIndirectSrc);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003174
3175 MachineBasicBlock::iterator First = RemainderBB->begin();
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003176 BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec)
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003177 .addReg(SaveExec);
3178
Matt Arsenaultdcf0cfc2016-10-04 01:41:05 +00003179 return InsPt;
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003180}
3181
3182// Returns subreg index, offset
3183static std::pair<unsigned, int>
3184computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3185 const TargetRegisterClass *SuperRC,
3186 unsigned VecReg,
3187 int Offset) {
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00003188 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003189
3190 // Skip out of bounds offsets, or else we would end up using an undefined
3191 // register.
3192 if (Offset >= NumElts || Offset < 0)
3193 return std::make_pair(AMDGPU::sub0, Offset);
3194
3195 return std::make_pair(AMDGPU::sub0 + Offset, 0);
3196}
3197
3198// Return true if the index is an SGPR and was set.
3199static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3200 MachineRegisterInfo &MRI,
3201 MachineInstr &MI,
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003202 int Offset,
3203 bool UseGPRIdxMode,
3204 bool IsIndirectSrc) {
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003205 MachineBasicBlock *MBB = MI.getParent();
3206 const DebugLoc &DL = MI.getDebugLoc();
3207 MachineBasicBlock::iterator I(&MI);
3208
3209 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3210 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3211
3212 assert(Idx->getReg() != AMDGPU::NoRegister);
3213
3214 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3215 return false;
3216
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003217 if (UseGPRIdxMode) {
3218 unsigned IdxMode = IsIndirectSrc ?
Dmitry Preobrazhenskyef920352019-02-27 13:12:12 +00003219 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003220 if (Offset == 0) {
3221 MachineInstr *SetOn =
Diana Picus116bbab2017-01-13 09:58:52 +00003222 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3223 .add(*Idx)
3224 .addImm(IdxMode);
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003225
Matt Arsenaultdac31db2016-10-13 12:45:16 +00003226 SetOn->getOperand(3).setIsUndef();
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003227 } else {
3228 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3229 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
Diana Picus116bbab2017-01-13 09:58:52 +00003230 .add(*Idx)
3231 .addImm(Offset);
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003232 MachineInstr *SetOn =
3233 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3234 .addReg(Tmp, RegState::Kill)
3235 .addImm(IdxMode);
3236
Matt Arsenaultdac31db2016-10-13 12:45:16 +00003237 SetOn->getOperand(3).setIsUndef();
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003238 }
3239
3240 return true;
3241 }
3242
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003243 if (Offset == 0) {
Matt Arsenault7d6b71d2017-02-21 22:50:41 +00003244 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3245 .add(*Idx);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003246 } else {
3247 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
Matt Arsenault7d6b71d2017-02-21 22:50:41 +00003248 .add(*Idx)
3249 .addImm(Offset);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003250 }
3251
3252 return true;
3253}
3254
3255// Control flow needs to be inserted if indexing with a VGPR.
3256static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3257 MachineBasicBlock &MBB,
Tom Stellard5bfbae52018-07-11 20:59:01 +00003258 const GCNSubtarget &ST) {
Matt Arsenaultdcf0cfc2016-10-04 01:41:05 +00003259 const SIInstrInfo *TII = ST.getInstrInfo();
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003260 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3261 MachineFunction *MF = MBB.getParent();
3262 MachineRegisterInfo &MRI = MF->getRegInfo();
3263
3264 unsigned Dst = MI.getOperand(0).getReg();
Nicolai Haehnlebd15c322016-10-14 09:03:04 +00003265 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003266 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3267
Nicolai Haehnlebd15c322016-10-14 09:03:04 +00003268 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003269
3270 unsigned SubReg;
3271 std::tie(SubReg, Offset)
Nicolai Haehnlebd15c322016-10-14 09:03:04 +00003272 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003273
Marek Olsake22fdb92017-03-21 17:00:32 +00003274 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003275
3276 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003277 MachineBasicBlock::iterator I(&MI);
3278 const DebugLoc &DL = MI.getDebugLoc();
3279
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003280 if (UseGPRIdxMode) {
3281 // TODO: Look at the uses to avoid the copy. This may require rescheduling
3282 // to avoid interfering with other uses, so probably requires a new
3283 // optimization pass.
3284 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
Nicolai Haehnlebd15c322016-10-14 09:03:04 +00003285 .addReg(SrcReg, RegState::Undef, SubReg)
3286 .addReg(SrcReg, RegState::Implicit)
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003287 .addReg(AMDGPU::M0, RegState::Implicit);
3288 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3289 } else {
3290 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
Nicolai Haehnlebd15c322016-10-14 09:03:04 +00003291 .addReg(SrcReg, RegState::Undef, SubReg)
3292 .addReg(SrcReg, RegState::Implicit);
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003293 }
3294
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003295 MI.eraseFromParent();
3296
3297 return &MBB;
3298 }
3299
3300 const DebugLoc &DL = MI.getDebugLoc();
3301 MachineBasicBlock::iterator I(&MI);
3302
3303 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3304 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3305
3306 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3307
Changpeng Fangda38b5f2018-02-16 16:31:30 +00003308 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3309 Offset, UseGPRIdxMode, true);
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003310 MachineBasicBlock *LoopBB = InsPt->getParent();
3311
3312 if (UseGPRIdxMode) {
3313 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
Nicolai Haehnlebd15c322016-10-14 09:03:04 +00003314 .addReg(SrcReg, RegState::Undef, SubReg)
3315 .addReg(SrcReg, RegState::Implicit)
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003316 .addReg(AMDGPU::M0, RegState::Implicit);
Changpeng Fangda38b5f2018-02-16 16:31:30 +00003317 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003318 } else {
3319 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
Nicolai Haehnlebd15c322016-10-14 09:03:04 +00003320 .addReg(SrcReg, RegState::Undef, SubReg)
3321 .addReg(SrcReg, RegState::Implicit);
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003322 }
3323
Nicolai Haehnlebd15c322016-10-14 09:03:04 +00003324 MI.eraseFromParent();
3325
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003326 return LoopBB;
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003327}
3328
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00003329static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3330 const TargetRegisterClass *VecRC) {
3331 switch (TRI.getRegSizeInBits(*VecRC)) {
3332 case 32: // 4 bytes
Nicolai Haehnlea7852092016-10-24 14:56:02 +00003333 return AMDGPU::V_MOVRELD_B32_V1;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00003334 case 64: // 8 bytes
Nicolai Haehnlea7852092016-10-24 14:56:02 +00003335 return AMDGPU::V_MOVRELD_B32_V2;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00003336 case 128: // 16 bytes
Nicolai Haehnlea7852092016-10-24 14:56:02 +00003337 return AMDGPU::V_MOVRELD_B32_V4;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00003338 case 256: // 32 bytes
Nicolai Haehnlea7852092016-10-24 14:56:02 +00003339 return AMDGPU::V_MOVRELD_B32_V8;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00003340 case 512: // 64 bytes
Nicolai Haehnlea7852092016-10-24 14:56:02 +00003341 return AMDGPU::V_MOVRELD_B32_V16;
3342 default:
3343 llvm_unreachable("unsupported size for MOVRELD pseudos");
3344 }
3345}
3346
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003347static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3348 MachineBasicBlock &MBB,
Tom Stellard5bfbae52018-07-11 20:59:01 +00003349 const GCNSubtarget &ST) {
Matt Arsenaultdcf0cfc2016-10-04 01:41:05 +00003350 const SIInstrInfo *TII = ST.getInstrInfo();
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003351 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3352 MachineFunction *MF = MBB.getParent();
3353 MachineRegisterInfo &MRI = MF->getRegInfo();
3354
3355 unsigned Dst = MI.getOperand(0).getReg();
3356 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3357 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3358 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3359 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3360 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3361
3362 // This can be an immediate, but will be folded later.
3363 assert(Val->getReg());
3364
3365 unsigned SubReg;
3366 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3367 SrcVec->getReg(),
3368 Offset);
Marek Olsake22fdb92017-03-21 17:00:32 +00003369 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003370
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003371 if (Idx->getReg() == AMDGPU::NoRegister) {
3372 MachineBasicBlock::iterator I(&MI);
3373 const DebugLoc &DL = MI.getDebugLoc();
3374
3375 assert(Offset == 0);
3376
3377 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
Diana Picus116bbab2017-01-13 09:58:52 +00003378 .add(*SrcVec)
3379 .add(*Val)
3380 .addImm(SubReg);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003381
3382 MI.eraseFromParent();
3383 return &MBB;
3384 }
3385
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003386 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003387 MachineBasicBlock::iterator I(&MI);
3388 const DebugLoc &DL = MI.getDebugLoc();
3389
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003390 if (UseGPRIdxMode) {
3391 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
Diana Picus116bbab2017-01-13 09:58:52 +00003392 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3393 .add(*Val)
3394 .addReg(Dst, RegState::ImplicitDefine)
3395 .addReg(SrcVec->getReg(), RegState::Implicit)
3396 .addReg(AMDGPU::M0, RegState::Implicit);
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003397
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003398 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3399 } else {
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00003400 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003401
Nicolai Haehnlea7852092016-10-24 14:56:02 +00003402 BuildMI(MBB, I, DL, MovRelDesc)
3403 .addReg(Dst, RegState::Define)
3404 .addReg(SrcVec->getReg())
Diana Picus116bbab2017-01-13 09:58:52 +00003405 .add(*Val)
Nicolai Haehnlea7852092016-10-24 14:56:02 +00003406 .addImm(SubReg - AMDGPU::sub0);
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003407 }
3408
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003409 MI.eraseFromParent();
3410 return &MBB;
3411 }
3412
3413 if (Val->isReg())
3414 MRI.clearKillFlags(Val->getReg());
3415
3416 const DebugLoc &DL = MI.getDebugLoc();
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003417
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003418 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3419
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003420 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
Changpeng Fangda38b5f2018-02-16 16:31:30 +00003421 Offset, UseGPRIdxMode, false);
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003422 MachineBasicBlock *LoopBB = InsPt->getParent();
Matt Arsenaultdcf0cfc2016-10-04 01:41:05 +00003423
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003424 if (UseGPRIdxMode) {
3425 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
Diana Picus116bbab2017-01-13 09:58:52 +00003426 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3427 .add(*Val) // src0
3428 .addReg(Dst, RegState::ImplicitDefine)
3429 .addReg(PhiReg, RegState::Implicit)
3430 .addReg(AMDGPU::M0, RegState::Implicit);
Changpeng Fangda38b5f2018-02-16 16:31:30 +00003431 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003432 } else {
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00003433 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003434
Nicolai Haehnlea7852092016-10-24 14:56:02 +00003435 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3436 .addReg(Dst, RegState::Define)
3437 .addReg(PhiReg)
Diana Picus116bbab2017-01-13 09:58:52 +00003438 .add(*Val)
Nicolai Haehnlea7852092016-10-24 14:56:02 +00003439 .addImm(SubReg - AMDGPU::sub0);
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003440 }
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003441
Nicolai Haehnlebd15c322016-10-14 09:03:04 +00003442 MI.eraseFromParent();
3443
Matt Arsenaultd486d3f2016-10-12 18:49:05 +00003444 return LoopBB;
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003445}
3446
Matt Arsenault786724a2016-07-12 21:41:32 +00003447MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3448 MachineInstr &MI, MachineBasicBlock *BB) const {
Tom Stellard244891d2016-12-20 15:52:17 +00003449
3450 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3451 MachineFunction *MF = BB->getParent();
3452 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3453
3454 if (TII->isMIMG(MI)) {
Matt Arsenault905f3512017-12-29 17:18:14 +00003455 if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3456 report_fatal_error("missing mem operand from MIMG instruction");
3457 }
Tom Stellard244891d2016-12-20 15:52:17 +00003458 // Add a memoperand for mimg instructions so that they aren't assumed to
3459 // be ordered memory instuctions.
3460
Tom Stellard244891d2016-12-20 15:52:17 +00003461 return BB;
3462 }
3463
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00003464 switch (MI.getOpcode()) {
Matt Arsenault301162c2017-11-15 21:51:43 +00003465 case AMDGPU::S_ADD_U64_PSEUDO:
3466 case AMDGPU::S_SUB_U64_PSEUDO: {
3467 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003468 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3469 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3470 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
Matt Arsenault301162c2017-11-15 21:51:43 +00003471 const DebugLoc &DL = MI.getDebugLoc();
3472
3473 MachineOperand &Dest = MI.getOperand(0);
3474 MachineOperand &Src0 = MI.getOperand(1);
3475 MachineOperand &Src1 = MI.getOperand(2);
3476
3477 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3478 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3479
3480 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003481 Src0, BoolRC, AMDGPU::sub0,
Matt Arsenault301162c2017-11-15 21:51:43 +00003482 &AMDGPU::SReg_32_XM0RegClass);
3483 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003484 Src0, BoolRC, AMDGPU::sub1,
Matt Arsenault301162c2017-11-15 21:51:43 +00003485 &AMDGPU::SReg_32_XM0RegClass);
3486
3487 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003488 Src1, BoolRC, AMDGPU::sub0,
Matt Arsenault301162c2017-11-15 21:51:43 +00003489 &AMDGPU::SReg_32_XM0RegClass);
3490 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003491 Src1, BoolRC, AMDGPU::sub1,
Matt Arsenault301162c2017-11-15 21:51:43 +00003492 &AMDGPU::SReg_32_XM0RegClass);
3493
3494 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3495
3496 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3497 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3498 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3499 .add(Src0Sub0)
3500 .add(Src1Sub0);
3501 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3502 .add(Src0Sub1)
3503 .add(Src1Sub1);
3504 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3505 .addReg(DestSub0)
3506 .addImm(AMDGPU::sub0)
3507 .addReg(DestSub1)
3508 .addImm(AMDGPU::sub1);
3509 MI.eraseFromParent();
3510 return BB;
3511 }
3512 case AMDGPU::SI_INIT_M0: {
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00003513 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
Matt Arsenault4ac341c2016-04-14 21:58:15 +00003514 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
Diana Picus116bbab2017-01-13 09:58:52 +00003515 .add(MI.getOperand(0));
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00003516 MI.eraseFromParent();
Matt Arsenault20711b72015-02-20 22:10:45 +00003517 return BB;
Matt Arsenault301162c2017-11-15 21:51:43 +00003518 }
Marek Olsak2d825902017-04-28 20:21:58 +00003519 case AMDGPU::SI_INIT_EXEC:
3520 // This should be before all vector instructions.
3521 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3522 AMDGPU::EXEC)
3523 .addImm(MI.getOperand(0).getImm());
3524 MI.eraseFromParent();
3525 return BB;
3526
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003527 case AMDGPU::SI_INIT_EXEC_LO:
3528 // This should be before all vector instructions.
3529 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3530 AMDGPU::EXEC_LO)
3531 .addImm(MI.getOperand(0).getImm());
3532 MI.eraseFromParent();
3533 return BB;
3534
Marek Olsak2d825902017-04-28 20:21:58 +00003535 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3536 // Extract the thread count from an SGPR input and set EXEC accordingly.
3537 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3538 //
3539 // S_BFE_U32 count, input, {shift, 7}
3540 // S_BFM_B64 exec, count, 0
3541 // S_CMP_EQ_U32 count, 64
3542 // S_CMOV_B64 exec, -1
3543 MachineInstr *FirstMI = &*BB->begin();
3544 MachineRegisterInfo &MRI = MF->getRegInfo();
3545 unsigned InputReg = MI.getOperand(0).getReg();
3546 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3547 bool Found = false;
3548
3549 // Move the COPY of the input reg to the beginning, so that we can use it.
3550 for (auto I = BB->begin(); I != &MI; I++) {
3551 if (I->getOpcode() != TargetOpcode::COPY ||
3552 I->getOperand(0).getReg() != InputReg)
3553 continue;
3554
3555 if (I == FirstMI) {
3556 FirstMI = &*++BB->begin();
3557 } else {
3558 I->removeFromParent();
3559 BB->insert(FirstMI, &*I);
3560 }
3561 Found = true;
3562 break;
3563 }
3564 assert(Found);
Davide Italiano0dcc0152017-05-11 19:58:52 +00003565 (void)Found;
Marek Olsak2d825902017-04-28 20:21:58 +00003566
3567 // This should be before all vector instructions.
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003568 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3569 bool isWave32 = getSubtarget()->isWave32();
3570 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
Marek Olsak2d825902017-04-28 20:21:58 +00003571 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3572 .addReg(InputReg)
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003573 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3574 BuildMI(*BB, FirstMI, DebugLoc(),
3575 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3576 Exec)
Marek Olsak2d825902017-04-28 20:21:58 +00003577 .addReg(CountReg)
3578 .addImm(0);
3579 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3580 .addReg(CountReg, RegState::Kill)
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003581 .addImm(getSubtarget()->getWavefrontSize());
3582 BuildMI(*BB, FirstMI, DebugLoc(),
3583 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3584 Exec)
Marek Olsak2d825902017-04-28 20:21:58 +00003585 .addImm(-1);
3586 MI.eraseFromParent();
3587 return BB;
3588 }
3589
Changpeng Fang01f60622016-03-15 17:28:44 +00003590 case AMDGPU::GET_GROUPSTATICSIZE: {
Nicolai Haehnle27101712019-06-25 11:52:30 +00003591 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3592 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00003593 DebugLoc DL = MI.getDebugLoc();
Matt Arsenault3c07c812016-07-22 17:01:33 +00003594 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
Diana Picus116bbab2017-01-13 09:58:52 +00003595 .add(MI.getOperand(0))
3596 .addImm(MFI->getLDSSize());
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00003597 MI.eraseFromParent();
Changpeng Fang01f60622016-03-15 17:28:44 +00003598 return BB;
3599 }
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003600 case AMDGPU::SI_INDIRECT_SRC_V1:
3601 case AMDGPU::SI_INDIRECT_SRC_V2:
3602 case AMDGPU::SI_INDIRECT_SRC_V4:
3603 case AMDGPU::SI_INDIRECT_SRC_V8:
3604 case AMDGPU::SI_INDIRECT_SRC_V16:
Matt Arsenaultdcf0cfc2016-10-04 01:41:05 +00003605 return emitIndirectSrc(MI, *BB, *getSubtarget());
Matt Arsenaultcb540bc2016-07-19 00:35:03 +00003606 case AMDGPU::SI_INDIRECT_DST_V1:
3607 case AMDGPU::SI_INDIRECT_DST_V2:
3608 case AMDGPU::SI_INDIRECT_DST_V4:
3609 case AMDGPU::SI_INDIRECT_DST_V8:
3610 case AMDGPU::SI_INDIRECT_DST_V16:
Matt Arsenaultdcf0cfc2016-10-04 01:41:05 +00003611 return emitIndirectDst(MI, *BB, *getSubtarget());
Marek Olsakce76ea02017-10-24 10:27:13 +00003612 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3613 case AMDGPU::SI_KILL_I1_PSEUDO:
Matt Arsenault786724a2016-07-12 21:41:32 +00003614 return splitKillBlock(MI, BB);
Matt Arsenault22e41792016-08-27 01:00:37 +00003615 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3616 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003617 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3618 const SIRegisterInfo *TRI = ST.getRegisterInfo();
Matt Arsenault22e41792016-08-27 01:00:37 +00003619
3620 unsigned Dst = MI.getOperand(0).getReg();
3621 unsigned Src0 = MI.getOperand(1).getReg();
3622 unsigned Src1 = MI.getOperand(2).getReg();
3623 const DebugLoc &DL = MI.getDebugLoc();
3624 unsigned SrcCond = MI.getOperand(3).getReg();
3625
3626 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3627 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003628 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3629 unsigned SrcCondCopy = MRI.createVirtualRegister(CondRC);
Matt Arsenault22e41792016-08-27 01:00:37 +00003630
Nicolai Haehnlece4ddd02017-09-29 15:37:31 +00003631 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3632 .addReg(SrcCond);
Matt Arsenault22e41792016-08-27 01:00:37 +00003633 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
Tim Renouf2e94f6e2019-03-18 19:25:39 +00003634 .addImm(0)
Matt Arsenault22e41792016-08-27 01:00:37 +00003635 .addReg(Src0, 0, AMDGPU::sub0)
Tim Renouf2e94f6e2019-03-18 19:25:39 +00003636 .addImm(0)
Matt Arsenault22e41792016-08-27 01:00:37 +00003637 .addReg(Src1, 0, AMDGPU::sub0)
Nicolai Haehnlece4ddd02017-09-29 15:37:31 +00003638 .addReg(SrcCondCopy);
Matt Arsenault22e41792016-08-27 01:00:37 +00003639 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
Tim Renouf2e94f6e2019-03-18 19:25:39 +00003640 .addImm(0)
Matt Arsenault22e41792016-08-27 01:00:37 +00003641 .addReg(Src0, 0, AMDGPU::sub1)
Tim Renouf2e94f6e2019-03-18 19:25:39 +00003642 .addImm(0)
Matt Arsenault22e41792016-08-27 01:00:37 +00003643 .addReg(Src1, 0, AMDGPU::sub1)
Nicolai Haehnlece4ddd02017-09-29 15:37:31 +00003644 .addReg(SrcCondCopy);
Matt Arsenault22e41792016-08-27 01:00:37 +00003645
3646 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3647 .addReg(DstLo)
3648 .addImm(AMDGPU::sub0)
3649 .addReg(DstHi)
3650 .addImm(AMDGPU::sub1);
3651 MI.eraseFromParent();
3652 return BB;
3653 }
Matt Arsenault327188a2016-12-15 21:57:11 +00003654 case AMDGPU::SI_BR_UNDEF: {
3655 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3656 const DebugLoc &DL = MI.getDebugLoc();
3657 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
Diana Picus116bbab2017-01-13 09:58:52 +00003658 .add(MI.getOperand(0));
Matt Arsenault327188a2016-12-15 21:57:11 +00003659 Br->getOperand(1).setIsUndef(true); // read undef SCC
3660 MI.eraseFromParent();
3661 return BB;
3662 }
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00003663 case AMDGPU::ADJCALLSTACKUP:
3664 case AMDGPU::ADJCALLSTACKDOWN: {
3665 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3666 MachineInstrBuilder MIB(*MF, &MI);
Matt Arsenaulte9f36792018-03-27 18:38:51 +00003667
3668 // Add an implicit use of the frame offset reg to prevent the restore copy
3669 // inserted after the call from being reorderd after stack operations in the
3670 // the caller's frame.
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00003671 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
Matt Arsenaulte9f36792018-03-27 18:38:51 +00003672 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3673 .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00003674 return BB;
3675 }
Scott Linderd19d1972019-02-04 20:00:07 +00003676 case AMDGPU::SI_CALL_ISEL: {
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00003677 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3678 const DebugLoc &DL = MI.getDebugLoc();
Scott Linderd19d1972019-02-04 20:00:07 +00003679
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00003680 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
Matt Arsenault6ed7b9b2017-08-02 01:31:28 +00003681
Matt Arsenault71bcbd42017-08-11 20:42:08 +00003682 MachineInstrBuilder MIB;
Scott Linderd19d1972019-02-04 20:00:07 +00003683 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
Matt Arsenault71bcbd42017-08-11 20:42:08 +00003684
Scott Linderd19d1972019-02-04 20:00:07 +00003685 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00003686 MIB.add(MI.getOperand(I));
Matt Arsenault6ed7b9b2017-08-02 01:31:28 +00003687
Chandler Carruthc73c0302018-08-16 21:30:05 +00003688 MIB.cloneMemRefs(MI);
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00003689 MI.eraseFromParent();
3690 return BB;
3691 }
Stanislav Mekhanoshin64399da2019-05-02 04:26:35 +00003692 case AMDGPU::V_ADD_I32_e32:
3693 case AMDGPU::V_SUB_I32_e32:
3694 case AMDGPU::V_SUBREV_I32_e32: {
3695 // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3696 const DebugLoc &DL = MI.getDebugLoc();
3697 unsigned Opc = MI.getOpcode();
3698
3699 bool NeedClampOperand = false;
3700 if (TII->pseudoToMCOpcode(Opc) == -1) {
3701 Opc = AMDGPU::getVOPe64(Opc);
3702 NeedClampOperand = true;
3703 }
3704
3705 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3706 if (TII->isVOP3(*I)) {
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00003707 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3708 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3709 I.addReg(TRI->getVCC(), RegState::Define);
Stanislav Mekhanoshin64399da2019-05-02 04:26:35 +00003710 }
3711 I.add(MI.getOperand(1))
3712 .add(MI.getOperand(2));
3713 if (NeedClampOperand)
3714 I.addImm(0); // clamp bit for e64 encoding
3715
3716 TII->legalizeOperands(*I);
3717
3718 MI.eraseFromParent();
3719 return BB;
3720 }
Matt Arsenault8ad1dec2019-06-20 20:54:32 +00003721 case AMDGPU::DS_GWS_INIT:
3722 case AMDGPU::DS_GWS_SEMA_V:
3723 case AMDGPU::DS_GWS_SEMA_BR:
3724 case AMDGPU::DS_GWS_SEMA_P:
Matt Arsenault740322f2019-06-20 21:11:42 +00003725 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
Matt Arsenault8ad1dec2019-06-20 20:54:32 +00003726 case AMDGPU::DS_GWS_BARRIER:
3727 if (getSubtarget()->hasGWSAutoReplay())
3728 return BB;
3729 return emitGWSMemViolTestLoop(MI, BB);
Changpeng Fang01f60622016-03-15 17:28:44 +00003730 default:
3731 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
Tom Stellard75aadc22012-12-11 21:25:42 +00003732 }
Tom Stellard75aadc22012-12-11 21:25:42 +00003733}
3734
Matt Arsenaulte11d8ac2017-10-13 21:10:22 +00003735bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3736 return isTypeLegal(VT.getScalarType());
3737}
3738
Matt Arsenault423bf3f2015-01-29 19:34:32 +00003739bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3740 // This currently forces unfolding various combinations of fsub into fma with
3741 // free fneg'd operands. As long as we have fast FMA (controlled by
3742 // isFMAFasterThanFMulAndFAdd), we should perform these.
3743
3744 // When fma is quarter rate, for f64 where add / sub are at best half rate,
3745 // most of these combines appear to be cycle neutral but save on instruction
3746 // count / code size.
3747 return true;
3748}
3749
Mehdi Amini44ede332015-07-09 02:09:04 +00003750EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3751 EVT VT) const {
Tom Stellard83747202013-07-18 21:43:53 +00003752 if (!VT.isVector()) {
3753 return MVT::i1;
3754 }
Matt Arsenault8596f712014-11-28 22:51:38 +00003755 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
Tom Stellard75aadc22012-12-11 21:25:42 +00003756}
3757
Matt Arsenault94163282016-12-22 16:36:25 +00003758MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3759 // TODO: Should i16 be used always if legal? For now it would force VALU
3760 // shifts.
3761 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
Christian Konig082a14a2013-03-18 11:34:05 +00003762}
3763
Matt Arsenault423bf3f2015-01-29 19:34:32 +00003764// Answering this is somewhat tricky and depends on the specific device which
3765// have different rates for fma or all f64 operations.
3766//
3767// v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3768// regardless of which device (although the number of cycles differs between
3769// devices), so it is always profitable for f64.
3770//
3771// v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3772// only on full rate devices. Normally, we should prefer selecting v_mad_f32
3773// which we can always do even without fused FP ops since it returns the same
3774// result as the separate operations and since it is always full
3775// rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3776// however does not support denormals, so we do report fma as faster if we have
3777// a fast fma device and require denormals.
3778//
Niels Ole Salscheiderd3a039f2013-08-10 10:38:54 +00003779bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3780 VT = VT.getScalarType();
3781
Niels Ole Salscheiderd3a039f2013-08-10 10:38:54 +00003782 switch (VT.getSimpleVT().SimpleTy) {
Matt Arsenault0084adc2018-04-30 19:08:16 +00003783 case MVT::f32: {
Matt Arsenault423bf3f2015-01-29 19:34:32 +00003784 // This is as fast on some subtargets. However, we always have full rate f32
3785 // mad available which returns the same result as the separate operations
Matt Arsenault8d630032015-02-20 22:10:41 +00003786 // which we should prefer over fma. We can't use this if we want to support
3787 // denormals, so only report this in these cases.
Matt Arsenault0084adc2018-04-30 19:08:16 +00003788 if (Subtarget->hasFP32Denormals())
3789 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3790
3791 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3792 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3793 }
Niels Ole Salscheiderd3a039f2013-08-10 10:38:54 +00003794 case MVT::f64:
3795 return true;
Matt Arsenault9e22bc22016-12-22 03:21:48 +00003796 case MVT::f16:
3797 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
Niels Ole Salscheiderd3a039f2013-08-10 10:38:54 +00003798 default:
3799 break;
3800 }
3801
3802 return false;
3803}
3804
Tom Stellard75aadc22012-12-11 21:25:42 +00003805//===----------------------------------------------------------------------===//
3806// Custom DAG Lowering Operations
3807//===----------------------------------------------------------------------===//
3808
Matt Arsenault02dc7e12018-06-15 15:15:46 +00003809// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3810// wider vector type is legal.
3811SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3812 SelectionDAG &DAG) const {
3813 unsigned Opc = Op.getOpcode();
3814 EVT VT = Op.getValueType();
3815 assert(VT == MVT::v4f16);
3816
3817 SDValue Lo, Hi;
3818 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3819
3820 SDLoc SL(Op);
3821 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3822 Op->getFlags());
3823 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3824 Op->getFlags());
3825
3826 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3827}
3828
3829// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3830// wider vector type is legal.
3831SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3832 SelectionDAG &DAG) const {
3833 unsigned Opc = Op.getOpcode();
3834 EVT VT = Op.getValueType();
3835 assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3836
3837 SDValue Lo0, Hi0;
3838 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3839 SDValue Lo1, Hi1;
3840 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3841
3842 SDLoc SL(Op);
3843
3844 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3845 Op->getFlags());
3846 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3847 Op->getFlags());
3848
3849 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3850}
3851
Tom Stellard75aadc22012-12-11 21:25:42 +00003852SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3853 switch (Op.getOpcode()) {
3854 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
Tom Stellardf8794352012-12-19 22:10:31 +00003855 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
Aakanksha Patild5443f82019-05-29 18:20:11 +00003856 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
Tom Stellard35bb18c2013-08-26 15:06:04 +00003857 case ISD::LOAD: {
Tom Stellarde812f2f2014-07-21 15:45:06 +00003858 SDValue Result = LowerLOAD(Op, DAG);
3859 assert((!Result.getNode() ||
3860 Result.getNode()->getNumValues() == 2) &&
3861 "Load should return a value and a chain");
3862 return Result;
Tom Stellard35bb18c2013-08-26 15:06:04 +00003863 }
Tom Stellardaf775432013-10-23 00:44:32 +00003864
Matt Arsenaultad14ce82014-07-19 18:44:39 +00003865 case ISD::FSIN:
3866 case ISD::FCOS:
3867 return LowerTrig(Op, DAG);
Tom Stellard0ec134f2014-02-04 17:18:40 +00003868 case ISD::SELECT: return LowerSELECT(Op, DAG);
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00003869 case ISD::FDIV: return LowerFDIV(Op, DAG);
Tom Stellard354a43c2016-04-01 18:27:37 +00003870 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
Tom Stellard81d871d2013-11-13 23:36:50 +00003871 case ISD::STORE: return LowerSTORE(Op, DAG);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00003872 case ISD::GlobalAddress: {
3873 MachineFunction &MF = DAG.getMachineFunction();
3874 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3875 return LowerGlobalAddress(MFI, Op, DAG);
Tom Stellard94593ee2013-06-03 17:40:18 +00003876 }
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00003877 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +00003878 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00003879 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
Matt Arsenault99c14522016-04-25 19:27:24 +00003880 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
Matt Arsenault3aef8092017-01-23 23:09:58 +00003881 case ISD::INSERT_VECTOR_ELT:
3882 return lowerINSERT_VECTOR_ELT(Op, DAG);
3883 case ISD::EXTRACT_VECTOR_ELT:
3884 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
Matt Arsenault67a98152018-05-16 11:47:30 +00003885 case ISD::BUILD_VECTOR:
3886 return lowerBUILD_VECTOR(Op, DAG);
Konstantin Zhuravlyovd709efb2016-11-17 04:28:37 +00003887 case ISD::FP_ROUND:
3888 return lowerFP_ROUND(Op, DAG);
Matt Arsenault3e025382017-04-24 17:49:13 +00003889 case ISD::TRAP:
Matt Arsenault3e025382017-04-24 17:49:13 +00003890 return lowerTRAP(Op, DAG);
Tony Tye43259df2018-05-16 16:19:34 +00003891 case ISD::DEBUGTRAP:
3892 return lowerDEBUGTRAP(Op, DAG);
Matt Arsenault02dc7e12018-06-15 15:15:46 +00003893 case ISD::FABS:
3894 case ISD::FNEG:
Matt Arsenault36cdcfa2018-08-02 13:43:42 +00003895 case ISD::FCANONICALIZE:
Matt Arsenault02dc7e12018-06-15 15:15:46 +00003896 return splitUnaryVectorOp(Op, DAG);
Matt Arsenault687ec752018-10-22 16:27:27 +00003897 case ISD::FMINNUM:
3898 case ISD::FMAXNUM:
3899 return lowerFMINNUM_FMAXNUM(Op, DAG);
Matt Arsenault02dc7e12018-06-15 15:15:46 +00003900 case ISD::SHL:
3901 case ISD::SRA:
3902 case ISD::SRL:
3903 case ISD::ADD:
3904 case ISD::SUB:
3905 case ISD::MUL:
3906 case ISD::SMIN:
3907 case ISD::SMAX:
3908 case ISD::UMIN:
3909 case ISD::UMAX:
Matt Arsenault02dc7e12018-06-15 15:15:46 +00003910 case ISD::FADD:
3911 case ISD::FMUL:
Matt Arsenault687ec752018-10-22 16:27:27 +00003912 case ISD::FMINNUM_IEEE:
3913 case ISD::FMAXNUM_IEEE:
Matt Arsenault02dc7e12018-06-15 15:15:46 +00003914 return splitBinaryVectorOp(Op, DAG);
Tom Stellard75aadc22012-12-11 21:25:42 +00003915 }
3916 return SDValue();
3917}
3918
Matt Arsenault1349a042018-05-22 06:32:10 +00003919static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
3920 const SDLoc &DL,
3921 SelectionDAG &DAG, bool Unpacked) {
3922 if (!LoadVT.isVector())
3923 return Result;
3924
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00003925 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3926 // Truncate to v2i16/v4i16.
3927 EVT IntLoadVT = LoadVT.changeTypeToInteger();
Matt Arsenault1349a042018-05-22 06:32:10 +00003928
3929 // Workaround legalizer not scalarizing truncate after vector op
3930 // legalization byt not creating intermediate vector trunc.
3931 SmallVector<SDValue, 4> Elts;
3932 DAG.ExtractVectorElements(Result, Elts);
3933 for (SDValue &Elt : Elts)
3934 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
3935
3936 Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
3937
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00003938 // Bitcast to original type (v2f16/v4f16).
Matt Arsenault1349a042018-05-22 06:32:10 +00003939 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00003940 }
Matt Arsenault1349a042018-05-22 06:32:10 +00003941
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00003942 // Cast back to the original packed type.
3943 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3944}
3945
Matt Arsenault1349a042018-05-22 06:32:10 +00003946SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
3947 MemSDNode *M,
3948 SelectionDAG &DAG,
Tim Renouf366a49d2018-08-02 23:33:01 +00003949 ArrayRef<SDValue> Ops,
Matt Arsenault1349a042018-05-22 06:32:10 +00003950 bool IsIntrinsic) const {
3951 SDLoc DL(M);
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00003952
3953 bool Unpacked = Subtarget->hasUnpackedD16VMem();
Matt Arsenault1349a042018-05-22 06:32:10 +00003954 EVT LoadVT = M->getValueType(0);
3955
Matt Arsenault1349a042018-05-22 06:32:10 +00003956 EVT EquivLoadVT = LoadVT;
Matt Arsenault02dc7e12018-06-15 15:15:46 +00003957 if (Unpacked && LoadVT.isVector()) {
3958 EquivLoadVT = LoadVT.isVector() ?
3959 EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3960 LoadVT.getVectorNumElements()) : LoadVT;
Matt Arsenault1349a042018-05-22 06:32:10 +00003961 }
3962
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00003963 // Change from v4f16/v2f16 to EquivLoadVT.
3964 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
3965
Matt Arsenault02dc7e12018-06-15 15:15:46 +00003966 SDValue Load
3967 = DAG.getMemIntrinsicNode(
3968 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
3969 VTList, Ops, M->getMemoryVT(),
3970 M->getMemOperand());
3971 if (!Unpacked) // Just adjusted the opcode.
3972 return Load;
Changpeng Fang4737e892018-01-18 22:08:53 +00003973
Matt Arsenault1349a042018-05-22 06:32:10 +00003974 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
Changpeng Fang4737e892018-01-18 22:08:53 +00003975
Matt Arsenault1349a042018-05-22 06:32:10 +00003976 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00003977}
3978
Matt Arsenaultb3a80e52018-08-15 21:25:20 +00003979static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
3980 SDNode *N, SelectionDAG &DAG) {
3981 EVT VT = N->getValueType(0);
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003982 const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
Matt Arsenaultb3a80e52018-08-15 21:25:20 +00003983 int CondCode = CD->getSExtValue();
3984 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
3985 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
3986 return DAG.getUNDEF(VT);
3987
3988 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
3989
Matt Arsenaultb3a80e52018-08-15 21:25:20 +00003990 SDValue LHS = N->getOperand(1);
3991 SDValue RHS = N->getOperand(2);
3992
3993 SDLoc DL(N);
3994
3995 EVT CmpVT = LHS.getValueType();
3996 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
3997 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
3998 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3999 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4000 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4001 }
4002
4003 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4004
Stanislav Mekhanoshin68a2fef2019-06-13 23:47:36 +00004005 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4006 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4007
4008 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4009 DAG.getCondCode(CCOpcode));
4010 if (VT.bitsEq(CCVT))
4011 return SetCC;
4012 return DAG.getZExtOrTrunc(SetCC, DL, VT);
Matt Arsenaultb3a80e52018-08-15 21:25:20 +00004013}
4014
4015static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4016 SDNode *N, SelectionDAG &DAG) {
4017 EVT VT = N->getValueType(0);
Matt Arsenaultcaf13162019-03-12 21:02:54 +00004018 const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
Matt Arsenaultb3a80e52018-08-15 21:25:20 +00004019
4020 int CondCode = CD->getSExtValue();
4021 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4022 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4023 return DAG.getUNDEF(VT);
4024 }
4025
4026 SDValue Src0 = N->getOperand(1);
4027 SDValue Src1 = N->getOperand(2);
4028 EVT CmpVT = Src0.getValueType();
4029 SDLoc SL(N);
4030
4031 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4032 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4033 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4034 }
4035
4036 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4037 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
Stanislav Mekhanoshin68a2fef2019-06-13 23:47:36 +00004038 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4039 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4040 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4041 Src1, DAG.getCondCode(CCOpcode));
4042 if (VT.bitsEq(CCVT))
4043 return SetCC;
4044 return DAG.getZExtOrTrunc(SetCC, SL, VT);
Matt Arsenaultb3a80e52018-08-15 21:25:20 +00004045}
4046
Matt Arsenault3aef8092017-01-23 23:09:58 +00004047void SITargetLowering::ReplaceNodeResults(SDNode *N,
4048 SmallVectorImpl<SDValue> &Results,
4049 SelectionDAG &DAG) const {
4050 switch (N->getOpcode()) {
4051 case ISD::INSERT_VECTOR_ELT: {
4052 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4053 Results.push_back(Res);
4054 return;
4055 }
4056 case ISD::EXTRACT_VECTOR_ELT: {
4057 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4058 Results.push_back(Res);
4059 return;
4060 }
Matt Arsenault1f17c662017-02-22 00:27:34 +00004061 case ISD::INTRINSIC_WO_CHAIN: {
4062 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
Marek Olsak13e47412018-01-31 20:18:04 +00004063 switch (IID) {
4064 case Intrinsic::amdgcn_cvt_pkrtz: {
Matt Arsenault1f17c662017-02-22 00:27:34 +00004065 SDValue Src0 = N->getOperand(1);
4066 SDValue Src1 = N->getOperand(2);
4067 SDLoc SL(N);
4068 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4069 Src0, Src1);
Matt Arsenault1f17c662017-02-22 00:27:34 +00004070 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4071 return;
4072 }
Marek Olsak13e47412018-01-31 20:18:04 +00004073 case Intrinsic::amdgcn_cvt_pknorm_i16:
4074 case Intrinsic::amdgcn_cvt_pknorm_u16:
4075 case Intrinsic::amdgcn_cvt_pk_i16:
4076 case Intrinsic::amdgcn_cvt_pk_u16: {
4077 SDValue Src0 = N->getOperand(1);
4078 SDValue Src1 = N->getOperand(2);
4079 SDLoc SL(N);
4080 unsigned Opcode;
4081
4082 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4083 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4084 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4085 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4086 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4087 Opcode = AMDGPUISD::CVT_PK_I16_I32;
4088 else
4089 Opcode = AMDGPUISD::CVT_PK_U16_U32;
4090
Matt Arsenault709374d2018-08-01 20:13:58 +00004091 EVT VT = N->getValueType(0);
4092 if (isTypeLegal(VT))
4093 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4094 else {
4095 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4096 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4097 }
Marek Olsak13e47412018-01-31 20:18:04 +00004098 return;
4099 }
4100 }
Simon Pilgrimd362d272017-07-08 19:50:03 +00004101 break;
Matt Arsenault1f17c662017-02-22 00:27:34 +00004102 }
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00004103 case ISD::INTRINSIC_W_CHAIN: {
Matt Arsenault1349a042018-05-22 06:32:10 +00004104 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00004105 Results.push_back(Res);
Matt Arsenault1349a042018-05-22 06:32:10 +00004106 Results.push_back(Res.getValue(1));
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00004107 return;
4108 }
Matt Arsenault1349a042018-05-22 06:32:10 +00004109
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00004110 break;
4111 }
Matt Arsenault4a486232017-04-19 20:53:07 +00004112 case ISD::SELECT: {
4113 SDLoc SL(N);
4114 EVT VT = N->getValueType(0);
4115 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4116 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4117 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4118
4119 EVT SelectVT = NewVT;
4120 if (NewVT.bitsLT(MVT::i32)) {
4121 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4122 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4123 SelectVT = MVT::i32;
4124 }
4125
4126 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4127 N->getOperand(0), LHS, RHS);
4128
4129 if (NewVT != SelectVT)
4130 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4131 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4132 return;
4133 }
Matt Arsenaulte9524f12018-06-06 21:28:11 +00004134 case ISD::FNEG: {
Matt Arsenault02dc7e12018-06-15 15:15:46 +00004135 if (N->getValueType(0) != MVT::v2f16)
4136 break;
4137
Matt Arsenaulte9524f12018-06-06 21:28:11 +00004138 SDLoc SL(N);
Matt Arsenaulte9524f12018-06-06 21:28:11 +00004139 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4140
4141 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4142 BC,
4143 DAG.getConstant(0x80008000, SL, MVT::i32));
4144 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4145 return;
4146 }
4147 case ISD::FABS: {
Matt Arsenault02dc7e12018-06-15 15:15:46 +00004148 if (N->getValueType(0) != MVT::v2f16)
4149 break;
4150
Matt Arsenaulte9524f12018-06-06 21:28:11 +00004151 SDLoc SL(N);
Matt Arsenaulte9524f12018-06-06 21:28:11 +00004152 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4153
4154 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4155 BC,
4156 DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4157 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4158 return;
4159 }
Matt Arsenault3aef8092017-01-23 23:09:58 +00004160 default:
4161 break;
4162 }
4163}
4164
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004165/// Helper function for LowerBRCOND
Tom Stellardf8794352012-12-19 22:10:31 +00004166static SDNode *findUser(SDValue Value, unsigned Opcode) {
Tom Stellard75aadc22012-12-11 21:25:42 +00004167
Tom Stellardf8794352012-12-19 22:10:31 +00004168 SDNode *Parent = Value.getNode();
4169 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4170 I != E; ++I) {
4171
4172 if (I.getUse().get() != Value)
4173 continue;
4174
4175 if (I->getOpcode() == Opcode)
4176 return *I;
4177 }
Craig Topper062a2ba2014-04-25 05:30:21 +00004178 return nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +00004179}
4180
Matt Arsenaultc5b641a2017-03-17 20:41:45 +00004181unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
Matt Arsenault6408c912016-09-16 22:11:18 +00004182 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4183 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
Matt Arsenaultc5b641a2017-03-17 20:41:45 +00004184 case Intrinsic::amdgcn_if:
4185 return AMDGPUISD::IF;
4186 case Intrinsic::amdgcn_else:
4187 return AMDGPUISD::ELSE;
4188 case Intrinsic::amdgcn_loop:
4189 return AMDGPUISD::LOOP;
4190 case Intrinsic::amdgcn_end_cf:
4191 llvm_unreachable("should not occur");
Matt Arsenault6408c912016-09-16 22:11:18 +00004192 default:
Matt Arsenaultc5b641a2017-03-17 20:41:45 +00004193 return 0;
Matt Arsenault6408c912016-09-16 22:11:18 +00004194 }
Tom Stellardbc4497b2016-02-12 23:45:29 +00004195 }
Matt Arsenault6408c912016-09-16 22:11:18 +00004196
Matt Arsenaultc5b641a2017-03-17 20:41:45 +00004197 // break, if_break, else_break are all only used as inputs to loop, not
4198 // directly as branch conditions.
4199 return 0;
Tom Stellardbc4497b2016-02-12 23:45:29 +00004200}
4201
Konstantin Zhuravlyov08326b62016-10-20 18:12:38 +00004202bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4203 const Triple &TT = getTargetMachine().getTargetTriple();
Matt Arsenault0da63502018-08-31 05:49:54 +00004204 return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4205 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
Konstantin Zhuravlyov08326b62016-10-20 18:12:38 +00004206 AMDGPU::shouldEmitConstantsToTextSection(TT);
4207}
4208
4209bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
Scott Linderd19d1972019-02-04 20:00:07 +00004210 // FIXME: Either avoid relying on address space here or change the default
4211 // address space for functions to avoid the explicit check.
4212 return (GV->getValueType()->isFunctionTy() ||
4213 GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
Matt Arsenault0da63502018-08-31 05:49:54 +00004214 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4215 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
Konstantin Zhuravlyov08326b62016-10-20 18:12:38 +00004216 !shouldEmitFixup(GV) &&
4217 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4218}
4219
4220bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4221 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4222}
4223
Tom Stellardf8794352012-12-19 22:10:31 +00004224/// This transforms the control flow intrinsics to get the branch destination as
4225/// last parameter, also switches branch target with BR if the need arise
4226SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4227 SelectionDAG &DAG) const {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004228 SDLoc DL(BRCOND);
Tom Stellardf8794352012-12-19 22:10:31 +00004229
4230 SDNode *Intr = BRCOND.getOperand(1).getNode();
4231 SDValue Target = BRCOND.getOperand(2);
Craig Topper062a2ba2014-04-25 05:30:21 +00004232 SDNode *BR = nullptr;
Tom Stellardbc4497b2016-02-12 23:45:29 +00004233 SDNode *SetCC = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +00004234
4235 if (Intr->getOpcode() == ISD::SETCC) {
4236 // As long as we negate the condition everything is fine
Tom Stellardbc4497b2016-02-12 23:45:29 +00004237 SetCC = Intr;
Tom Stellardf8794352012-12-19 22:10:31 +00004238 Intr = SetCC->getOperand(0).getNode();
4239
4240 } else {
4241 // Get the target from BR if we don't negate the condition
4242 BR = findUser(BRCOND, ISD::BR);
4243 Target = BR->getOperand(1);
4244 }
4245
Matt Arsenault6408c912016-09-16 22:11:18 +00004246 // FIXME: This changes the types of the intrinsics instead of introducing new
4247 // nodes with the correct types.
4248 // e.g. llvm.amdgcn.loop
4249
4250 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4251 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4252
Matt Arsenaultc5b641a2017-03-17 20:41:45 +00004253 unsigned CFNode = isCFIntrinsic(Intr);
4254 if (CFNode == 0) {
Tom Stellardbc4497b2016-02-12 23:45:29 +00004255 // This is a uniform branch so we don't need to legalize.
4256 return BRCOND;
4257 }
4258
Matt Arsenault6408c912016-09-16 22:11:18 +00004259 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4260 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4261
Tom Stellardbc4497b2016-02-12 23:45:29 +00004262 assert(!SetCC ||
4263 (SetCC->getConstantOperandVal(1) == 1 &&
Tom Stellardbc4497b2016-02-12 23:45:29 +00004264 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4265 ISD::SETNE));
Tom Stellardf8794352012-12-19 22:10:31 +00004266
Tom Stellardf8794352012-12-19 22:10:31 +00004267 // operands of the new intrinsic call
4268 SmallVector<SDValue, 4> Ops;
Matt Arsenault6408c912016-09-16 22:11:18 +00004269 if (HaveChain)
4270 Ops.push_back(BRCOND.getOperand(0));
4271
Matt Arsenaultc5b641a2017-03-17 20:41:45 +00004272 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
Tom Stellardf8794352012-12-19 22:10:31 +00004273 Ops.push_back(Target);
4274
Matt Arsenault6408c912016-09-16 22:11:18 +00004275 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4276
Tom Stellardf8794352012-12-19 22:10:31 +00004277 // build the new intrinsic call
Matt Arsenaultc5b641a2017-03-17 20:41:45 +00004278 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
Tom Stellardf8794352012-12-19 22:10:31 +00004279
Matt Arsenault6408c912016-09-16 22:11:18 +00004280 if (!HaveChain) {
4281 SDValue Ops[] = {
4282 SDValue(Result, 0),
4283 BRCOND.getOperand(0)
4284 };
4285
4286 Result = DAG.getMergeValues(Ops, DL).getNode();
4287 }
4288
Tom Stellardf8794352012-12-19 22:10:31 +00004289 if (BR) {
4290 // Give the branch instruction our target
4291 SDValue Ops[] = {
4292 BR->getOperand(0),
4293 BRCOND.getOperand(2)
4294 };
Chandler Carruth356665a2014-08-01 22:09:43 +00004295 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4296 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4297 BR = NewBR.getNode();
Tom Stellardf8794352012-12-19 22:10:31 +00004298 }
4299
4300 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4301
4302 // Copy the intrinsic results to registers
4303 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4304 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4305 if (!CopyToReg)
4306 continue;
4307
4308 Chain = DAG.getCopyToReg(
4309 Chain, DL,
4310 CopyToReg->getOperand(1),
4311 SDValue(Result, i - 1),
4312 SDValue());
4313
4314 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4315 }
4316
4317 // Remove the old intrinsic from the chain
4318 DAG.ReplaceAllUsesOfValueWith(
4319 SDValue(Intr, Intr->getNumValues() - 1),
4320 Intr->getOperand(0));
4321
4322 return Chain;
Tom Stellard75aadc22012-12-11 21:25:42 +00004323}
4324
Aakanksha Patild5443f82019-05-29 18:20:11 +00004325SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4326 SelectionDAG &DAG) const {
4327 MVT VT = Op.getSimpleValueType();
4328 SDLoc DL(Op);
4329 // Checking the depth
4330 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4331 return DAG.getConstant(0, DL, VT);
4332
4333 MachineFunction &MF = DAG.getMachineFunction();
4334 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4335 // Check for kernel and shader functions
4336 if (Info->isEntryFunction())
4337 return DAG.getConstant(0, DL, VT);
4338
4339 MachineFrameInfo &MFI = MF.getFrameInfo();
4340 // There is a call to @llvm.returnaddress in this function
4341 MFI.setReturnAddressIsTaken(true);
4342
4343 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4344 // Get the return address reg and mark it as an implicit live-in
4345 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4346
4347 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4348}
4349
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +00004350SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4351 SDValue Op,
4352 const SDLoc &DL,
4353 EVT VT) const {
4354 return Op.getValueType().bitsLE(VT) ?
4355 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4356 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4357}
4358
Konstantin Zhuravlyovd709efb2016-11-17 04:28:37 +00004359SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
Matt Arsenaultafe614c2016-11-18 18:33:36 +00004360 assert(Op.getValueType() == MVT::f16 &&
Konstantin Zhuravlyovd709efb2016-11-17 04:28:37 +00004361 "Do not know how to custom lower FP_ROUND for non-f16 type");
4362
Matt Arsenaultafe614c2016-11-18 18:33:36 +00004363 SDValue Src = Op.getOperand(0);
4364 EVT SrcVT = Src.getValueType();
Konstantin Zhuravlyovd709efb2016-11-17 04:28:37 +00004365 if (SrcVT != MVT::f64)
4366 return Op;
4367
4368 SDLoc DL(Op);
Matt Arsenaultafe614c2016-11-18 18:33:36 +00004369
Konstantin Zhuravlyovd709efb2016-11-17 04:28:37 +00004370 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4371 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
Mandeep Singh Grang5e1697e2017-06-06 05:08:36 +00004372 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
Konstantin Zhuravlyovd709efb2016-11-17 04:28:37 +00004373}
4374
Matt Arsenault687ec752018-10-22 16:27:27 +00004375SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4376 SelectionDAG &DAG) const {
4377 EVT VT = Op.getValueType();
Matt Arsenault055e4dc2019-03-29 19:14:54 +00004378 const MachineFunction &MF = DAG.getMachineFunction();
4379 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4380 bool IsIEEEMode = Info->getMode().IEEE;
Matt Arsenault687ec752018-10-22 16:27:27 +00004381
4382 // FIXME: Assert during eslection that this is only selected for
4383 // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4384 // mode functions, but this happens to be OK since it's only done in cases
4385 // where there is known no sNaN.
4386 if (IsIEEEMode)
4387 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4388
4389 if (VT == MVT::v4f16)
4390 return splitBinaryVectorOp(Op, DAG);
4391 return Op;
4392}
4393
Matt Arsenault3e025382017-04-24 17:49:13 +00004394SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4395 SDLoc SL(Op);
Matt Arsenault3e025382017-04-24 17:49:13 +00004396 SDValue Chain = Op.getOperand(0);
4397
Tom Stellard5bfbae52018-07-11 20:59:01 +00004398 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
Tony Tye43259df2018-05-16 16:19:34 +00004399 !Subtarget->isTrapHandlerEnabled())
Matt Arsenault3e025382017-04-24 17:49:13 +00004400 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
Tony Tye43259df2018-05-16 16:19:34 +00004401
4402 MachineFunction &MF = DAG.getMachineFunction();
4403 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4404 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4405 assert(UserSGPR != AMDGPU::NoRegister);
4406 SDValue QueuePtr = CreateLiveInRegister(
4407 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4408 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4409 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4410 QueuePtr, SDValue());
4411 SDValue Ops[] = {
4412 ToReg,
Tom Stellard5bfbae52018-07-11 20:59:01 +00004413 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
Tony Tye43259df2018-05-16 16:19:34 +00004414 SGPR01,
4415 ToReg.getValue(1)
4416 };
4417 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4418}
4419
4420SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4421 SDLoc SL(Op);
4422 SDValue Chain = Op.getOperand(0);
4423 MachineFunction &MF = DAG.getMachineFunction();
4424
Tom Stellard5bfbae52018-07-11 20:59:01 +00004425 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
Tony Tye43259df2018-05-16 16:19:34 +00004426 !Subtarget->isTrapHandlerEnabled()) {
Matthias Braunf1caa282017-12-15 22:22:58 +00004427 DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
Matt Arsenault3e025382017-04-24 17:49:13 +00004428 "debugtrap handler not supported",
4429 Op.getDebugLoc(),
4430 DS_Warning);
Matthias Braunf1caa282017-12-15 22:22:58 +00004431 LLVMContext &Ctx = MF.getFunction().getContext();
Matt Arsenault3e025382017-04-24 17:49:13 +00004432 Ctx.diagnose(NoTrap);
4433 return Chain;
4434 }
Matt Arsenault3e025382017-04-24 17:49:13 +00004435
Tony Tye43259df2018-05-16 16:19:34 +00004436 SDValue Ops[] = {
4437 Chain,
Tom Stellard5bfbae52018-07-11 20:59:01 +00004438 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
Tony Tye43259df2018-05-16 16:19:34 +00004439 };
4440 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
Matt Arsenault3e025382017-04-24 17:49:13 +00004441}
4442
Konstantin Zhuravlyov4b3847e2017-04-06 23:02:33 +00004443SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
Matt Arsenault99c14522016-04-25 19:27:24 +00004444 SelectionDAG &DAG) const {
Konstantin Zhuravlyov4b3847e2017-04-06 23:02:33 +00004445 // FIXME: Use inline constants (src_{shared, private}_base) instead.
4446 if (Subtarget->hasApertureRegs()) {
Matt Arsenault0da63502018-08-31 05:49:54 +00004447 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
Konstantin Zhuravlyov4b3847e2017-04-06 23:02:33 +00004448 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4449 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
Matt Arsenault0da63502018-08-31 05:49:54 +00004450 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
Konstantin Zhuravlyov4b3847e2017-04-06 23:02:33 +00004451 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4452 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4453 unsigned Encoding =
4454 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4455 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4456 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
Matt Arsenaulte823d922017-02-18 18:29:53 +00004457
Konstantin Zhuravlyov4b3847e2017-04-06 23:02:33 +00004458 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4459 SDValue ApertureReg = SDValue(
4460 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4461 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4462 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
Matt Arsenaulte823d922017-02-18 18:29:53 +00004463 }
4464
Matt Arsenault99c14522016-04-25 19:27:24 +00004465 MachineFunction &MF = DAG.getMachineFunction();
4466 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
Matt Arsenault3b2e2a52016-06-06 20:03:31 +00004467 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4468 assert(UserSGPR != AMDGPU::NoRegister);
4469
Matt Arsenault99c14522016-04-25 19:27:24 +00004470 SDValue QueuePtr = CreateLiveInRegister(
Matt Arsenault3b2e2a52016-06-06 20:03:31 +00004471 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
Matt Arsenault99c14522016-04-25 19:27:24 +00004472
4473 // Offset into amd_queue_t for group_segment_aperture_base_hi /
4474 // private_segment_aperture_base_hi.
Matt Arsenault0da63502018-08-31 05:49:54 +00004475 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
Matt Arsenault99c14522016-04-25 19:27:24 +00004476
Matt Arsenaultb655fa92017-11-29 01:25:12 +00004477 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
Matt Arsenault99c14522016-04-25 19:27:24 +00004478
4479 // TODO: Use custom target PseudoSourceValue.
4480 // TODO: We should use the value from the IR intrinsic call, but it might not
4481 // be available and how do we get it?
4482 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
Matt Arsenault0da63502018-08-31 05:49:54 +00004483 AMDGPUAS::CONSTANT_ADDRESS));
Matt Arsenault99c14522016-04-25 19:27:24 +00004484
4485 MachinePointerInfo PtrInfo(V, StructOffset);
Konstantin Zhuravlyov4b3847e2017-04-06 23:02:33 +00004486 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
Justin Lebar9c375812016-07-15 18:27:10 +00004487 MinAlign(64, StructOffset),
Justin Lebaradbf09e2016-09-11 01:38:58 +00004488 MachineMemOperand::MODereferenceable |
4489 MachineMemOperand::MOInvariant);
Matt Arsenault99c14522016-04-25 19:27:24 +00004490}
4491
4492SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4493 SelectionDAG &DAG) const {
4494 SDLoc SL(Op);
4495 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4496
4497 SDValue Src = ASC->getOperand(0);
Matt Arsenault99c14522016-04-25 19:27:24 +00004498 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4499
Matt Arsenault747bf8a2017-03-13 20:18:14 +00004500 const AMDGPUTargetMachine &TM =
4501 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4502
Matt Arsenault99c14522016-04-25 19:27:24 +00004503 // flat -> local/private
Matt Arsenault0da63502018-08-31 05:49:54 +00004504 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
Matt Arsenault971c85e2017-03-13 19:47:31 +00004505 unsigned DestAS = ASC->getDestAddressSpace();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +00004506
Matt Arsenault0da63502018-08-31 05:49:54 +00004507 if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4508 DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
Matt Arsenault747bf8a2017-03-13 20:18:14 +00004509 unsigned NullVal = TM.getNullPointerValue(DestAS);
4510 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
Matt Arsenault99c14522016-04-25 19:27:24 +00004511 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4512 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4513
4514 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4515 NonNull, Ptr, SegmentNullPtr);
4516 }
4517 }
4518
4519 // local/private -> flat
Matt Arsenault0da63502018-08-31 05:49:54 +00004520 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
Matt Arsenault971c85e2017-03-13 19:47:31 +00004521 unsigned SrcAS = ASC->getSrcAddressSpace();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +00004522
Matt Arsenault0da63502018-08-31 05:49:54 +00004523 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4524 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
Matt Arsenault747bf8a2017-03-13 20:18:14 +00004525 unsigned NullVal = TM.getNullPointerValue(SrcAS);
4526 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
Matt Arsenault971c85e2017-03-13 19:47:31 +00004527
Matt Arsenault99c14522016-04-25 19:27:24 +00004528 SDValue NonNull
4529 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4530
Konstantin Zhuravlyov4b3847e2017-04-06 23:02:33 +00004531 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
Matt Arsenault99c14522016-04-25 19:27:24 +00004532 SDValue CvtPtr
4533 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4534
4535 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4536 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4537 FlatNullPtr);
4538 }
4539 }
4540
4541 // global <-> flat are no-ops and never emitted.
4542
4543 const MachineFunction &MF = DAG.getMachineFunction();
4544 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
Matthias Braunf1caa282017-12-15 22:22:58 +00004545 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
Matt Arsenault99c14522016-04-25 19:27:24 +00004546 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4547
4548 return DAG.getUNDEF(ASC->getValueType(0));
4549}
4550
Matt Arsenault3aef8092017-01-23 23:09:58 +00004551SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4552 SelectionDAG &DAG) const {
Matt Arsenault67a98152018-05-16 11:47:30 +00004553 SDValue Vec = Op.getOperand(0);
4554 SDValue InsVal = Op.getOperand(1);
Matt Arsenault3aef8092017-01-23 23:09:58 +00004555 SDValue Idx = Op.getOperand(2);
Matt Arsenault67a98152018-05-16 11:47:30 +00004556 EVT VecVT = Vec.getValueType();
Matt Arsenault9224c002018-06-05 19:52:46 +00004557 EVT EltVT = VecVT.getVectorElementType();
4558 unsigned VecSize = VecVT.getSizeInBits();
4559 unsigned EltSize = EltVT.getSizeInBits();
Matt Arsenault67a98152018-05-16 11:47:30 +00004560
Matt Arsenault9224c002018-06-05 19:52:46 +00004561
4562 assert(VecSize <= 64);
Matt Arsenault67a98152018-05-16 11:47:30 +00004563
4564 unsigned NumElts = VecVT.getVectorNumElements();
4565 SDLoc SL(Op);
4566 auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4567
Matt Arsenault9224c002018-06-05 19:52:46 +00004568 if (NumElts == 4 && EltSize == 16 && KIdx) {
Matt Arsenault67a98152018-05-16 11:47:30 +00004569 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4570
4571 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4572 DAG.getConstant(0, SL, MVT::i32));
4573 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4574 DAG.getConstant(1, SL, MVT::i32));
4575
4576 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4577 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4578
4579 unsigned Idx = KIdx->getZExtValue();
4580 bool InsertLo = Idx < 2;
4581 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4582 InsertLo ? LoVec : HiVec,
4583 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4584 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4585
4586 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4587
4588 SDValue Concat = InsertLo ?
4589 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4590 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4591
4592 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4593 }
4594
Matt Arsenault3aef8092017-01-23 23:09:58 +00004595 if (isa<ConstantSDNode>(Idx))
4596 return SDValue();
4597
Matt Arsenault9224c002018-06-05 19:52:46 +00004598 MVT IntVT = MVT::getIntegerVT(VecSize);
Matt Arsenault67a98152018-05-16 11:47:30 +00004599
Matt Arsenault3aef8092017-01-23 23:09:58 +00004600 // Avoid stack access for dynamic indexing.
Matt Arsenault3aef8092017-01-23 23:09:58 +00004601 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
Tim Corringhamfa3e4e52019-02-01 16:51:09 +00004602
4603 // Create a congruent vector with the target value in each element so that
4604 // the required element can be masked and ORed into the target vector.
4605 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4606 DAG.getSplatBuildVector(VecVT, SL, InsVal));
Matt Arsenault3aef8092017-01-23 23:09:58 +00004607
Matt Arsenault9224c002018-06-05 19:52:46 +00004608 assert(isPowerOf2_32(EltSize));
4609 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4610
Matt Arsenault3aef8092017-01-23 23:09:58 +00004611 // Convert vector index to bit-index.
Matt Arsenault9224c002018-06-05 19:52:46 +00004612 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
Matt Arsenault3aef8092017-01-23 23:09:58 +00004613
Matt Arsenault67a98152018-05-16 11:47:30 +00004614 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4615 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4616 DAG.getConstant(0xffff, SL, IntVT),
Matt Arsenault3aef8092017-01-23 23:09:58 +00004617 ScaledIdx);
4618
Matt Arsenault67a98152018-05-16 11:47:30 +00004619 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4620 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4621 DAG.getNOT(SL, BFM, IntVT), BCVec);
Matt Arsenault3aef8092017-01-23 23:09:58 +00004622
Matt Arsenault67a98152018-05-16 11:47:30 +00004623 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4624 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
Matt Arsenault3aef8092017-01-23 23:09:58 +00004625}
4626
4627SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4628 SelectionDAG &DAG) const {
4629 SDLoc SL(Op);
4630
4631 EVT ResultVT = Op.getValueType();
4632 SDValue Vec = Op.getOperand(0);
4633 SDValue Idx = Op.getOperand(1);
Matt Arsenault67a98152018-05-16 11:47:30 +00004634 EVT VecVT = Vec.getValueType();
Matt Arsenault9224c002018-06-05 19:52:46 +00004635 unsigned VecSize = VecVT.getSizeInBits();
4636 EVT EltVT = VecVT.getVectorElementType();
4637 assert(VecSize <= 64);
Matt Arsenault3aef8092017-01-23 23:09:58 +00004638
Matt Arsenault98f29462017-05-17 20:30:58 +00004639 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4640
Hiroshi Inoue372ffa12018-04-13 11:37:06 +00004641 // Make sure we do any optimizations that will make it easier to fold
Matt Arsenault98f29462017-05-17 20:30:58 +00004642 // source modifiers before obscuring it with bit operations.
4643
4644 // XXX - Why doesn't this get called when vector_shuffle is expanded?
4645 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4646 return Combined;
4647
Matt Arsenault9224c002018-06-05 19:52:46 +00004648 unsigned EltSize = EltVT.getSizeInBits();
4649 assert(isPowerOf2_32(EltSize));
Matt Arsenault3aef8092017-01-23 23:09:58 +00004650
Matt Arsenault9224c002018-06-05 19:52:46 +00004651 MVT IntVT = MVT::getIntegerVT(VecSize);
4652 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4653
4654 // Convert vector index to bit-index (* EltSize)
4655 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
Matt Arsenault3aef8092017-01-23 23:09:58 +00004656
Matt Arsenault67a98152018-05-16 11:47:30 +00004657 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4658 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
Matt Arsenault3aef8092017-01-23 23:09:58 +00004659
Matt Arsenault67a98152018-05-16 11:47:30 +00004660 if (ResultVT == MVT::f16) {
4661 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4662 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4663 }
Matt Arsenault3aef8092017-01-23 23:09:58 +00004664
Matt Arsenault67a98152018-05-16 11:47:30 +00004665 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4666}
4667
4668SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4669 SelectionDAG &DAG) const {
4670 SDLoc SL(Op);
4671 EVT VT = Op.getValueType();
Matt Arsenault67a98152018-05-16 11:47:30 +00004672
Matt Arsenault02dc7e12018-06-15 15:15:46 +00004673 if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4674 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4675
4676 // Turn into pair of packed build_vectors.
4677 // TODO: Special case for constants that can be materialized with s_mov_b64.
4678 SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4679 { Op.getOperand(0), Op.getOperand(1) });
4680 SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4681 { Op.getOperand(2), Op.getOperand(3) });
4682
4683 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4684 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4685
4686 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4687 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4688 }
4689
Matt Arsenault1349a042018-05-22 06:32:10 +00004690 assert(VT == MVT::v2f16 || VT == MVT::v2i16);
Matt Arsenault3ead7d72018-08-12 08:42:46 +00004691 assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
Matt Arsenault67a98152018-05-16 11:47:30 +00004692
Matt Arsenault1349a042018-05-22 06:32:10 +00004693 SDValue Lo = Op.getOperand(0);
4694 SDValue Hi = Op.getOperand(1);
Matt Arsenault67a98152018-05-16 11:47:30 +00004695
Matt Arsenault3ead7d72018-08-12 08:42:46 +00004696 // Avoid adding defined bits with the zero_extend.
4697 if (Hi.isUndef()) {
4698 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4699 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
4700 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
4701 }
Matt Arsenault67a98152018-05-16 11:47:30 +00004702
Matt Arsenault3ead7d72018-08-12 08:42:46 +00004703 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
Matt Arsenault1349a042018-05-22 06:32:10 +00004704 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4705
4706 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4707 DAG.getConstant(16, SL, MVT::i32));
Matt Arsenault3ead7d72018-08-12 08:42:46 +00004708 if (Lo.isUndef())
4709 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
4710
4711 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4712 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
Matt Arsenault1349a042018-05-22 06:32:10 +00004713
4714 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
Matt Arsenault1349a042018-05-22 06:32:10 +00004715 return DAG.getNode(ISD::BITCAST, SL, VT, Or);
Matt Arsenault3aef8092017-01-23 23:09:58 +00004716}
4717
Tom Stellard418beb72016-07-13 14:23:33 +00004718bool
4719SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4720 // We can fold offsets for anything that doesn't require a GOT relocation.
Matt Arsenault0da63502018-08-31 05:49:54 +00004721 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4722 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4723 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
Konstantin Zhuravlyov08326b62016-10-20 18:12:38 +00004724 !shouldEmitGOTReloc(GA->getGlobal());
Tom Stellard418beb72016-07-13 14:23:33 +00004725}
Tom Stellardbf3e6e52016-06-14 20:29:59 +00004726
Benjamin Kramer061f4a52017-01-13 14:39:03 +00004727static SDValue
4728buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4729 const SDLoc &DL, unsigned Offset, EVT PtrVT,
4730 unsigned GAFlags = SIInstrInfo::MO_NONE) {
Tom Stellardbf3e6e52016-06-14 20:29:59 +00004731 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4732 // lowered to the following code sequence:
Tom Stellardbf3e6e52016-06-14 20:29:59 +00004733 //
Konstantin Zhuravlyovc96b5d72016-10-14 04:37:34 +00004734 // For constant address space:
4735 // s_getpc_b64 s[0:1]
4736 // s_add_u32 s0, s0, $symbol
4737 // s_addc_u32 s1, s1, 0
4738 //
4739 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4740 // a fixup or relocation is emitted to replace $symbol with a literal
4741 // constant, which is a pc-relative offset from the encoding of the $symbol
4742 // operand to the global variable.
4743 //
4744 // For global address space:
4745 // s_getpc_b64 s[0:1]
4746 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4747 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4748 //
4749 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4750 // fixups or relocations are emitted to replace $symbol@*@lo and
4751 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4752 // which is a 64-bit pc-relative offset from the encoding of the $symbol
4753 // operand to the global variable.
Tom Stellardbf3e6e52016-06-14 20:29:59 +00004754 //
4755 // What we want here is an offset from the value returned by s_getpc
4756 // (which is the address of the s_add_u32 instruction) to the global
4757 // variable, but since the encoding of $symbol starts 4 bytes after the start
4758 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4759 // small. This requires us to add 4 to the global variable offset in order to
4760 // compute the correct address.
Nicolai Haehnle6d71be42019-06-16 17:32:01 +00004761 unsigned LoFlags = GAFlags;
4762 if (LoFlags == SIInstrInfo::MO_NONE)
4763 LoFlags = SIInstrInfo::MO_REL32;
4764 SDValue PtrLo =
4765 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, LoFlags);
4766 SDValue PtrHi;
4767 if (GAFlags == SIInstrInfo::MO_NONE) {
4768 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
4769 } else {
4770 PtrHi =
4771 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
4772 }
Konstantin Zhuravlyovc96b5d72016-10-14 04:37:34 +00004773 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
Tom Stellardbf3e6e52016-06-14 20:29:59 +00004774}
4775
Tom Stellard418beb72016-07-13 14:23:33 +00004776SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4777 SDValue Op,
4778 SelectionDAG &DAG) const {
4779 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
Matt Arsenaultb62a4eb2017-08-01 19:54:18 +00004780 const GlobalValue *GV = GSD->getGlobal();
Nicolai Haehnle27101712019-06-25 11:52:30 +00004781 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
4782 (!GV->hasExternalLinkage() ||
4783 getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4784 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) ||
Matt Arsenaultd1f45712018-09-10 12:16:11 +00004785 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
4786 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
Tom Stellard418beb72016-07-13 14:23:33 +00004787 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4788
4789 SDLoc DL(GSD);
Tom Stellard418beb72016-07-13 14:23:33 +00004790 EVT PtrVT = Op.getValueType();
4791
Nicolai Haehnle27101712019-06-25 11:52:30 +00004792 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
4793 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
4794 SIInstrInfo::MO_ABS32_LO);
4795 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
4796 }
4797
Konstantin Zhuravlyov08326b62016-10-20 18:12:38 +00004798 if (shouldEmitFixup(GV))
Tom Stellard418beb72016-07-13 14:23:33 +00004799 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
Konstantin Zhuravlyov08326b62016-10-20 18:12:38 +00004800 else if (shouldEmitPCReloc(GV))
Konstantin Zhuravlyovc96b5d72016-10-14 04:37:34 +00004801 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4802 SIInstrInfo::MO_REL32);
Tom Stellard418beb72016-07-13 14:23:33 +00004803
4804 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
Konstantin Zhuravlyovc96b5d72016-10-14 04:37:34 +00004805 SIInstrInfo::MO_GOTPCREL32);
Tom Stellard418beb72016-07-13 14:23:33 +00004806
4807 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
Matt Arsenault0da63502018-08-31 05:49:54 +00004808 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
Tom Stellard418beb72016-07-13 14:23:33 +00004809 const DataLayout &DataLayout = DAG.getDataLayout();
4810 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
Matt Arsenaultd77fcc22018-09-10 02:23:39 +00004811 MachinePointerInfo PtrInfo
4812 = MachinePointerInfo::getGOT(DAG.getMachineFunction());
Tom Stellard418beb72016-07-13 14:23:33 +00004813
Justin Lebar9c375812016-07-15 18:27:10 +00004814 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
Justin Lebaradbf09e2016-09-11 01:38:58 +00004815 MachineMemOperand::MODereferenceable |
4816 MachineMemOperand::MOInvariant);
Tom Stellard418beb72016-07-13 14:23:33 +00004817}
4818
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004819SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4820 const SDLoc &DL, SDValue V) const {
Matt Arsenault4ac341c2016-04-14 21:58:15 +00004821 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4822 // the destination register.
4823 //
Tom Stellardfc92e772015-05-12 14:18:14 +00004824 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4825 // so we will end up with redundant moves to m0.
4826 //
Matt Arsenault4ac341c2016-04-14 21:58:15 +00004827 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4828
4829 // A Null SDValue creates a glue result.
4830 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4831 V, Chain);
4832 return SDValue(M0, 0);
Tom Stellardfc92e772015-05-12 14:18:14 +00004833}
4834
Matt Arsenaultff6da2f2015-11-30 21:15:45 +00004835SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4836 SDValue Op,
4837 MVT VT,
4838 unsigned Offset) const {
4839 SDLoc SL(Op);
Matt Arsenaulte622dc32017-04-11 22:29:24 +00004840 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
Matt Arsenault7b4826e2018-05-30 16:17:51 +00004841 DAG.getEntryNode(), Offset, 4, false);
Matt Arsenaultff6da2f2015-11-30 21:15:45 +00004842 // The local size values will have the hi 16-bits as zero.
4843 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4844 DAG.getValueType(VT));
4845}
4846
Benjamin Kramer061f4a52017-01-13 14:39:03 +00004847static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4848 EVT VT) {
Matthias Braunf1caa282017-12-15 22:22:58 +00004849 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00004850 "non-hsa intrinsic with hsa target",
4851 DL.getDebugLoc());
4852 DAG.getContext()->diagnose(BadIntrin);
4853 return DAG.getUNDEF(VT);
4854}
4855
Benjamin Kramer061f4a52017-01-13 14:39:03 +00004856static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4857 EVT VT) {
Matthias Braunf1caa282017-12-15 22:22:58 +00004858 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00004859 "intrinsic not supported on subtarget",
4860 DL.getDebugLoc());
Matt Arsenaulte0132462016-01-30 05:19:45 +00004861 DAG.getContext()->diagnose(BadIntrin);
4862 return DAG.getUNDEF(VT);
4863}
4864
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00004865static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
4866 ArrayRef<SDValue> Elts) {
4867 assert(!Elts.empty());
4868 MVT Type;
4869 unsigned NumElts;
4870
4871 if (Elts.size() == 1) {
4872 Type = MVT::f32;
4873 NumElts = 1;
4874 } else if (Elts.size() == 2) {
4875 Type = MVT::v2f32;
4876 NumElts = 2;
4877 } else if (Elts.size() <= 4) {
4878 Type = MVT::v4f32;
4879 NumElts = 4;
4880 } else if (Elts.size() <= 8) {
4881 Type = MVT::v8f32;
4882 NumElts = 8;
4883 } else {
4884 assert(Elts.size() <= 16);
4885 Type = MVT::v16f32;
4886 NumElts = 16;
4887 }
4888
4889 SmallVector<SDValue, 16> VecElts(NumElts);
4890 for (unsigned i = 0; i < Elts.size(); ++i) {
4891 SDValue Elt = Elts[i];
4892 if (Elt.getValueType() != MVT::f32)
4893 Elt = DAG.getBitcast(MVT::f32, Elt);
4894 VecElts[i] = Elt;
4895 }
4896 for (unsigned i = Elts.size(); i < NumElts; ++i)
4897 VecElts[i] = DAG.getUNDEF(MVT::f32);
4898
4899 if (NumElts == 1)
4900 return VecElts[0];
4901 return DAG.getBuildVector(Type, DL, VecElts);
4902}
4903
4904static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00004905 SDValue *GLC, SDValue *SLC, SDValue *DLC) {
Matt Arsenaultcaf13162019-03-12 21:02:54 +00004906 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00004907
4908 uint64_t Value = CachePolicyConst->getZExtValue();
4909 SDLoc DL(CachePolicy);
4910 if (GLC) {
4911 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
4912 Value &= ~(uint64_t)0x1;
4913 }
4914 if (SLC) {
4915 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
4916 Value &= ~(uint64_t)0x2;
4917 }
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00004918 if (DLC) {
4919 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
4920 Value &= ~(uint64_t)0x4;
4921 }
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00004922
4923 return Value == 0;
4924}
4925
David Stuttardf77079f2019-01-14 11:55:24 +00004926// Re-construct the required return value for a image load intrinsic.
4927// This is more complicated due to the optional use TexFailCtrl which means the required
4928// return type is an aggregate
4929static SDValue constructRetValue(SelectionDAG &DAG,
4930 MachineSDNode *Result,
4931 ArrayRef<EVT> ResultTypes,
4932 bool IsTexFail, bool Unpacked, bool IsD16,
4933 int DMaskPop, int NumVDataDwords,
4934 const SDLoc &DL, LLVMContext &Context) {
4935 // Determine the required return type. This is the same regardless of IsTexFail flag
4936 EVT ReqRetVT = ResultTypes[0];
4937 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT;
4938 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
4939 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT;
4940 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts)
4941 : AdjEltVT
4942 : ReqRetVT;
4943
4944 // Extract data part of the result
4945 // Bitcast the result to the same type as the required return type
4946 int NumElts;
4947 if (IsD16 && !Unpacked)
4948 NumElts = NumVDataDwords << 1;
4949 else
4950 NumElts = NumVDataDwords;
4951
4952 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts)
4953 : AdjEltVT;
4954
Tim Renouf6f0191a2019-03-22 15:21:11 +00004955 // Special case for v6f16. Rather than add support for this, use v3i32 to
David Stuttardf77079f2019-01-14 11:55:24 +00004956 // extract the data elements
Tim Renouf6f0191a2019-03-22 15:21:11 +00004957 bool V6F16Special = false;
4958 if (NumElts == 6) {
4959 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2);
David Stuttardf77079f2019-01-14 11:55:24 +00004960 DMaskPop >>= 1;
4961 ReqRetNumElts >>= 1;
Tim Renouf6f0191a2019-03-22 15:21:11 +00004962 V6F16Special = true;
David Stuttardf77079f2019-01-14 11:55:24 +00004963 AdjVT = MVT::v2i32;
4964 }
4965
4966 SDValue N = SDValue(Result, 0);
4967 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N);
4968
4969 // Iterate over the result
4970 SmallVector<SDValue, 4> BVElts;
4971
4972 if (CastVT.isVector()) {
4973 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop);
4974 } else {
4975 BVElts.push_back(CastRes);
4976 }
4977 int ExtraElts = ReqRetNumElts - DMaskPop;
4978 while(ExtraElts--)
4979 BVElts.push_back(DAG.getUNDEF(AdjEltVT));
4980
4981 SDValue PreTFCRes;
4982 if (ReqRetNumElts > 1) {
4983 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts);
4984 if (IsD16 && Unpacked)
4985 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked);
4986 else
4987 PreTFCRes = NewVec;
4988 } else {
4989 PreTFCRes = BVElts[0];
4990 }
4991
Tim Renouf6f0191a2019-03-22 15:21:11 +00004992 if (V6F16Special)
David Stuttardf77079f2019-01-14 11:55:24 +00004993 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes);
4994
4995 if (!IsTexFail) {
4996 if (Result->getNumValues() > 1)
4997 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL);
4998 else
4999 return PreTFCRes;
5000 }
5001
5002 // Extract the TexFail result and insert into aggregate return
5003 SmallVector<SDValue, 1> TFCElt;
5004 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1);
5005 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]);
5006 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL);
5007}
5008
5009static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5010 SDValue *LWE, bool &IsTexFail) {
Matt Arsenaultcaf13162019-03-12 21:02:54 +00005011 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
David Stuttardf77079f2019-01-14 11:55:24 +00005012
5013 uint64_t Value = TexFailCtrlConst->getZExtValue();
5014 if (Value) {
5015 IsTexFail = true;
5016 }
5017
5018 SDLoc DL(TexFailCtrlConst);
5019 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5020 Value &= ~(uint64_t)0x1;
5021 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5022 Value &= ~(uint64_t)0x2;
5023
5024 return Value == 0;
5025}
5026
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005027SDValue SITargetLowering::lowerImage(SDValue Op,
5028 const AMDGPU::ImageDimIntrinsicInfo *Intr,
5029 SelectionDAG &DAG) const {
5030 SDLoc DL(Op);
Ryan Taylor1f334d02018-08-28 15:07:30 +00005031 MachineFunction &MF = DAG.getMachineFunction();
5032 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005033 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5034 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5035 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
Ryan Taylor894c8fd2018-08-01 12:12:01 +00005036 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5037 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
Piotr Sobczak9b11e932019-06-10 15:58:51 +00005038 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5039 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
Ryan Taylor894c8fd2018-08-01 12:12:01 +00005040 unsigned IntrOpcode = Intr->BaseOpcode;
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005041 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005042
David Stuttardf77079f2019-01-14 11:55:24 +00005043 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5044 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005045 bool IsD16 = false;
Ryan Taylor1f334d02018-08-28 15:07:30 +00005046 bool IsA16 = false;
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005047 SDValue VData;
5048 int NumVDataDwords;
David Stuttardf77079f2019-01-14 11:55:24 +00005049 bool AdjustRetType = false;
5050
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005051 unsigned AddrIdx; // Index of first address argument
5052 unsigned DMask;
David Stuttardf77079f2019-01-14 11:55:24 +00005053 unsigned DMaskLanes = 0;
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005054
5055 if (BaseOpcode->Atomic) {
5056 VData = Op.getOperand(2);
5057
5058 bool Is64Bit = VData.getValueType() == MVT::i64;
5059 if (BaseOpcode->AtomicX2) {
5060 SDValue VData2 = Op.getOperand(3);
5061 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5062 {VData, VData2});
5063 if (Is64Bit)
5064 VData = DAG.getBitcast(MVT::v4i32, VData);
5065
5066 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5067 DMask = Is64Bit ? 0xf : 0x3;
5068 NumVDataDwords = Is64Bit ? 4 : 2;
5069 AddrIdx = 4;
5070 } else {
5071 DMask = Is64Bit ? 0x3 : 0x1;
5072 NumVDataDwords = Is64Bit ? 2 : 1;
5073 AddrIdx = 3;
5074 }
5075 } else {
David Stuttardf77079f2019-01-14 11:55:24 +00005076 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
Matt Arsenaultcaf13162019-03-12 21:02:54 +00005077 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
David Stuttardf77079f2019-01-14 11:55:24 +00005078 DMask = DMaskConst->getZExtValue();
5079 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005080
5081 if (BaseOpcode->Store) {
5082 VData = Op.getOperand(2);
5083
5084 MVT StoreVT = VData.getSimpleValueType();
5085 if (StoreVT.getScalarType() == MVT::f16) {
Matt Arsenaulte4c2e9b2019-06-19 23:54:58 +00005086 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005087 return Op; // D16 is unsupported for this instruction
5088
5089 IsD16 = true;
5090 VData = handleD16VData(VData, DAG);
5091 }
5092
5093 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005094 } else {
David Stuttardf77079f2019-01-14 11:55:24 +00005095 // Work out the num dwords based on the dmask popcount and underlying type
5096 // and whether packing is supported.
5097 MVT LoadVT = ResultTypes[0].getSimpleVT();
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005098 if (LoadVT.getScalarType() == MVT::f16) {
Matt Arsenaulte4c2e9b2019-06-19 23:54:58 +00005099 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005100 return Op; // D16 is unsupported for this instruction
5101
5102 IsD16 = true;
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005103 }
5104
David Stuttardf77079f2019-01-14 11:55:24 +00005105 // Confirm that the return type is large enough for the dmask specified
5106 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5107 (!LoadVT.isVector() && DMaskLanes > 1))
5108 return Op;
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005109
David Stuttardf77079f2019-01-14 11:55:24 +00005110 if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5111 NumVDataDwords = (DMaskLanes + 1) / 2;
5112 else
5113 NumVDataDwords = DMaskLanes;
5114
5115 AdjustRetType = true;
5116 }
David Stuttardc6603862018-11-29 20:14:17 +00005117
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005118 AddrIdx = DMaskIdx + 1;
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005119 }
5120
Ryan Taylor1f334d02018-08-28 15:07:30 +00005121 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5122 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5123 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5124 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5125 NumCoords + NumLCM;
5126 unsigned NumMIVAddrs = NumVAddrs;
5127
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005128 SmallVector<SDValue, 4> VAddrs;
Ryan Taylor894c8fd2018-08-01 12:12:01 +00005129
5130 // Optimize _L to _LZ when _L is zero
5131 if (LZMappingInfo) {
5132 if (auto ConstantLod =
Ryan Taylor1f334d02018-08-28 15:07:30 +00005133 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
Ryan Taylor894c8fd2018-08-01 12:12:01 +00005134 if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5135 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l
Ryan Taylor1f334d02018-08-28 15:07:30 +00005136 NumMIVAddrs--; // remove 'lod'
Ryan Taylor894c8fd2018-08-01 12:12:01 +00005137 }
5138 }
5139 }
5140
Piotr Sobczak9b11e932019-06-10 15:58:51 +00005141 // Optimize _mip away, when 'lod' is zero
5142 if (MIPMappingInfo) {
5143 if (auto ConstantLod =
5144 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5145 if (ConstantLod->isNullValue()) {
5146 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip
5147 NumMIVAddrs--; // remove 'lod'
5148 }
5149 }
5150 }
5151
Ryan Taylor1f334d02018-08-28 15:07:30 +00005152 // Check for 16 bit addresses and pack if true.
5153 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5154 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
Neil Henning63718b22018-10-31 10:34:48 +00005155 const MVT VAddrScalarVT = VAddrVT.getScalarType();
5156 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) &&
Ryan Taylor1f334d02018-08-28 15:07:30 +00005157 ST->hasFeature(AMDGPU::FeatureR128A16)) {
5158 IsA16 = true;
Neil Henning63718b22018-10-31 10:34:48 +00005159 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
Ryan Taylor1f334d02018-08-28 15:07:30 +00005160 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5161 SDValue AddrLo, AddrHi;
5162 // Push back extra arguments.
5163 if (i < DimIdx) {
5164 AddrLo = Op.getOperand(i);
5165 } else {
5166 AddrLo = Op.getOperand(i);
5167 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5168 // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5169 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
Matt Arsenault0da63502018-08-31 05:49:54 +00005170 ((NumGradients / 2) % 2 == 1 &&
5171 (i == DimIdx + (NumGradients / 2) - 1 ||
Ryan Taylor1f334d02018-08-28 15:07:30 +00005172 i == DimIdx + NumGradients - 1))) {
5173 AddrHi = DAG.getUNDEF(MVT::f16);
5174 } else {
5175 AddrHi = Op.getOperand(i + 1);
5176 i++;
5177 }
Neil Henning63718b22018-10-31 10:34:48 +00005178 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT,
Ryan Taylor1f334d02018-08-28 15:07:30 +00005179 {AddrLo, AddrHi});
5180 AddrLo = DAG.getBitcast(MVT::i32, AddrLo);
5181 }
5182 VAddrs.push_back(AddrLo);
5183 }
5184 } else {
5185 for (unsigned i = 0; i < NumMIVAddrs; ++i)
5186 VAddrs.push_back(Op.getOperand(AddrIdx + i));
5187 }
5188
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005189 // If the register allocator cannot place the address registers contiguously
5190 // without introducing moves, then using the non-sequential address encoding
5191 // is always preferable, since it saves VALU instructions and is usually a
5192 // wash in terms of code size or even better.
5193 //
5194 // However, we currently have no way of hinting to the register allocator that
5195 // MIMG addresses should be placed contiguously when it is possible to do so,
5196 // so force non-NSA for the common 2-address case as a heuristic.
5197 //
5198 // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5199 // allocation when possible.
5200 bool UseNSA =
5201 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5202 SDValue VAddr;
5203 if (!UseNSA)
5204 VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005205
5206 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5207 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5208 unsigned CtrlIdx; // Index of texfailctrl argument
5209 SDValue Unorm;
5210 if (!BaseOpcode->Sampler) {
5211 Unorm = True;
5212 CtrlIdx = AddrIdx + NumVAddrs + 1;
5213 } else {
5214 auto UnormConst =
Matt Arsenaultcaf13162019-03-12 21:02:54 +00005215 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005216
5217 Unorm = UnormConst->getZExtValue() ? True : False;
5218 CtrlIdx = AddrIdx + NumVAddrs + 3;
5219 }
5220
David Stuttardf77079f2019-01-14 11:55:24 +00005221 SDValue TFE;
5222 SDValue LWE;
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005223 SDValue TexFail = Op.getOperand(CtrlIdx);
David Stuttardf77079f2019-01-14 11:55:24 +00005224 bool IsTexFail = false;
5225 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005226 return Op;
5227
David Stuttardf77079f2019-01-14 11:55:24 +00005228 if (IsTexFail) {
5229 if (!DMaskLanes) {
5230 // Expecting to get an error flag since TFC is on - and dmask is 0
5231 // Force dmask to be at least 1 otherwise the instruction will fail
5232 DMask = 0x1;
5233 DMaskLanes = 1;
5234 NumVDataDwords = 1;
5235 }
5236 NumVDataDwords += 1;
5237 AdjustRetType = true;
5238 }
5239
5240 // Has something earlier tagged that the return type needs adjusting
5241 // This happens if the instruction is a load or has set TexFailCtrl flags
5242 if (AdjustRetType) {
5243 // NumVDataDwords reflects the true number of dwords required in the return type
5244 if (DMaskLanes == 0 && !BaseOpcode->Store) {
5245 // This is a no-op load. This can be eliminated
5246 SDValue Undef = DAG.getUNDEF(Op.getValueType());
5247 if (isa<MemSDNode>(Op))
5248 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5249 return Undef;
5250 }
5251
David Stuttardf77079f2019-01-14 11:55:24 +00005252 EVT NewVT = NumVDataDwords > 1 ?
5253 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords)
5254 : MVT::f32;
5255
5256 ResultTypes[0] = NewVT;
5257 if (ResultTypes.size() == 3) {
5258 // Original result was aggregate type used for TexFailCtrl results
5259 // The actual instruction returns as a vector type which has now been
5260 // created. Remove the aggregate result.
5261 ResultTypes.erase(&ResultTypes[1]);
5262 }
5263 }
5264
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005265 SDValue GLC;
5266 SDValue SLC;
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005267 SDValue DLC;
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005268 if (BaseOpcode->Atomic) {
5269 GLC = True; // TODO no-return optimization
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005270 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5271 IsGFX10 ? &DLC : nullptr))
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005272 return Op;
5273 } else {
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005274 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5275 IsGFX10 ? &DLC : nullptr))
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005276 return Op;
5277 }
5278
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005279 SmallVector<SDValue, 26> Ops;
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005280 if (BaseOpcode->Store || BaseOpcode->Atomic)
5281 Ops.push_back(VData); // vdata
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005282 if (UseNSA) {
5283 for (const SDValue &Addr : VAddrs)
5284 Ops.push_back(Addr);
5285 } else {
5286 Ops.push_back(VAddr);
5287 }
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005288 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5289 if (BaseOpcode->Sampler)
5290 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5291 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005292 if (IsGFX10)
5293 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005294 Ops.push_back(Unorm);
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005295 if (IsGFX10)
5296 Ops.push_back(DLC);
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005297 Ops.push_back(GLC);
5298 Ops.push_back(SLC);
Ryan Taylor1f334d02018-08-28 15:07:30 +00005299 Ops.push_back(IsA16 && // a16 or r128
5300 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
David Stuttardf77079f2019-01-14 11:55:24 +00005301 Ops.push_back(TFE); // tfe
5302 Ops.push_back(LWE); // lwe
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005303 if (!IsGFX10)
5304 Ops.push_back(DimInfo->DA ? True : False);
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005305 if (BaseOpcode->HasD16)
5306 Ops.push_back(IsD16 ? True : False);
5307 if (isa<MemSDNode>(Op))
5308 Ops.push_back(Op.getOperand(0)); // chain
5309
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005310 int NumVAddrDwords =
5311 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005312 int Opcode = -1;
5313
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005314 if (IsGFX10) {
5315 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5316 UseNSA ? AMDGPU::MIMGEncGfx10NSA
5317 : AMDGPU::MIMGEncGfx10Default,
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005318 NumVDataDwords, NumVAddrDwords);
Stanislav Mekhanoshin692560d2019-05-01 16:32:58 +00005319 } else {
5320 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5321 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5322 NumVDataDwords, NumVAddrDwords);
5323 if (Opcode == -1)
5324 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5325 NumVDataDwords, NumVAddrDwords);
5326 }
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005327 assert(Opcode != -1);
5328
5329 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5330 if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
Chandler Carruth66654b72018-08-14 23:30:32 +00005331 MachineMemOperand *MemRef = MemOp->getMemOperand();
5332 DAG.setNodeMemRefs(NewNode, {MemRef});
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005333 }
5334
5335 if (BaseOpcode->AtomicX2) {
5336 SmallVector<SDValue, 1> Elt;
5337 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5338 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
David Stuttardf77079f2019-01-14 11:55:24 +00005339 } else if (!BaseOpcode->Store) {
5340 return constructRetValue(DAG, NewNode,
5341 OrigResultTypes, IsTexFail,
5342 Subtarget->hasUnpackedD16VMem(), IsD16,
5343 DMaskLanes, NumVDataDwords, DL,
5344 *DAG.getContext());
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005345 }
5346
5347 return SDValue(NewNode, 0);
5348}
5349
Nicolai Haehnlea7b00052018-11-30 22:55:38 +00005350SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
Nicolai Haehnle490e83c2019-06-16 17:14:12 +00005351 SDValue Offset, SDValue GLC, SDValue DLC,
Nicolai Haehnlea7b00052018-11-30 22:55:38 +00005352 SelectionDAG &DAG) const {
5353 MachineFunction &MF = DAG.getMachineFunction();
5354 MachineMemOperand *MMO = MF.getMachineMemOperand(
5355 MachinePointerInfo(),
5356 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5357 MachineMemOperand::MOInvariant,
5358 VT.getStoreSize(), VT.getStoreSize());
5359
5360 if (!Offset->isDivergent()) {
5361 SDValue Ops[] = {
5362 Rsrc,
5363 Offset, // Offset
Nicolai Haehnle490e83c2019-06-16 17:14:12 +00005364 GLC,
5365 DLC,
Nicolai Haehnlea7b00052018-11-30 22:55:38 +00005366 };
5367 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5368 DAG.getVTList(VT), Ops, VT, MMO);
5369 }
5370
5371 // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5372 // assume that the buffer is unswizzled.
5373 SmallVector<SDValue, 4> Loads;
5374 unsigned NumLoads = 1;
5375 MVT LoadVT = VT.getSimpleVT();
Matt Arsenaultce2e0532018-12-07 18:41:39 +00005376 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
Simon Pilgrim44dfd812018-12-07 21:44:25 +00005377 assert((LoadVT.getScalarType() == MVT::i32 ||
5378 LoadVT.getScalarType() == MVT::f32) &&
Matt Arsenaultce2e0532018-12-07 18:41:39 +00005379 isPowerOf2_32(NumElts));
Nicolai Haehnlea7b00052018-11-30 22:55:38 +00005380
Matt Arsenaultce2e0532018-12-07 18:41:39 +00005381 if (NumElts == 8 || NumElts == 16) {
5382 NumLoads = NumElts == 16 ? 4 : 2;
Nicolai Haehnlea7b00052018-11-30 22:55:38 +00005383 LoadVT = MVT::v4i32;
5384 }
5385
5386 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5387 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue();
5388 SDValue Ops[] = {
5389 DAG.getEntryNode(), // Chain
5390 Rsrc, // rsrc
5391 DAG.getConstant(0, DL, MVT::i32), // vindex
5392 {}, // voffset
5393 {}, // soffset
5394 {}, // offset
5395 DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy
5396 DAG.getConstant(0, DL, MVT::i1), // idxen
5397 };
5398
5399 // Use the alignment to ensure that the required offsets will fit into the
5400 // immediate offsets.
5401 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5402
5403 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5404 for (unsigned i = 0; i < NumLoads; ++i) {
5405 Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32);
5406 Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList,
5407 Ops, LoadVT, MMO));
5408 }
5409
5410 if (VT == MVT::v8i32 || VT == MVT::v16i32)
5411 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5412
5413 return Loads[0];
5414}
5415
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005416SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5417 SelectionDAG &DAG) const {
5418 MachineFunction &MF = DAG.getMachineFunction();
Tom Stellarddcb9f092015-07-09 21:20:37 +00005419 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005420
5421 EVT VT = Op.getValueType();
5422 SDLoc DL(Op);
5423 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5424
Sanjay Patela2607012015-09-16 16:31:21 +00005425 // TODO: Should this propagate fast-math-flags?
5426
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005427 switch (IntrinsicID) {
Tom Stellard2f3f9852017-01-25 01:25:13 +00005428 case Intrinsic::amdgcn_implicit_buffer_ptr: {
Konstantin Zhuravlyovaa067cb2018-10-04 21:02:16 +00005429 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
Matt Arsenault10fc0622017-06-26 03:01:31 +00005430 return emitNonHSAIntrinsicError(DAG, DL, VT);
Matt Arsenault8623e8d2017-08-03 23:00:29 +00005431 return getPreloadedValue(DAG, *MFI, VT,
5432 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
Tom Stellard2f3f9852017-01-25 01:25:13 +00005433 }
Tom Stellard48f29f22015-11-26 00:43:29 +00005434 case Intrinsic::amdgcn_dispatch_ptr:
Matt Arsenault48ab5262016-04-25 19:27:18 +00005435 case Intrinsic::amdgcn_queue_ptr: {
Konstantin Zhuravlyovaa067cb2018-10-04 21:02:16 +00005436 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
Oliver Stannard7e7d9832016-02-02 13:52:43 +00005437 DiagnosticInfoUnsupported BadIntrin(
Matthias Braunf1caa282017-12-15 22:22:58 +00005438 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
Oliver Stannard7e7d9832016-02-02 13:52:43 +00005439 DL.getDebugLoc());
Matt Arsenault800fecf2016-01-11 21:18:33 +00005440 DAG.getContext()->diagnose(BadIntrin);
5441 return DAG.getUNDEF(VT);
5442 }
5443
Matt Arsenault8623e8d2017-08-03 23:00:29 +00005444 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5445 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5446 return getPreloadedValue(DAG, *MFI, VT, RegID);
Matt Arsenault48ab5262016-04-25 19:27:18 +00005447 }
Jan Veselyfea814d2016-06-21 20:46:20 +00005448 case Intrinsic::amdgcn_implicitarg_ptr: {
Matt Arsenault9166ce82017-07-28 15:52:08 +00005449 if (MFI->isEntryFunction())
5450 return getImplicitArgPtr(DAG, DL);
Matt Arsenault817c2532017-08-03 23:12:44 +00005451 return getPreloadedValue(DAG, *MFI, VT,
5452 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
Jan Veselyfea814d2016-06-21 20:46:20 +00005453 }
Matt Arsenaultdc4ebad2016-04-29 21:16:52 +00005454 case Intrinsic::amdgcn_kernarg_segment_ptr: {
Matt Arsenault8623e8d2017-08-03 23:00:29 +00005455 return getPreloadedValue(DAG, *MFI, VT,
5456 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
Matt Arsenaultdc4ebad2016-04-29 21:16:52 +00005457 }
Matt Arsenault8d718dc2016-07-22 17:01:30 +00005458 case Intrinsic::amdgcn_dispatch_id: {
Matt Arsenault8623e8d2017-08-03 23:00:29 +00005459 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
Matt Arsenault8d718dc2016-07-22 17:01:30 +00005460 }
Matt Arsenaultf75257a2016-01-23 05:32:20 +00005461 case Intrinsic::amdgcn_rcp:
5462 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5463 case Intrinsic::amdgcn_rsq:
5464 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
Eugene Zelenko66203762017-01-21 00:53:49 +00005465 case Intrinsic::amdgcn_rsq_legacy:
Tom Stellard5bfbae52018-07-11 20:59:01 +00005466 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00005467 return emitRemovedIntrinsicError(DAG, DL, VT);
5468
5469 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
Eugene Zelenko66203762017-01-21 00:53:49 +00005470 case Intrinsic::amdgcn_rcp_legacy:
Tom Stellard5bfbae52018-07-11 20:59:01 +00005471 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
Matt Arsenault32fc5272016-07-26 16:45:45 +00005472 return emitRemovedIntrinsicError(DAG, DL, VT);
5473 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
Matt Arsenault09b2c4a2016-07-15 21:26:52 +00005474 case Intrinsic::amdgcn_rsq_clamp: {
Tom Stellard5bfbae52018-07-11 20:59:01 +00005475 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
Matt Arsenault79963e82016-02-13 01:03:00 +00005476 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
Tom Stellard48f29f22015-11-26 00:43:29 +00005477
Matt Arsenaultf75257a2016-01-23 05:32:20 +00005478 Type *Type = VT.getTypeForEVT(*DAG.getContext());
5479 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5480 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5481
5482 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5483 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5484 DAG.getConstantFP(Max, DL, VT));
5485 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5486 DAG.getConstantFP(Min, DL, VT));
5487 }
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005488 case Intrinsic::r600_read_ngroups_x:
Matt Arsenaulte0132462016-01-30 05:19:45 +00005489 if (Subtarget->isAmdHsaOS())
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00005490 return emitNonHSAIntrinsicError(DAG, DL, VT);
Matt Arsenaulte0132462016-01-30 05:19:45 +00005491
Matt Arsenaulte622dc32017-04-11 22:29:24 +00005492 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
Matt Arsenault7b4826e2018-05-30 16:17:51 +00005493 SI::KernelInputOffsets::NGROUPS_X, 4, false);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005494 case Intrinsic::r600_read_ngroups_y:
Matt Arsenaulte0132462016-01-30 05:19:45 +00005495 if (Subtarget->isAmdHsaOS())
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00005496 return emitNonHSAIntrinsicError(DAG, DL, VT);
Matt Arsenaulte0132462016-01-30 05:19:45 +00005497
Matt Arsenaulte622dc32017-04-11 22:29:24 +00005498 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
Matt Arsenault7b4826e2018-05-30 16:17:51 +00005499 SI::KernelInputOffsets::NGROUPS_Y, 4, false);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005500 case Intrinsic::r600_read_ngroups_z:
Matt Arsenaulte0132462016-01-30 05:19:45 +00005501 if (Subtarget->isAmdHsaOS())
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00005502 return emitNonHSAIntrinsicError(DAG, DL, VT);
Matt Arsenaulte0132462016-01-30 05:19:45 +00005503
Matt Arsenaulte622dc32017-04-11 22:29:24 +00005504 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
Matt Arsenault7b4826e2018-05-30 16:17:51 +00005505 SI::KernelInputOffsets::NGROUPS_Z, 4, false);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005506 case Intrinsic::r600_read_global_size_x:
Matt Arsenaulte0132462016-01-30 05:19:45 +00005507 if (Subtarget->isAmdHsaOS())
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00005508 return emitNonHSAIntrinsicError(DAG, DL, VT);
Matt Arsenaulte0132462016-01-30 05:19:45 +00005509
Matt Arsenaulte622dc32017-04-11 22:29:24 +00005510 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
Matt Arsenault7b4826e2018-05-30 16:17:51 +00005511 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005512 case Intrinsic::r600_read_global_size_y:
Matt Arsenaulte0132462016-01-30 05:19:45 +00005513 if (Subtarget->isAmdHsaOS())
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00005514 return emitNonHSAIntrinsicError(DAG, DL, VT);
Matt Arsenaulte0132462016-01-30 05:19:45 +00005515
Matt Arsenaulte622dc32017-04-11 22:29:24 +00005516 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
Matt Arsenault7b4826e2018-05-30 16:17:51 +00005517 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005518 case Intrinsic::r600_read_global_size_z:
Matt Arsenaulte0132462016-01-30 05:19:45 +00005519 if (Subtarget->isAmdHsaOS())
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00005520 return emitNonHSAIntrinsicError(DAG, DL, VT);
Matt Arsenaulte0132462016-01-30 05:19:45 +00005521
Matt Arsenaulte622dc32017-04-11 22:29:24 +00005522 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
Matt Arsenault7b4826e2018-05-30 16:17:51 +00005523 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005524 case Intrinsic::r600_read_local_size_x:
Matt Arsenaulte0132462016-01-30 05:19:45 +00005525 if (Subtarget->isAmdHsaOS())
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00005526 return emitNonHSAIntrinsicError(DAG, DL, VT);
Matt Arsenaulte0132462016-01-30 05:19:45 +00005527
Matt Arsenaultff6da2f2015-11-30 21:15:45 +00005528 return lowerImplicitZextParam(DAG, Op, MVT::i16,
5529 SI::KernelInputOffsets::LOCAL_SIZE_X);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005530 case Intrinsic::r600_read_local_size_y:
Matt Arsenaulte0132462016-01-30 05:19:45 +00005531 if (Subtarget->isAmdHsaOS())
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00005532 return emitNonHSAIntrinsicError(DAG, DL, VT);
Matt Arsenaulte0132462016-01-30 05:19:45 +00005533
Matt Arsenaultff6da2f2015-11-30 21:15:45 +00005534 return lowerImplicitZextParam(DAG, Op, MVT::i16,
5535 SI::KernelInputOffsets::LOCAL_SIZE_Y);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005536 case Intrinsic::r600_read_local_size_z:
Matt Arsenaulte0132462016-01-30 05:19:45 +00005537 if (Subtarget->isAmdHsaOS())
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00005538 return emitNonHSAIntrinsicError(DAG, DL, VT);
Matt Arsenaulte0132462016-01-30 05:19:45 +00005539
Matt Arsenaultff6da2f2015-11-30 21:15:45 +00005540 return lowerImplicitZextParam(DAG, Op, MVT::i16,
5541 SI::KernelInputOffsets::LOCAL_SIZE_Z);
Matt Arsenault43976df2016-01-30 04:25:19 +00005542 case Intrinsic::amdgcn_workgroup_id_x:
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005543 case Intrinsic::r600_read_tgid_x:
Matt Arsenault8623e8d2017-08-03 23:00:29 +00005544 return getPreloadedValue(DAG, *MFI, VT,
5545 AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
Matt Arsenault43976df2016-01-30 04:25:19 +00005546 case Intrinsic::amdgcn_workgroup_id_y:
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005547 case Intrinsic::r600_read_tgid_y:
Matt Arsenault8623e8d2017-08-03 23:00:29 +00005548 return getPreloadedValue(DAG, *MFI, VT,
5549 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
Matt Arsenault43976df2016-01-30 04:25:19 +00005550 case Intrinsic::amdgcn_workgroup_id_z:
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005551 case Intrinsic::r600_read_tgid_z:
Matt Arsenault8623e8d2017-08-03 23:00:29 +00005552 return getPreloadedValue(DAG, *MFI, VT,
5553 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00005554 case Intrinsic::amdgcn_workitem_id_x:
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005555 case Intrinsic::r600_read_tidig_x:
Matt Arsenault8623e8d2017-08-03 23:00:29 +00005556 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5557 SDLoc(DAG.getEntryNode()),
5558 MFI->getArgInfo().WorkItemIDX);
Matt Arsenault43976df2016-01-30 04:25:19 +00005559 case Intrinsic::amdgcn_workitem_id_y:
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005560 case Intrinsic::r600_read_tidig_y:
Matt Arsenault8623e8d2017-08-03 23:00:29 +00005561 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5562 SDLoc(DAG.getEntryNode()),
5563 MFI->getArgInfo().WorkItemIDY);
Matt Arsenault43976df2016-01-30 04:25:19 +00005564 case Intrinsic::amdgcn_workitem_id_z:
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005565 case Intrinsic::r600_read_tidig_z:
Matt Arsenault8623e8d2017-08-03 23:00:29 +00005566 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5567 SDLoc(DAG.getEntryNode()),
5568 MFI->getArgInfo().WorkItemIDZ);
Stanislav Mekhanoshin68a2fef2019-06-13 23:47:36 +00005569 case Intrinsic::amdgcn_wavefrontsize:
5570 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5571 SDLoc(Op), MVT::i32);
Tim Renouf904343f2018-08-25 14:53:17 +00005572 case Intrinsic::amdgcn_s_buffer_load: {
Nicolai Haehnle490e83c2019-06-16 17:14:12 +00005573 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5574 SDValue GLC;
5575 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5576 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5577 IsGFX10 ? &DLC : nullptr))
5578 return Op;
5579 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC,
5580 DAG);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005581 }
Matt Arsenaultc5b641a2017-03-17 20:41:45 +00005582 case Intrinsic::amdgcn_fdiv_fast:
Matt Arsenaulta1fe17c2016-07-19 23:16:53 +00005583 return lowerFDIV_FAST(Op, DAG);
Tom Stellard2187bb82016-12-06 23:52:13 +00005584 case Intrinsic::amdgcn_interp_mov: {
5585 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5586 SDValue Glue = M0.getValue(1);
5587 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
5588 Op.getOperand(2), Op.getOperand(3), Glue);
5589 }
Tom Stellardad7d03d2015-12-15 17:02:49 +00005590 case Intrinsic::amdgcn_interp_p1: {
5591 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5592 SDValue Glue = M0.getValue(1);
5593 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
5594 Op.getOperand(2), Op.getOperand(3), Glue);
5595 }
5596 case Intrinsic::amdgcn_interp_p2: {
5597 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5598 SDValue Glue = SDValue(M0.getNode(), 1);
5599 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
5600 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
5601 Glue);
5602 }
Tim Corringham824ca3f2019-01-28 13:48:59 +00005603 case Intrinsic::amdgcn_interp_p1_f16: {
5604 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5605 SDValue Glue = M0.getValue(1);
5606 if (getSubtarget()->getLDSBankCount() == 16) {
5607 // 16 bank LDS
5608 SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
5609 DAG.getConstant(2, DL, MVT::i32), // P0
5610 Op.getOperand(2), // Attrchan
5611 Op.getOperand(3), // Attr
5612 Glue);
5613 SDValue Ops[] = {
5614 Op.getOperand(1), // Src0
5615 Op.getOperand(2), // Attrchan
5616 Op.getOperand(3), // Attr
5617 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5618 S, // Src2 - holds two f16 values selected by high
5619 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5620 Op.getOperand(4), // high
5621 DAG.getConstant(0, DL, MVT::i1), // $clamp
5622 DAG.getConstant(0, DL, MVT::i32) // $omod
5623 };
5624 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops);
5625 } else {
5626 // 32 bank LDS
5627 SDValue Ops[] = {
5628 Op.getOperand(1), // Src0
5629 Op.getOperand(2), // Attrchan
5630 Op.getOperand(3), // Attr
5631 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5632 Op.getOperand(4), // high
5633 DAG.getConstant(0, DL, MVT::i1), // $clamp
5634 DAG.getConstant(0, DL, MVT::i32), // $omod
5635 Glue
5636 };
5637 return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops);
5638 }
5639 }
5640 case Intrinsic::amdgcn_interp_p2_f16: {
5641 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6));
5642 SDValue Glue = SDValue(M0.getNode(), 1);
5643 SDValue Ops[] = {
5644 Op.getOperand(2), // Src0
5645 Op.getOperand(3), // Attrchan
5646 Op.getOperand(4), // Attr
5647 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5648 Op.getOperand(1), // Src2
5649 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5650 Op.getOperand(5), // high
5651 DAG.getConstant(0, DL, MVT::i1), // $clamp
5652 Glue
5653 };
5654 return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops);
5655 }
Matt Arsenaultce56a0e2016-02-13 01:19:56 +00005656 case Intrinsic::amdgcn_sin:
5657 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5658
5659 case Intrinsic::amdgcn_cos:
5660 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5661
5662 case Intrinsic::amdgcn_log_clamp: {
Tom Stellard5bfbae52018-07-11 20:59:01 +00005663 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
Matt Arsenaultce56a0e2016-02-13 01:19:56 +00005664 return SDValue();
5665
5666 DiagnosticInfoUnsupported BadIntrin(
Matthias Braunf1caa282017-12-15 22:22:58 +00005667 MF.getFunction(), "intrinsic not supported on subtarget",
Matt Arsenaultce56a0e2016-02-13 01:19:56 +00005668 DL.getDebugLoc());
5669 DAG.getContext()->diagnose(BadIntrin);
5670 return DAG.getUNDEF(VT);
5671 }
Matt Arsenaultf75257a2016-01-23 05:32:20 +00005672 case Intrinsic::amdgcn_ldexp:
5673 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5674 Op.getOperand(1), Op.getOperand(2));
Matt Arsenault74015162016-05-28 00:19:52 +00005675
5676 case Intrinsic::amdgcn_fract:
5677 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5678
Matt Arsenaultf75257a2016-01-23 05:32:20 +00005679 case Intrinsic::amdgcn_class:
5680 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5681 Op.getOperand(1), Op.getOperand(2));
5682 case Intrinsic::amdgcn_div_fmas:
5683 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5684 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5685 Op.getOperand(4));
5686
5687 case Intrinsic::amdgcn_div_fixup:
5688 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5689 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5690
5691 case Intrinsic::amdgcn_trig_preop:
5692 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5693 Op.getOperand(1), Op.getOperand(2));
5694 case Intrinsic::amdgcn_div_scale: {
Matt Arsenaultcaf13162019-03-12 21:02:54 +00005695 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
Matt Arsenaultf75257a2016-01-23 05:32:20 +00005696
5697 // Translate to the operands expected by the machine instruction. The
5698 // first parameter must be the same as the first instruction.
5699 SDValue Numerator = Op.getOperand(1);
5700 SDValue Denominator = Op.getOperand(2);
5701
5702 // Note this order is opposite of the machine instruction's operations,
5703 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5704 // intrinsic has the numerator as the first operand to match a normal
5705 // division operation.
5706
5707 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
5708
5709 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
5710 Denominator, Numerator);
5711 }
Wei Ding07e03712016-07-28 16:42:13 +00005712 case Intrinsic::amdgcn_icmp: {
Marek Olsak33eb4d92019-01-15 02:13:18 +00005713 // There is a Pat that handles this variant, so return it as-is.
5714 if (Op.getOperand(1).getValueType() == MVT::i1 &&
5715 Op.getConstantOperandVal(2) == 0 &&
5716 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
5717 return Op;
Matt Arsenaultb3a80e52018-08-15 21:25:20 +00005718 return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
Wei Ding07e03712016-07-28 16:42:13 +00005719 }
5720 case Intrinsic::amdgcn_fcmp: {
Matt Arsenaultb3a80e52018-08-15 21:25:20 +00005721 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
Wei Ding07e03712016-07-28 16:42:13 +00005722 }
Matt Arsenaultf84e5d92017-01-31 03:07:46 +00005723 case Intrinsic::amdgcn_fmed3:
5724 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
5725 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
Farhana Aleenc370d7b2018-07-16 18:19:59 +00005726 case Intrinsic::amdgcn_fdot2:
5727 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
Konstantin Zhuravlyovbb30ef72018-08-01 01:31:30 +00005728 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5729 Op.getOperand(4));
Matt Arsenault32fc5272016-07-26 16:45:45 +00005730 case Intrinsic::amdgcn_fmul_legacy:
5731 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
5732 Op.getOperand(1), Op.getOperand(2));
Matt Arsenaultc96e1de2016-07-18 18:35:05 +00005733 case Intrinsic::amdgcn_sffbh:
Matt Arsenaultc96e1de2016-07-18 18:35:05 +00005734 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
Matt Arsenaultf5262252017-02-22 23:04:58 +00005735 case Intrinsic::amdgcn_sbfe:
5736 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
5737 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5738 case Intrinsic::amdgcn_ubfe:
5739 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
5740 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
Marek Olsak13e47412018-01-31 20:18:04 +00005741 case Intrinsic::amdgcn_cvt_pkrtz:
5742 case Intrinsic::amdgcn_cvt_pknorm_i16:
5743 case Intrinsic::amdgcn_cvt_pknorm_u16:
5744 case Intrinsic::amdgcn_cvt_pk_i16:
5745 case Intrinsic::amdgcn_cvt_pk_u16: {
5746 // FIXME: Stop adding cast if v2f16/v2i16 are legal.
Matt Arsenault1f17c662017-02-22 00:27:34 +00005747 EVT VT = Op.getValueType();
Marek Olsak13e47412018-01-31 20:18:04 +00005748 unsigned Opcode;
5749
5750 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
5751 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
5752 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
5753 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5754 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
5755 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5756 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
5757 Opcode = AMDGPUISD::CVT_PK_I16_I32;
5758 else
5759 Opcode = AMDGPUISD::CVT_PK_U16_U32;
5760
Matt Arsenault709374d2018-08-01 20:13:58 +00005761 if (isTypeLegal(VT))
5762 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
5763
Marek Olsak13e47412018-01-31 20:18:04 +00005764 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
Matt Arsenault1f17c662017-02-22 00:27:34 +00005765 Op.getOperand(1), Op.getOperand(2));
5766 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
5767 }
Connor Abbott8c217d02017-08-04 18:36:49 +00005768 case Intrinsic::amdgcn_wqm: {
5769 SDValue Src = Op.getOperand(1);
5770 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
5771 0);
5772 }
Connor Abbott92638ab2017-08-04 18:36:52 +00005773 case Intrinsic::amdgcn_wwm: {
5774 SDValue Src = Op.getOperand(1);
5775 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
5776 0);
5777 }
Stanislav Mekhanoshindacda792018-06-26 20:04:19 +00005778 case Intrinsic::amdgcn_fmad_ftz:
5779 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
5780 Op.getOperand(2), Op.getOperand(3));
Stanislav Mekhanoshin68a2fef2019-06-13 23:47:36 +00005781
5782 case Intrinsic::amdgcn_if_break:
5783 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
5784 Op->getOperand(1), Op->getOperand(2)), 0);
5785
Nicolai Haehnle27101712019-06-25 11:52:30 +00005786 case Intrinsic::amdgcn_groupstaticsize: {
5787 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
5788 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
5789 return Op;
5790
5791 const Module *M = MF.getFunction().getParent();
5792 const GlobalValue *GV =
5793 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
5794 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
5795 SIInstrInfo::MO_ABS32_LO);
5796 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
5797 }
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005798 default:
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00005799 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5800 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5801 return lowerImage(Op, ImageDimIntr, DAG);
5802
Matt Arsenault754dd3e2017-04-03 18:08:08 +00005803 return Op;
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00005804 }
5805}
5806
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +00005807SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
5808 SelectionDAG &DAG) const {
5809 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
Tom Stellard6f9ef142016-12-20 17:19:44 +00005810 SDLoc DL(Op);
David Stuttard70e8bc12017-06-22 16:29:22 +00005811
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +00005812 switch (IntrID) {
Marek Olsakc5cec5e2019-01-16 15:43:53 +00005813 case Intrinsic::amdgcn_ds_ordered_add:
5814 case Intrinsic::amdgcn_ds_ordered_swap: {
5815 MemSDNode *M = cast<MemSDNode>(Op);
5816 SDValue Chain = M->getOperand(0);
5817 SDValue M0 = M->getOperand(2);
5818 SDValue Value = M->getOperand(3);
5819 unsigned OrderedCountIndex = M->getConstantOperandVal(7);
5820 unsigned WaveRelease = M->getConstantOperandVal(8);
5821 unsigned WaveDone = M->getConstantOperandVal(9);
5822 unsigned ShaderType;
5823 unsigned Instruction;
5824
5825 switch (IntrID) {
5826 case Intrinsic::amdgcn_ds_ordered_add:
5827 Instruction = 0;
5828 break;
5829 case Intrinsic::amdgcn_ds_ordered_swap:
5830 Instruction = 1;
5831 break;
5832 }
5833
5834 if (WaveDone && !WaveRelease)
5835 report_fatal_error("ds_ordered_count: wave_done requires wave_release");
5836
5837 switch (DAG.getMachineFunction().getFunction().getCallingConv()) {
5838 case CallingConv::AMDGPU_CS:
5839 case CallingConv::AMDGPU_KERNEL:
5840 ShaderType = 0;
5841 break;
5842 case CallingConv::AMDGPU_PS:
5843 ShaderType = 1;
5844 break;
5845 case CallingConv::AMDGPU_VS:
5846 ShaderType = 2;
5847 break;
5848 case CallingConv::AMDGPU_GS:
5849 ShaderType = 3;
5850 break;
5851 default:
5852 report_fatal_error("ds_ordered_count unsupported for this calling conv");
5853 }
5854
5855 unsigned Offset0 = OrderedCountIndex << 2;
5856 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
5857 (Instruction << 4);
5858 unsigned Offset = Offset0 | (Offset1 << 8);
5859
5860 SDValue Ops[] = {
5861 Chain,
5862 Value,
5863 DAG.getTargetConstant(Offset, DL, MVT::i16),
5864 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
5865 };
5866 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
5867 M->getVTList(), Ops, M->getMemoryVT(),
5868 M->getMemOperand());
5869 }
Matt Arsenaulta5840c32019-01-22 18:36:06 +00005870 case Intrinsic::amdgcn_ds_fadd: {
5871 MemSDNode *M = cast<MemSDNode>(Op);
5872 unsigned Opc;
5873 switch (IntrID) {
5874 case Intrinsic::amdgcn_ds_fadd:
5875 Opc = ISD::ATOMIC_LOAD_FADD;
5876 break;
5877 }
5878
5879 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
5880 M->getOperand(0), M->getOperand(2), M->getOperand(3),
5881 M->getMemOperand());
5882 }
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +00005883 case Intrinsic::amdgcn_atomic_inc:
Daniil Fukalovd5fca552018-01-17 14:05:05 +00005884 case Intrinsic::amdgcn_atomic_dec:
Daniil Fukalov6e1dc682018-01-26 11:09:38 +00005885 case Intrinsic::amdgcn_ds_fmin:
5886 case Intrinsic::amdgcn_ds_fmax: {
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +00005887 MemSDNode *M = cast<MemSDNode>(Op);
Daniil Fukalovd5fca552018-01-17 14:05:05 +00005888 unsigned Opc;
5889 switch (IntrID) {
5890 case Intrinsic::amdgcn_atomic_inc:
5891 Opc = AMDGPUISD::ATOMIC_INC;
5892 break;
5893 case Intrinsic::amdgcn_atomic_dec:
5894 Opc = AMDGPUISD::ATOMIC_DEC;
5895 break;
Daniil Fukalov6e1dc682018-01-26 11:09:38 +00005896 case Intrinsic::amdgcn_ds_fmin:
Daniil Fukalovd5fca552018-01-17 14:05:05 +00005897 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
5898 break;
Daniil Fukalov6e1dc682018-01-26 11:09:38 +00005899 case Intrinsic::amdgcn_ds_fmax:
Daniil Fukalovd5fca552018-01-17 14:05:05 +00005900 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
5901 break;
5902 default:
5903 llvm_unreachable("Unknown intrinsic!");
5904 }
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +00005905 SDValue Ops[] = {
5906 M->getOperand(0), // Chain
5907 M->getOperand(2), // Ptr
5908 M->getOperand(3) // Value
5909 };
5910
5911 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
5912 M->getMemoryVT(), M->getMemOperand());
5913 }
Tom Stellard6f9ef142016-12-20 17:19:44 +00005914 case Intrinsic::amdgcn_buffer_load:
5915 case Intrinsic::amdgcn_buffer_load_format: {
Tim Renouf4f703f52018-08-21 11:07:10 +00005916 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
5917 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
5918 unsigned IdxEn = 1;
5919 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
5920 IdxEn = Idx->getZExtValue() != 0;
Tom Stellard6f9ef142016-12-20 17:19:44 +00005921 SDValue Ops[] = {
5922 Op.getOperand(0), // Chain
5923 Op.getOperand(2), // rsrc
5924 Op.getOperand(3), // vindex
Tim Renouf4f703f52018-08-21 11:07:10 +00005925 SDValue(), // voffset -- will be set by setBufferOffsets
5926 SDValue(), // soffset -- will be set by setBufferOffsets
5927 SDValue(), // offset -- will be set by setBufferOffsets
5928 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
5929 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
Tom Stellard6f9ef142016-12-20 17:19:44 +00005930 };
Tom Stellard6f9ef142016-12-20 17:19:44 +00005931
Tim Renouf4f703f52018-08-21 11:07:10 +00005932 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
Tom Stellard6f9ef142016-12-20 17:19:44 +00005933 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
5934 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
Tim Renouf4f703f52018-08-21 11:07:10 +00005935
5936 EVT VT = Op.getValueType();
5937 EVT IntVT = VT.changeTypeToInteger();
5938 auto *M = cast<MemSDNode>(Op);
5939 EVT LoadVT = Op.getValueType();
5940
5941 if (LoadVT.getScalarType() == MVT::f16)
5942 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
5943 M, DAG, Ops);
Ryan Taylor00e063a2019-03-19 16:07:00 +00005944
5945 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
5946 if (LoadVT.getScalarType() == MVT::i8 ||
5947 LoadVT.getScalarType() == MVT::i16)
5948 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
5949
Tim Renouf677387d2019-03-22 14:58:02 +00005950 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5951 M->getMemOperand(), DAG);
Tim Renouf4f703f52018-08-21 11:07:10 +00005952 }
5953 case Intrinsic::amdgcn_raw_buffer_load:
5954 case Intrinsic::amdgcn_raw_buffer_load_format: {
5955 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
5956 SDValue Ops[] = {
5957 Op.getOperand(0), // Chain
5958 Op.getOperand(2), // rsrc
5959 DAG.getConstant(0, DL, MVT::i32), // vindex
5960 Offsets.first, // voffset
5961 Op.getOperand(4), // soffset
5962 Offsets.second, // offset
5963 Op.getOperand(5), // cachepolicy
5964 DAG.getConstant(0, DL, MVT::i1), // idxen
5965 };
5966
5967 unsigned Opc = (IntrID == Intrinsic::amdgcn_raw_buffer_load) ?
5968 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5969
5970 EVT VT = Op.getValueType();
5971 EVT IntVT = VT.changeTypeToInteger();
5972 auto *M = cast<MemSDNode>(Op);
5973 EVT LoadVT = Op.getValueType();
5974
5975 if (LoadVT.getScalarType() == MVT::f16)
5976 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
5977 M, DAG, Ops);
Ryan Taylor00e063a2019-03-19 16:07:00 +00005978
5979 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
5980 if (LoadVT.getScalarType() == MVT::i8 ||
5981 LoadVT.getScalarType() == MVT::i16)
5982 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
5983
Tim Renouf677387d2019-03-22 14:58:02 +00005984 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5985 M->getMemOperand(), DAG);
Tim Renouf4f703f52018-08-21 11:07:10 +00005986 }
5987 case Intrinsic::amdgcn_struct_buffer_load:
5988 case Intrinsic::amdgcn_struct_buffer_load_format: {
5989 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
5990 SDValue Ops[] = {
5991 Op.getOperand(0), // Chain
5992 Op.getOperand(2), // rsrc
5993 Op.getOperand(3), // vindex
5994 Offsets.first, // voffset
5995 Op.getOperand(5), // soffset
5996 Offsets.second, // offset
5997 Op.getOperand(6), // cachepolicy
5998 DAG.getConstant(1, DL, MVT::i1), // idxen
5999 };
6000
6001 unsigned Opc = (IntrID == Intrinsic::amdgcn_struct_buffer_load) ?
6002 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6003
Tom Stellard6f9ef142016-12-20 17:19:44 +00006004 EVT VT = Op.getValueType();
6005 EVT IntVT = VT.changeTypeToInteger();
Matt Arsenaulte19bc2e2017-12-29 17:18:21 +00006006 auto *M = cast<MemSDNode>(Op);
Matt Arsenault1349a042018-05-22 06:32:10 +00006007 EVT LoadVT = Op.getValueType();
Matt Arsenault1349a042018-05-22 06:32:10 +00006008
Tim Renouf366a49d2018-08-02 23:33:01 +00006009 if (LoadVT.getScalarType() == MVT::f16)
6010 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6011 M, DAG, Ops);
Ryan Taylor00e063a2019-03-19 16:07:00 +00006012
6013 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6014 if (LoadVT.getScalarType() == MVT::i8 ||
6015 LoadVT.getScalarType() == MVT::i16)
6016 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6017
Tim Renouf677387d2019-03-22 14:58:02 +00006018 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6019 M->getMemOperand(), DAG);
Tom Stellard6f9ef142016-12-20 17:19:44 +00006020 }
David Stuttard70e8bc12017-06-22 16:29:22 +00006021 case Intrinsic::amdgcn_tbuffer_load: {
Matt Arsenaulte19bc2e2017-12-29 17:18:21 +00006022 MemSDNode *M = cast<MemSDNode>(Op);
Matt Arsenault1349a042018-05-22 06:32:10 +00006023 EVT LoadVT = Op.getValueType();
Matt Arsenault1349a042018-05-22 06:32:10 +00006024
Tim Renouf35484c92018-08-21 11:06:05 +00006025 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6026 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6027 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6028 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6029 unsigned IdxEn = 1;
6030 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6031 IdxEn = Idx->getZExtValue() != 0;
David Stuttard70e8bc12017-06-22 16:29:22 +00006032 SDValue Ops[] = {
6033 Op.getOperand(0), // Chain
6034 Op.getOperand(2), // rsrc
6035 Op.getOperand(3), // vindex
6036 Op.getOperand(4), // voffset
6037 Op.getOperand(5), // soffset
6038 Op.getOperand(6), // offset
Tim Renouf35484c92018-08-21 11:06:05 +00006039 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6040 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6041 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6042 };
6043
6044 if (LoadVT.getScalarType() == MVT::f16)
6045 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6046 M, DAG, Ops);
Tim Renouf677387d2019-03-22 14:58:02 +00006047 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6048 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6049 DAG);
Tim Renouf35484c92018-08-21 11:06:05 +00006050 }
6051 case Intrinsic::amdgcn_raw_tbuffer_load: {
6052 MemSDNode *M = cast<MemSDNode>(Op);
6053 EVT LoadVT = Op.getValueType();
6054 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6055
6056 SDValue Ops[] = {
6057 Op.getOperand(0), // Chain
6058 Op.getOperand(2), // rsrc
6059 DAG.getConstant(0, DL, MVT::i32), // vindex
6060 Offsets.first, // voffset
6061 Op.getOperand(4), // soffset
6062 Offsets.second, // offset
6063 Op.getOperand(5), // format
6064 Op.getOperand(6), // cachepolicy
6065 DAG.getConstant(0, DL, MVT::i1), // idxen
6066 };
6067
6068 if (LoadVT.getScalarType() == MVT::f16)
6069 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6070 M, DAG, Ops);
Tim Renouf677387d2019-03-22 14:58:02 +00006071 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6072 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6073 DAG);
Tim Renouf35484c92018-08-21 11:06:05 +00006074 }
6075 case Intrinsic::amdgcn_struct_tbuffer_load: {
6076 MemSDNode *M = cast<MemSDNode>(Op);
6077 EVT LoadVT = Op.getValueType();
6078 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6079
6080 SDValue Ops[] = {
6081 Op.getOperand(0), // Chain
6082 Op.getOperand(2), // rsrc
6083 Op.getOperand(3), // vindex
6084 Offsets.first, // voffset
6085 Op.getOperand(5), // soffset
6086 Offsets.second, // offset
6087 Op.getOperand(6), // format
6088 Op.getOperand(7), // cachepolicy
6089 DAG.getConstant(1, DL, MVT::i1), // idxen
David Stuttard70e8bc12017-06-22 16:29:22 +00006090 };
6091
Tim Renouf366a49d2018-08-02 23:33:01 +00006092 if (LoadVT.getScalarType() == MVT::f16)
6093 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6094 M, DAG, Ops);
Tim Renouf677387d2019-03-22 14:58:02 +00006095 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6096 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6097 DAG);
David Stuttard70e8bc12017-06-22 16:29:22 +00006098 }
Marek Olsak5cec6412017-11-09 01:52:48 +00006099 case Intrinsic::amdgcn_buffer_atomic_swap:
6100 case Intrinsic::amdgcn_buffer_atomic_add:
6101 case Intrinsic::amdgcn_buffer_atomic_sub:
6102 case Intrinsic::amdgcn_buffer_atomic_smin:
6103 case Intrinsic::amdgcn_buffer_atomic_umin:
6104 case Intrinsic::amdgcn_buffer_atomic_smax:
6105 case Intrinsic::amdgcn_buffer_atomic_umax:
6106 case Intrinsic::amdgcn_buffer_atomic_and:
6107 case Intrinsic::amdgcn_buffer_atomic_or:
6108 case Intrinsic::amdgcn_buffer_atomic_xor: {
Tim Renouf4f703f52018-08-21 11:07:10 +00006109 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6110 unsigned IdxEn = 1;
6111 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6112 IdxEn = Idx->getZExtValue() != 0;
Marek Olsak5cec6412017-11-09 01:52:48 +00006113 SDValue Ops[] = {
6114 Op.getOperand(0), // Chain
6115 Op.getOperand(2), // vdata
6116 Op.getOperand(3), // rsrc
6117 Op.getOperand(4), // vindex
Tim Renouf4f703f52018-08-21 11:07:10 +00006118 SDValue(), // voffset -- will be set by setBufferOffsets
6119 SDValue(), // soffset -- will be set by setBufferOffsets
6120 SDValue(), // offset -- will be set by setBufferOffsets
6121 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6122 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
Marek Olsak5cec6412017-11-09 01:52:48 +00006123 };
Tim Renouf4f703f52018-08-21 11:07:10 +00006124 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
Matt Arsenaulte19bc2e2017-12-29 17:18:21 +00006125 EVT VT = Op.getValueType();
6126
6127 auto *M = cast<MemSDNode>(Op);
Marek Olsak5cec6412017-11-09 01:52:48 +00006128 unsigned Opcode = 0;
6129
6130 switch (IntrID) {
6131 case Intrinsic::amdgcn_buffer_atomic_swap:
6132 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6133 break;
6134 case Intrinsic::amdgcn_buffer_atomic_add:
6135 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6136 break;
6137 case Intrinsic::amdgcn_buffer_atomic_sub:
6138 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6139 break;
6140 case Intrinsic::amdgcn_buffer_atomic_smin:
6141 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6142 break;
6143 case Intrinsic::amdgcn_buffer_atomic_umin:
6144 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6145 break;
6146 case Intrinsic::amdgcn_buffer_atomic_smax:
6147 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6148 break;
6149 case Intrinsic::amdgcn_buffer_atomic_umax:
6150 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6151 break;
6152 case Intrinsic::amdgcn_buffer_atomic_and:
6153 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6154 break;
6155 case Intrinsic::amdgcn_buffer_atomic_or:
6156 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6157 break;
6158 case Intrinsic::amdgcn_buffer_atomic_xor:
6159 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6160 break;
6161 default:
6162 llvm_unreachable("unhandled atomic opcode");
6163 }
6164
Matt Arsenaulte19bc2e2017-12-29 17:18:21 +00006165 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6166 M->getMemOperand());
Marek Olsak5cec6412017-11-09 01:52:48 +00006167 }
Tim Renouf4f703f52018-08-21 11:07:10 +00006168 case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6169 case Intrinsic::amdgcn_raw_buffer_atomic_add:
6170 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6171 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6172 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6173 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6174 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6175 case Intrinsic::amdgcn_raw_buffer_atomic_and:
6176 case Intrinsic::amdgcn_raw_buffer_atomic_or:
6177 case Intrinsic::amdgcn_raw_buffer_atomic_xor: {
6178 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6179 SDValue Ops[] = {
6180 Op.getOperand(0), // Chain
6181 Op.getOperand(2), // vdata
6182 Op.getOperand(3), // rsrc
6183 DAG.getConstant(0, DL, MVT::i32), // vindex
6184 Offsets.first, // voffset
6185 Op.getOperand(5), // soffset
6186 Offsets.second, // offset
6187 Op.getOperand(6), // cachepolicy
6188 DAG.getConstant(0, DL, MVT::i1), // idxen
6189 };
6190 EVT VT = Op.getValueType();
Marek Olsak5cec6412017-11-09 01:52:48 +00006191
Tim Renouf4f703f52018-08-21 11:07:10 +00006192 auto *M = cast<MemSDNode>(Op);
6193 unsigned Opcode = 0;
6194
6195 switch (IntrID) {
6196 case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6197 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6198 break;
6199 case Intrinsic::amdgcn_raw_buffer_atomic_add:
6200 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6201 break;
6202 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6203 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6204 break;
6205 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6206 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6207 break;
6208 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6209 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6210 break;
6211 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6212 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6213 break;
6214 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6215 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6216 break;
6217 case Intrinsic::amdgcn_raw_buffer_atomic_and:
6218 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6219 break;
6220 case Intrinsic::amdgcn_raw_buffer_atomic_or:
6221 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6222 break;
6223 case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6224 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6225 break;
6226 default:
6227 llvm_unreachable("unhandled atomic opcode");
6228 }
6229
6230 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6231 M->getMemOperand());
6232 }
6233 case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6234 case Intrinsic::amdgcn_struct_buffer_atomic_add:
6235 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6236 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6237 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6238 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6239 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6240 case Intrinsic::amdgcn_struct_buffer_atomic_and:
6241 case Intrinsic::amdgcn_struct_buffer_atomic_or:
6242 case Intrinsic::amdgcn_struct_buffer_atomic_xor: {
6243 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6244 SDValue Ops[] = {
6245 Op.getOperand(0), // Chain
6246 Op.getOperand(2), // vdata
6247 Op.getOperand(3), // rsrc
6248 Op.getOperand(4), // vindex
6249 Offsets.first, // voffset
6250 Op.getOperand(6), // soffset
6251 Offsets.second, // offset
6252 Op.getOperand(7), // cachepolicy
6253 DAG.getConstant(1, DL, MVT::i1), // idxen
6254 };
6255 EVT VT = Op.getValueType();
6256
6257 auto *M = cast<MemSDNode>(Op);
6258 unsigned Opcode = 0;
6259
6260 switch (IntrID) {
6261 case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6262 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6263 break;
6264 case Intrinsic::amdgcn_struct_buffer_atomic_add:
6265 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6266 break;
6267 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6268 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6269 break;
6270 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6271 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6272 break;
6273 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6274 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6275 break;
6276 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6277 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6278 break;
6279 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6280 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6281 break;
6282 case Intrinsic::amdgcn_struct_buffer_atomic_and:
6283 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6284 break;
6285 case Intrinsic::amdgcn_struct_buffer_atomic_or:
6286 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6287 break;
6288 case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6289 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6290 break;
6291 default:
6292 llvm_unreachable("unhandled atomic opcode");
6293 }
6294
6295 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6296 M->getMemOperand());
6297 }
Marek Olsak5cec6412017-11-09 01:52:48 +00006298 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
Tim Renouf4f703f52018-08-21 11:07:10 +00006299 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6300 unsigned IdxEn = 1;
6301 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6302 IdxEn = Idx->getZExtValue() != 0;
Marek Olsak5cec6412017-11-09 01:52:48 +00006303 SDValue Ops[] = {
6304 Op.getOperand(0), // Chain
6305 Op.getOperand(2), // src
6306 Op.getOperand(3), // cmp
6307 Op.getOperand(4), // rsrc
6308 Op.getOperand(5), // vindex
Tim Renouf4f703f52018-08-21 11:07:10 +00006309 SDValue(), // voffset -- will be set by setBufferOffsets
6310 SDValue(), // soffset -- will be set by setBufferOffsets
6311 SDValue(), // offset -- will be set by setBufferOffsets
6312 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6313 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6314 };
6315 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6316 EVT VT = Op.getValueType();
6317 auto *M = cast<MemSDNode>(Op);
6318
6319 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6320 Op->getVTList(), Ops, VT, M->getMemOperand());
6321 }
6322 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6323 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6324 SDValue Ops[] = {
6325 Op.getOperand(0), // Chain
6326 Op.getOperand(2), // src
6327 Op.getOperand(3), // cmp
6328 Op.getOperand(4), // rsrc
6329 DAG.getConstant(0, DL, MVT::i32), // vindex
6330 Offsets.first, // voffset
6331 Op.getOperand(6), // soffset
6332 Offsets.second, // offset
6333 Op.getOperand(7), // cachepolicy
6334 DAG.getConstant(0, DL, MVT::i1), // idxen
6335 };
6336 EVT VT = Op.getValueType();
6337 auto *M = cast<MemSDNode>(Op);
6338
6339 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6340 Op->getVTList(), Ops, VT, M->getMemOperand());
6341 }
6342 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6343 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6344 SDValue Ops[] = {
6345 Op.getOperand(0), // Chain
6346 Op.getOperand(2), // src
6347 Op.getOperand(3), // cmp
6348 Op.getOperand(4), // rsrc
6349 Op.getOperand(5), // vindex
6350 Offsets.first, // voffset
6351 Op.getOperand(7), // soffset
6352 Offsets.second, // offset
6353 Op.getOperand(8), // cachepolicy
6354 DAG.getConstant(1, DL, MVT::i1), // idxen
Marek Olsak5cec6412017-11-09 01:52:48 +00006355 };
Matt Arsenaulte19bc2e2017-12-29 17:18:21 +00006356 EVT VT = Op.getValueType();
6357 auto *M = cast<MemSDNode>(Op);
Marek Olsak5cec6412017-11-09 01:52:48 +00006358
6359 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
Matt Arsenaulte19bc2e2017-12-29 17:18:21 +00006360 Op->getVTList(), Ops, VT, M->getMemOperand());
Marek Olsak5cec6412017-11-09 01:52:48 +00006361 }
6362
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +00006363 default:
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00006364 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6365 AMDGPU::getImageDimIntrinsicInfo(IntrID))
6366 return lowerImage(Op, ImageDimIntr, DAG);
Matt Arsenault1349a042018-05-22 06:32:10 +00006367
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +00006368 return SDValue();
6369 }
6370}
6371
Tim Renouf677387d2019-03-22 14:58:02 +00006372// Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6373// dwordx4 if on SI.
6374SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6375 SDVTList VTList,
6376 ArrayRef<SDValue> Ops, EVT MemVT,
6377 MachineMemOperand *MMO,
6378 SelectionDAG &DAG) const {
6379 EVT VT = VTList.VTs[0];
6380 EVT WidenedVT = VT;
6381 EVT WidenedMemVT = MemVT;
6382 if (!Subtarget->hasDwordx3LoadStores() &&
6383 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6384 WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6385 WidenedVT.getVectorElementType(), 4);
6386 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6387 WidenedMemVT.getVectorElementType(), 4);
6388 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6389 }
6390
6391 assert(VTList.NumVTs == 2);
6392 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6393
6394 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6395 WidenedMemVT, MMO);
6396 if (WidenedVT != VT) {
6397 auto Extract = DAG.getNode(
6398 ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6399 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout())));
6400 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6401 }
6402 return NewOp;
6403}
6404
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00006405SDValue SITargetLowering::handleD16VData(SDValue VData,
6406 SelectionDAG &DAG) const {
6407 EVT StoreVT = VData.getValueType();
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00006408
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00006409 // No change for f16 and legal vector D16 types.
Matt Arsenault1349a042018-05-22 06:32:10 +00006410 if (!StoreVT.isVector())
6411 return VData;
6412
6413 SDLoc DL(VData);
6414 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6415
6416 if (Subtarget->hasUnpackedD16VMem()) {
6417 // We need to unpack the packed data to store.
6418 EVT IntStoreVT = StoreVT.changeTypeToInteger();
6419 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6420
6421 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6422 StoreVT.getVectorNumElements());
6423 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6424 return DAG.UnrollVectorOp(ZExt.getNode());
6425 }
6426
Matt Arsenault02dc7e12018-06-15 15:15:46 +00006427 assert(isTypeLegal(StoreVT));
6428 return VData;
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00006429}
6430
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00006431SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6432 SelectionDAG &DAG) const {
Tom Stellardfc92e772015-05-12 14:18:14 +00006433 SDLoc DL(Op);
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00006434 SDValue Chain = Op.getOperand(0);
6435 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
David Stuttard70e8bc12017-06-22 16:29:22 +00006436 MachineFunction &MF = DAG.getMachineFunction();
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00006437
6438 switch (IntrinsicID) {
Matt Arsenault7d6b71d2017-02-21 22:50:41 +00006439 case Intrinsic::amdgcn_exp: {
Matt Arsenault4165efd2017-01-17 07:26:53 +00006440 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6441 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6442 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
6443 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
6444
6445 const SDValue Ops[] = {
6446 Chain,
6447 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6448 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
6449 Op.getOperand(4), // src0
6450 Op.getOperand(5), // src1
6451 Op.getOperand(6), // src2
6452 Op.getOperand(7), // src3
6453 DAG.getTargetConstant(0, DL, MVT::i1), // compr
6454 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6455 };
6456
6457 unsigned Opc = Done->isNullValue() ?
6458 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6459 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6460 }
6461 case Intrinsic::amdgcn_exp_compr: {
6462 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6463 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6464 SDValue Src0 = Op.getOperand(4);
6465 SDValue Src1 = Op.getOperand(5);
6466 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6467 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
6468
6469 SDValue Undef = DAG.getUNDEF(MVT::f32);
6470 const SDValue Ops[] = {
6471 Chain,
6472 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6473 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
6474 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
6475 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
6476 Undef, // src2
6477 Undef, // src3
6478 DAG.getTargetConstant(1, DL, MVT::i1), // compr
6479 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6480 };
6481
6482 unsigned Opc = Done->isNullValue() ?
6483 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6484 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6485 }
6486 case Intrinsic::amdgcn_s_sendmsg:
Matt Arsenaultd3e5cb72017-02-16 02:01:17 +00006487 case Intrinsic::amdgcn_s_sendmsghalt: {
6488 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
6489 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
Tom Stellardfc92e772015-05-12 14:18:14 +00006490 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
6491 SDValue Glue = Chain.getValue(1);
Matt Arsenaulta78ca622017-02-15 22:17:09 +00006492 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
Jan Veselyd48445d2017-01-04 18:06:55 +00006493 Op.getOperand(2), Glue);
6494 }
Marek Olsak2d825902017-04-28 20:21:58 +00006495 case Intrinsic::amdgcn_init_exec: {
6496 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
6497 Op.getOperand(2));
6498 }
6499 case Intrinsic::amdgcn_init_exec_from_input: {
6500 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
6501 Op.getOperand(2), Op.getOperand(3));
6502 }
Stanislav Mekhanoshinea57c382017-04-06 16:48:30 +00006503 case Intrinsic::amdgcn_s_barrier: {
6504 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
Tom Stellard5bfbae52018-07-11 20:59:01 +00006505 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
Matthias Braunf1caa282017-12-15 22:22:58 +00006506 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
Stanislav Mekhanoshinea57c382017-04-06 16:48:30 +00006507 if (WGSize <= ST.getWavefrontSize())
6508 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6509 Op.getOperand(0)), 0);
6510 }
6511 return SDValue();
6512 };
David Stuttard70e8bc12017-06-22 16:29:22 +00006513 case Intrinsic::amdgcn_tbuffer_store: {
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00006514 SDValue VData = Op.getOperand(2);
6515 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6516 if (IsD16)
6517 VData = handleD16VData(VData, DAG);
Tim Renouf35484c92018-08-21 11:06:05 +00006518 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6519 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6520 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6521 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6522 unsigned IdxEn = 1;
6523 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6524 IdxEn = Idx->getZExtValue() != 0;
David Stuttard70e8bc12017-06-22 16:29:22 +00006525 SDValue Ops[] = {
6526 Chain,
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00006527 VData, // vdata
David Stuttard70e8bc12017-06-22 16:29:22 +00006528 Op.getOperand(3), // rsrc
6529 Op.getOperand(4), // vindex
6530 Op.getOperand(5), // voffset
6531 Op.getOperand(6), // soffset
6532 Op.getOperand(7), // offset
Tim Renouf35484c92018-08-21 11:06:05 +00006533 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6534 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6535 DAG.getConstant(IdxEn, DL, MVT::i1), // idexen
6536 };
6537 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6538 AMDGPUISD::TBUFFER_STORE_FORMAT;
6539 MemSDNode *M = cast<MemSDNode>(Op);
6540 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6541 M->getMemoryVT(), M->getMemOperand());
6542 }
6543
6544 case Intrinsic::amdgcn_struct_tbuffer_store: {
6545 SDValue VData = Op.getOperand(2);
6546 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6547 if (IsD16)
6548 VData = handleD16VData(VData, DAG);
6549 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6550 SDValue Ops[] = {
6551 Chain,
6552 VData, // vdata
6553 Op.getOperand(3), // rsrc
6554 Op.getOperand(4), // vindex
6555 Offsets.first, // voffset
6556 Op.getOperand(6), // soffset
6557 Offsets.second, // offset
6558 Op.getOperand(7), // format
6559 Op.getOperand(8), // cachepolicy
6560 DAG.getConstant(1, DL, MVT::i1), // idexen
6561 };
6562 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6563 AMDGPUISD::TBUFFER_STORE_FORMAT;
6564 MemSDNode *M = cast<MemSDNode>(Op);
6565 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6566 M->getMemoryVT(), M->getMemOperand());
6567 }
6568
6569 case Intrinsic::amdgcn_raw_tbuffer_store: {
6570 SDValue VData = Op.getOperand(2);
6571 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6572 if (IsD16)
6573 VData = handleD16VData(VData, DAG);
6574 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6575 SDValue Ops[] = {
6576 Chain,
6577 VData, // vdata
6578 Op.getOperand(3), // rsrc
6579 DAG.getConstant(0, DL, MVT::i32), // vindex
6580 Offsets.first, // voffset
6581 Op.getOperand(5), // soffset
6582 Offsets.second, // offset
6583 Op.getOperand(6), // format
6584 Op.getOperand(7), // cachepolicy
6585 DAG.getConstant(0, DL, MVT::i1), // idexen
David Stuttard70e8bc12017-06-22 16:29:22 +00006586 };
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00006587 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6588 AMDGPUISD::TBUFFER_STORE_FORMAT;
6589 MemSDNode *M = cast<MemSDNode>(Op);
6590 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6591 M->getMemoryVT(), M->getMemOperand());
David Stuttard70e8bc12017-06-22 16:29:22 +00006592 }
6593
Marek Olsak5cec6412017-11-09 01:52:48 +00006594 case Intrinsic::amdgcn_buffer_store:
6595 case Intrinsic::amdgcn_buffer_store_format: {
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00006596 SDValue VData = Op.getOperand(2);
6597 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6598 if (IsD16)
6599 VData = handleD16VData(VData, DAG);
Tim Renouf4f703f52018-08-21 11:07:10 +00006600 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6601 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6602 unsigned IdxEn = 1;
6603 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6604 IdxEn = Idx->getZExtValue() != 0;
Marek Olsak5cec6412017-11-09 01:52:48 +00006605 SDValue Ops[] = {
6606 Chain,
Tim Renouf4f703f52018-08-21 11:07:10 +00006607 VData,
Marek Olsak5cec6412017-11-09 01:52:48 +00006608 Op.getOperand(3), // rsrc
6609 Op.getOperand(4), // vindex
Tim Renouf4f703f52018-08-21 11:07:10 +00006610 SDValue(), // voffset -- will be set by setBufferOffsets
6611 SDValue(), // soffset -- will be set by setBufferOffsets
6612 SDValue(), // offset -- will be set by setBufferOffsets
6613 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6614 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
Marek Olsak5cec6412017-11-09 01:52:48 +00006615 };
Tim Renouf4f703f52018-08-21 11:07:10 +00006616 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00006617 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6618 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6619 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6620 MemSDNode *M = cast<MemSDNode>(Op);
Ryan Taylor00e063a2019-03-19 16:07:00 +00006621
6622 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6623 EVT VDataType = VData.getValueType().getScalarType();
6624 if (VDataType == MVT::i8 || VDataType == MVT::i16)
6625 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6626
Changpeng Fang44dfa1d2018-01-12 21:12:19 +00006627 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6628 M->getMemoryVT(), M->getMemOperand());
Marek Olsak5cec6412017-11-09 01:52:48 +00006629 }
Tim Renouf4f703f52018-08-21 11:07:10 +00006630
6631 case Intrinsic::amdgcn_raw_buffer_store:
6632 case Intrinsic::amdgcn_raw_buffer_store_format: {
6633 SDValue VData = Op.getOperand(2);
6634 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6635 if (IsD16)
6636 VData = handleD16VData(VData, DAG);
6637 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6638 SDValue Ops[] = {
6639 Chain,
6640 VData,
6641 Op.getOperand(3), // rsrc
6642 DAG.getConstant(0, DL, MVT::i32), // vindex
6643 Offsets.first, // voffset
6644 Op.getOperand(5), // soffset
6645 Offsets.second, // offset
6646 Op.getOperand(6), // cachepolicy
6647 DAG.getConstant(0, DL, MVT::i1), // idxen
6648 };
6649 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_raw_buffer_store ?
6650 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6651 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6652 MemSDNode *M = cast<MemSDNode>(Op);
Ryan Taylor00e063a2019-03-19 16:07:00 +00006653
6654 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6655 EVT VDataType = VData.getValueType().getScalarType();
6656 if (VDataType == MVT::i8 || VDataType == MVT::i16)
6657 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6658
Tim Renouf4f703f52018-08-21 11:07:10 +00006659 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6660 M->getMemoryVT(), M->getMemOperand());
6661 }
6662
6663 case Intrinsic::amdgcn_struct_buffer_store:
6664 case Intrinsic::amdgcn_struct_buffer_store_format: {
6665 SDValue VData = Op.getOperand(2);
6666 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6667 if (IsD16)
6668 VData = handleD16VData(VData, DAG);
6669 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6670 SDValue Ops[] = {
6671 Chain,
6672 VData,
6673 Op.getOperand(3), // rsrc
6674 Op.getOperand(4), // vindex
6675 Offsets.first, // voffset
6676 Op.getOperand(6), // soffset
6677 Offsets.second, // offset
6678 Op.getOperand(7), // cachepolicy
6679 DAG.getConstant(1, DL, MVT::i1), // idxen
6680 };
6681 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
6682 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6683 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6684 MemSDNode *M = cast<MemSDNode>(Op);
Ryan Taylor00e063a2019-03-19 16:07:00 +00006685
6686 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6687 EVT VDataType = VData.getValueType().getScalarType();
6688 if (VDataType == MVT::i8 || VDataType == MVT::i16)
6689 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6690
Tim Renouf4f703f52018-08-21 11:07:10 +00006691 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6692 M->getMemoryVT(), M->getMemOperand());
6693 }
6694
Stanislav Mekhanoshin68a2fef2019-06-13 23:47:36 +00006695 case Intrinsic::amdgcn_end_cf:
6696 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
6697 Op->getOperand(2), Chain), 0);
6698
Nicolai Haehnle2f5a7382018-04-04 10:58:54 +00006699 default: {
Nicolai Haehnle7a9c03f2018-06-21 13:36:57 +00006700 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6701 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6702 return lowerImage(Op, ImageDimIntr, DAG);
Nicolai Haehnle2f5a7382018-04-04 10:58:54 +00006703
Matt Arsenault754dd3e2017-04-03 18:08:08 +00006704 return Op;
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00006705 }
Nicolai Haehnle2f5a7382018-04-04 10:58:54 +00006706 }
Matt Arsenaulta5789bb2014-07-26 06:23:37 +00006707}
6708
Tim Renouf4f703f52018-08-21 11:07:10 +00006709// The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
6710// offset (the offset that is included in bounds checking and swizzling, to be
6711// split between the instruction's voffset and immoffset fields) and soffset
6712// (the offset that is excluded from bounds checking and swizzling, to go in
6713// the instruction's soffset field). This function takes the first kind of
6714// offset and figures out how to split it between voffset and immoffset.
Tim Renouf35484c92018-08-21 11:06:05 +00006715std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
6716 SDValue Offset, SelectionDAG &DAG) const {
6717 SDLoc DL(Offset);
6718 const unsigned MaxImm = 4095;
6719 SDValue N0 = Offset;
6720 ConstantSDNode *C1 = nullptr;
Piotr Sobczak378131b2019-01-02 09:47:41 +00006721
6722 if ((C1 = dyn_cast<ConstantSDNode>(N0)))
Tim Renouf35484c92018-08-21 11:06:05 +00006723 N0 = SDValue();
Piotr Sobczak378131b2019-01-02 09:47:41 +00006724 else if (DAG.isBaseWithConstantOffset(N0)) {
6725 C1 = cast<ConstantSDNode>(N0.getOperand(1));
6726 N0 = N0.getOperand(0);
6727 }
Tim Renouf35484c92018-08-21 11:06:05 +00006728
6729 if (C1) {
6730 unsigned ImmOffset = C1->getZExtValue();
6731 // If the immediate value is too big for the immoffset field, put the value
Tim Renoufa37679d2018-10-03 10:29:43 +00006732 // and -4096 into the immoffset field so that the value that is copied/added
Tim Renouf35484c92018-08-21 11:06:05 +00006733 // for the voffset field is a multiple of 4096, and it stands more chance
6734 // of being CSEd with the copy/add for another similar load/store.
Tim Renoufa37679d2018-10-03 10:29:43 +00006735 // However, do not do that rounding down to a multiple of 4096 if that is a
6736 // negative number, as it appears to be illegal to have a negative offset
6737 // in the vgpr, even if adding the immediate offset makes it positive.
Tim Renouf35484c92018-08-21 11:06:05 +00006738 unsigned Overflow = ImmOffset & ~MaxImm;
6739 ImmOffset -= Overflow;
Tim Renoufa37679d2018-10-03 10:29:43 +00006740 if ((int32_t)Overflow < 0) {
6741 Overflow += ImmOffset;
6742 ImmOffset = 0;
6743 }
Tim Renouf35484c92018-08-21 11:06:05 +00006744 C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32));
6745 if (Overflow) {
6746 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
6747 if (!N0)
6748 N0 = OverflowVal;
6749 else {
6750 SDValue Ops[] = { N0, OverflowVal };
6751 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
6752 }
6753 }
6754 }
6755 if (!N0)
6756 N0 = DAG.getConstant(0, DL, MVT::i32);
6757 if (!C1)
6758 C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32));
6759 return {N0, SDValue(C1, 0)};
6760}
6761
Tim Renouf4f703f52018-08-21 11:07:10 +00006762// Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
6763// three offsets (voffset, soffset and instoffset) into the SDValue[3] array
6764// pointed to by Offsets.
6765void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
Nicolai Haehnlea7b00052018-11-30 22:55:38 +00006766 SelectionDAG &DAG, SDValue *Offsets,
6767 unsigned Align) const {
Tim Renouf4f703f52018-08-21 11:07:10 +00006768 SDLoc DL(CombinedOffset);
6769 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
6770 uint32_t Imm = C->getZExtValue();
6771 uint32_t SOffset, ImmOffset;
Nicolai Haehnlea7b00052018-11-30 22:55:38 +00006772 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
Tim Renouf4f703f52018-08-21 11:07:10 +00006773 Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
6774 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
6775 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
6776 return;
6777 }
6778 }
6779 if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
6780 SDValue N0 = CombinedOffset.getOperand(0);
6781 SDValue N1 = CombinedOffset.getOperand(1);
6782 uint32_t SOffset, ImmOffset;
6783 int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
Nicolai Haehnlea7b00052018-11-30 22:55:38 +00006784 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
6785 Subtarget, Align)) {
Tim Renouf4f703f52018-08-21 11:07:10 +00006786 Offsets[0] = N0;
6787 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
6788 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
6789 return;
6790 }
6791 }
6792 Offsets[0] = CombinedOffset;
6793 Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
6794 Offsets[2] = DAG.getConstant(0, DL, MVT::i32);
6795}
6796
Ryan Taylor00e063a2019-03-19 16:07:00 +00006797// Handle 8 bit and 16 bit buffer loads
6798SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
6799 EVT LoadVT, SDLoc DL,
6800 ArrayRef<SDValue> Ops,
6801 MemSDNode *M) const {
6802 EVT IntVT = LoadVT.changeTypeToInteger();
6803 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
6804 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
6805
6806 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
6807 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
6808 Ops, IntVT,
6809 M->getMemOperand());
6810 SDValue BufferLoadTrunc = DAG.getNode(ISD::TRUNCATE, DL,
6811 LoadVT.getScalarType(), BufferLoad);
6812 return DAG.getMergeValues({BufferLoadTrunc, BufferLoad.getValue(1)}, DL);
6813}
6814
6815// Handle 8 bit and 16 bit buffer stores
6816SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
6817 EVT VDataType, SDLoc DL,
6818 SDValue Ops[],
6819 MemSDNode *M) const {
6820 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
6821 Ops[1] = BufferStoreExt;
6822 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
6823 AMDGPUISD::BUFFER_STORE_SHORT;
6824 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
6825 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
6826 M->getMemOperand());
6827}
6828
Matt Arsenault90083d32018-06-07 09:54:49 +00006829static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
6830 ISD::LoadExtType ExtType, SDValue Op,
6831 const SDLoc &SL, EVT VT) {
6832 if (VT.bitsLT(Op.getValueType()))
6833 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
6834
6835 switch (ExtType) {
6836 case ISD::SEXTLOAD:
6837 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
6838 case ISD::ZEXTLOAD:
6839 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
6840 case ISD::EXTLOAD:
6841 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
6842 case ISD::NON_EXTLOAD:
6843 return Op;
6844 }
6845
6846 llvm_unreachable("invalid ext type");
6847}
6848
6849SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
6850 SelectionDAG &DAG = DCI.DAG;
6851 if (Ld->getAlignment() < 4 || Ld->isDivergent())
6852 return SDValue();
6853
6854 // FIXME: Constant loads should all be marked invariant.
6855 unsigned AS = Ld->getAddressSpace();
Matt Arsenault0da63502018-08-31 05:49:54 +00006856 if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
6857 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
Matt Arsenault90083d32018-06-07 09:54:49 +00006858 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
6859 return SDValue();
6860
6861 // Don't do this early, since it may interfere with adjacent load merging for
6862 // illegal types. We can avoid losing alignment information for exotic types
6863 // pre-legalize.
6864 EVT MemVT = Ld->getMemoryVT();
6865 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
6866 MemVT.getSizeInBits() >= 32)
6867 return SDValue();
6868
6869 SDLoc SL(Ld);
6870
6871 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
6872 "unexpected vector extload");
6873
6874 // TODO: Drop only high part of range.
6875 SDValue Ptr = Ld->getBasePtr();
6876 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
6877 MVT::i32, SL, Ld->getChain(), Ptr,
6878 Ld->getOffset(),
6879 Ld->getPointerInfo(), MVT::i32,
6880 Ld->getAlignment(),
6881 Ld->getMemOperand()->getFlags(),
6882 Ld->getAAInfo(),
6883 nullptr); // Drop ranges
6884
6885 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
6886 if (MemVT.isFloatingPoint()) {
6887 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
6888 "unexpected fp extload");
6889 TruncVT = MemVT.changeTypeToInteger();
6890 }
6891
6892 SDValue Cvt = NewLoad;
6893 if (Ld->getExtensionType() == ISD::SEXTLOAD) {
6894 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
6895 DAG.getValueType(TruncVT));
6896 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
6897 Ld->getExtensionType() == ISD::NON_EXTLOAD) {
6898 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
6899 } else {
6900 assert(Ld->getExtensionType() == ISD::EXTLOAD);
6901 }
6902
6903 EVT VT = Ld->getValueType(0);
6904 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
6905
6906 DCI.AddToWorklist(Cvt.getNode());
6907
6908 // We may need to handle exotic cases, such as i16->i64 extloads, so insert
6909 // the appropriate extension from the 32-bit load.
6910 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
6911 DCI.AddToWorklist(Cvt.getNode());
6912
6913 // Handle conversion back to floating point if necessary.
6914 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
6915
6916 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
6917}
6918
Tom Stellard81d871d2013-11-13 23:36:50 +00006919SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6920 SDLoc DL(Op);
6921 LoadSDNode *Load = cast<LoadSDNode>(Op);
Matt Arsenault6dfda962016-02-10 18:21:39 +00006922 ISD::LoadExtType ExtType = Load->getExtensionType();
Matt Arsenaulta1436412016-02-10 18:21:45 +00006923 EVT MemVT = Load->getMemoryVT();
Matt Arsenault6dfda962016-02-10 18:21:39 +00006924
Matt Arsenaulta1436412016-02-10 18:21:45 +00006925 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
Matt Arsenault65ca292a2017-09-07 05:37:34 +00006926 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
6927 return SDValue();
6928
Matt Arsenault6dfda962016-02-10 18:21:39 +00006929 // FIXME: Copied from PPC
6930 // First, load into 32 bits, then truncate to 1 bit.
6931
6932 SDValue Chain = Load->getChain();
6933 SDValue BasePtr = Load->getBasePtr();
6934 MachineMemOperand *MMO = Load->getMemOperand();
6935
Tom Stellard115a6152016-11-10 16:02:37 +00006936 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
6937
Matt Arsenault6dfda962016-02-10 18:21:39 +00006938 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
Tom Stellard115a6152016-11-10 16:02:37 +00006939 BasePtr, RealMemVT, MMO);
Matt Arsenault6dfda962016-02-10 18:21:39 +00006940
Tim Renouf361b5b22019-03-21 12:01:21 +00006941 if (!MemVT.isVector()) {
6942 SDValue Ops[] = {
6943 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
6944 NewLD.getValue(1)
6945 };
6946
6947 return DAG.getMergeValues(Ops, DL);
6948 }
6949
6950 SmallVector<SDValue, 3> Elts;
6951 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
6952 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
6953 DAG.getConstant(I, DL, MVT::i32));
6954
6955 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
6956 }
6957
Matt Arsenault6dfda962016-02-10 18:21:39 +00006958 SDValue Ops[] = {
Tim Renouf361b5b22019-03-21 12:01:21 +00006959 DAG.getBuildVector(MemVT, DL, Elts),
Matt Arsenault6dfda962016-02-10 18:21:39 +00006960 NewLD.getValue(1)
6961 };
6962
6963 return DAG.getMergeValues(Ops, DL);
6964 }
Tom Stellard81d871d2013-11-13 23:36:50 +00006965
Matt Arsenaulta1436412016-02-10 18:21:45 +00006966 if (!MemVT.isVector())
6967 return SDValue();
Matt Arsenault4d801cd2015-11-24 12:05:03 +00006968
Matt Arsenaulta1436412016-02-10 18:21:45 +00006969 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
6970 "Custom lowering for non-i32 vectors hasn't been implemented.");
Matt Arsenault4d801cd2015-11-24 12:05:03 +00006971
Matt Arsenaultbcdfee72016-05-02 20:13:51 +00006972 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
Simon Pilgrim266f4392019-06-11 11:00:23 +00006973 *Load->getMemOperand())) {
Matt Arsenaultbcdfee72016-05-02 20:13:51 +00006974 SDValue Ops[2];
6975 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
6976 return DAG.getMergeValues(Ops, DL);
6977 }
Simon Pilgrim266f4392019-06-11 11:00:23 +00006978
6979 unsigned Alignment = Load->getAlignment();
6980 unsigned AS = Load->getAddressSpace();
Stanislav Mekhanoshina224f682019-05-01 16:11:11 +00006981 if (Subtarget->hasLDSMisalignedBug() &&
6982 AS == AMDGPUAS::FLAT_ADDRESS &&
6983 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
6984 return SplitVectorLoad(Op, DAG);
6985 }
Matt Arsenaultbcdfee72016-05-02 20:13:51 +00006986
Tom Stellardf8e6eaf2016-10-26 14:38:47 +00006987 MachineFunction &MF = DAG.getMachineFunction();
6988 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
6989 // If there is a possibilty that flat instruction access scratch memory
6990 // then we need to use the same legalization rules we use for private.
Matt Arsenault0da63502018-08-31 05:49:54 +00006991 if (AS == AMDGPUAS::FLAT_ADDRESS)
Tom Stellardf8e6eaf2016-10-26 14:38:47 +00006992 AS = MFI->hasFlatScratchInit() ?
Matt Arsenault0da63502018-08-31 05:49:54 +00006993 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
Tom Stellardf8e6eaf2016-10-26 14:38:47 +00006994
Matt Arsenaultbcdfee72016-05-02 20:13:51 +00006995 unsigned NumElements = MemVT.getVectorNumElements();
Matt Arsenault6c041a32018-03-29 19:59:28 +00006996
Matt Arsenault0da63502018-08-31 05:49:54 +00006997 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
6998 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
Tim Renouf361b5b22019-03-21 12:01:21 +00006999 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7000 if (MemVT.isPow2VectorType())
7001 return SDValue();
7002 if (NumElements == 3)
7003 return WidenVectorLoad(Op, DAG);
7004 return SplitVectorLoad(Op, DAG);
7005 }
Matt Arsenaulta1436412016-02-10 18:21:45 +00007006 // Non-uniform loads will be selected to MUBUF instructions, so they
Alexander Timofeev18009562016-12-08 17:28:47 +00007007 // have the same legalization requirements as global and private
Matt Arsenaulta1436412016-02-10 18:21:45 +00007008 // loads.
7009 //
Yaxun Liu1a14bfa2017-03-27 14:04:01 +00007010 }
Matt Arsenault6c041a32018-03-29 19:59:28 +00007011
Matt Arsenault0da63502018-08-31 05:49:54 +00007012 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7013 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7014 AS == AMDGPUAS::GLOBAL_ADDRESS) {
Alexander Timofeev2e5eece2018-03-05 15:12:21 +00007015 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
Farhana Aleen89196642018-03-07 17:09:18 +00007016 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
Tim Renouf361b5b22019-03-21 12:01:21 +00007017 Alignment >= 4 && NumElements < 32) {
7018 if (MemVT.isPow2VectorType())
7019 return SDValue();
7020 if (NumElements == 3)
7021 return WidenVectorLoad(Op, DAG);
7022 return SplitVectorLoad(Op, DAG);
7023 }
Alexander Timofeev18009562016-12-08 17:28:47 +00007024 // Non-uniform loads will be selected to MUBUF instructions, so they
7025 // have the same legalization requirements as global and private
7026 // loads.
7027 //
Yaxun Liu1a14bfa2017-03-27 14:04:01 +00007028 }
Matt Arsenault0da63502018-08-31 05:49:54 +00007029 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7030 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7031 AS == AMDGPUAS::GLOBAL_ADDRESS ||
7032 AS == AMDGPUAS::FLAT_ADDRESS) {
Matt Arsenaultf2ddbf02016-02-13 04:18:53 +00007033 if (NumElements > 4)
Matt Arsenaulta1436412016-02-10 18:21:45 +00007034 return SplitVectorLoad(Op, DAG);
Tim Renouf361b5b22019-03-21 12:01:21 +00007035 // v3 loads not supported on SI.
7036 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7037 return WidenVectorLoad(Op, DAG);
7038 // v3 and v4 loads are supported for private and global memory.
Matt Arsenaulta1436412016-02-10 18:21:45 +00007039 return SDValue();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +00007040 }
Matt Arsenault0da63502018-08-31 05:49:54 +00007041 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
Matt Arsenaultf2ddbf02016-02-13 04:18:53 +00007042 // Depending on the setting of the private_element_size field in the
7043 // resource descriptor, we can only make private accesses up to a certain
7044 // size.
7045 switch (Subtarget->getMaxPrivateElementSize()) {
7046 case 4:
Matt Arsenault9c499c32016-04-14 23:31:26 +00007047 return scalarizeVectorLoad(Load, DAG);
Matt Arsenaultf2ddbf02016-02-13 04:18:53 +00007048 case 8:
7049 if (NumElements > 2)
7050 return SplitVectorLoad(Op, DAG);
7051 return SDValue();
7052 case 16:
7053 // Same as global/flat
7054 if (NumElements > 4)
7055 return SplitVectorLoad(Op, DAG);
Tim Renouf361b5b22019-03-21 12:01:21 +00007056 // v3 loads not supported on SI.
7057 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7058 return WidenVectorLoad(Op, DAG);
Matt Arsenaultf2ddbf02016-02-13 04:18:53 +00007059 return SDValue();
7060 default:
7061 llvm_unreachable("unsupported private_element_size");
7062 }
Matt Arsenault0da63502018-08-31 05:49:54 +00007063 } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
Farhana Aleena7cb3112018-03-09 17:41:39 +00007064 // Use ds_read_b128 if possible.
Marek Olsaka9a58fa2018-04-10 22:48:23 +00007065 if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
Farhana Aleena7cb3112018-03-09 17:41:39 +00007066 MemVT.getStoreSize() == 16)
Matt Arsenaultbcdfee72016-05-02 20:13:51 +00007067 return SDValue();
7068
Farhana Aleena7cb3112018-03-09 17:41:39 +00007069 if (NumElements > 2)
7070 return SplitVectorLoad(Op, DAG);
Nicolai Haehnle48219372018-10-17 15:37:48 +00007071
7072 // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7073 // address is negative, then the instruction is incorrectly treated as
7074 // out-of-bounds even if base + offsets is in bounds. Split vectorized
7075 // loads here to avoid emitting ds_read2_b32. We may re-combine the
7076 // load later in the SILoadStoreOptimizer.
7077 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7078 NumElements == 2 && MemVT.getStoreSize() == 8 &&
7079 Load->getAlignment() < 8) {
7080 return SplitVectorLoad(Op, DAG);
7081 }
Tom Stellarde9373602014-01-22 19:24:14 +00007082 }
Yaxun Liu1a14bfa2017-03-27 14:04:01 +00007083 return SDValue();
Tom Stellard81d871d2013-11-13 23:36:50 +00007084}
7085
Tom Stellard0ec134f2014-02-04 17:18:40 +00007086SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
Matt Arsenault02dc7e12018-06-15 15:15:46 +00007087 EVT VT = Op.getValueType();
7088 assert(VT.getSizeInBits() == 64);
Tom Stellard0ec134f2014-02-04 17:18:40 +00007089
7090 SDLoc DL(Op);
7091 SDValue Cond = Op.getOperand(0);
Tom Stellard0ec134f2014-02-04 17:18:40 +00007092
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007093 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7094 SDValue One = DAG.getConstant(1, DL, MVT::i32);
Tom Stellard0ec134f2014-02-04 17:18:40 +00007095
Tom Stellard7ea3d6d2014-03-31 14:01:55 +00007096 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7097 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7098
7099 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7100 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
Tom Stellard0ec134f2014-02-04 17:18:40 +00007101
7102 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7103
Tom Stellard7ea3d6d2014-03-31 14:01:55 +00007104 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7105 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
Tom Stellard0ec134f2014-02-04 17:18:40 +00007106
7107 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7108
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007109 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
Matt Arsenault02dc7e12018-06-15 15:15:46 +00007110 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
Tom Stellard0ec134f2014-02-04 17:18:40 +00007111}
7112
Matt Arsenault22ca3f82014-07-15 23:50:10 +00007113// Catch division cases where we can use shortcuts with rcp and rsq
7114// instructions.
Matt Arsenaulta1fe17c2016-07-19 23:16:53 +00007115SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7116 SelectionDAG &DAG) const {
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00007117 SDLoc SL(Op);
7118 SDValue LHS = Op.getOperand(0);
7119 SDValue RHS = Op.getOperand(1);
7120 EVT VT = Op.getValueType();
Stanislav Mekhanoshin9d7b1c92017-07-06 20:34:21 +00007121 const SDNodeFlags Flags = Op->getFlags();
Michael Berg7acc81b2018-05-04 18:48:20 +00007122 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00007123
Konstantin Zhuravlyovc4b18e72017-04-21 19:25:33 +00007124 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
7125 return SDValue();
7126
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00007127 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
Konstantin Zhuravlyovc4b18e72017-04-21 19:25:33 +00007128 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
Matt Arsenault979902b2016-08-02 22:25:04 +00007129 if (CLHS->isExactlyValue(1.0)) {
7130 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7131 // the CI documentation has a worst case error of 1 ulp.
7132 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7133 // use it as long as we aren't trying to use denormals.
Matt Arsenaultcdff21b2016-12-22 03:05:44 +00007134 //
7135 // v_rcp_f16 and v_rsq_f16 DO support denormals.
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00007136
Matt Arsenault979902b2016-08-02 22:25:04 +00007137 // 1.0 / sqrt(x) -> rsq(x)
Matt Arsenaultcdff21b2016-12-22 03:05:44 +00007138
Matt Arsenault979902b2016-08-02 22:25:04 +00007139 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7140 // error seems really high at 2^29 ULP.
7141 if (RHS.getOpcode() == ISD::FSQRT)
7142 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7143
7144 // 1.0 / x -> rcp(x)
7145 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7146 }
7147
7148 // Same as for 1.0, but expand the sign out of the constant.
7149 if (CLHS->isExactlyValue(-1.0)) {
7150 // -1.0 / x -> rcp (fneg x)
7151 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7152 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7153 }
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00007154 }
7155 }
7156
Stanislav Mekhanoshin9d7b1c92017-07-06 20:34:21 +00007157 if (Unsafe) {
Matt Arsenault22ca3f82014-07-15 23:50:10 +00007158 // Turn into multiply by the reciprocal.
7159 // x / y -> x * (1.0 / y)
7160 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
Stanislav Mekhanoshin9d7b1c92017-07-06 20:34:21 +00007161 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
Matt Arsenault22ca3f82014-07-15 23:50:10 +00007162 }
7163
7164 return SDValue();
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00007165}
7166
Tom Stellard8485fa02016-12-07 02:42:15 +00007167static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7168 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7169 if (GlueChain->getNumValues() <= 1) {
7170 return DAG.getNode(Opcode, SL, VT, A, B);
7171 }
7172
7173 assert(GlueChain->getNumValues() == 3);
7174
7175 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7176 switch (Opcode) {
7177 default: llvm_unreachable("no chain equivalent for opcode");
7178 case ISD::FMUL:
7179 Opcode = AMDGPUISD::FMUL_W_CHAIN;
7180 break;
7181 }
7182
7183 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7184 GlueChain.getValue(2));
7185}
7186
7187static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7188 EVT VT, SDValue A, SDValue B, SDValue C,
7189 SDValue GlueChain) {
7190 if (GlueChain->getNumValues() <= 1) {
7191 return DAG.getNode(Opcode, SL, VT, A, B, C);
7192 }
7193
7194 assert(GlueChain->getNumValues() == 3);
7195
7196 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7197 switch (Opcode) {
7198 default: llvm_unreachable("no chain equivalent for opcode");
7199 case ISD::FMA:
7200 Opcode = AMDGPUISD::FMA_W_CHAIN;
7201 break;
7202 }
7203
7204 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7205 GlueChain.getValue(2));
7206}
7207
Matt Arsenault4052a572016-12-22 03:05:41 +00007208SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
Matt Arsenaultcdff21b2016-12-22 03:05:44 +00007209 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7210 return FastLowered;
7211
Matt Arsenault4052a572016-12-22 03:05:41 +00007212 SDLoc SL(Op);
7213 SDValue Src0 = Op.getOperand(0);
7214 SDValue Src1 = Op.getOperand(1);
7215
7216 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7217 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7218
7219 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7220 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7221
7222 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7223 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7224
7225 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7226}
7227
Matt Arsenaulta1fe17c2016-07-19 23:16:53 +00007228// Faster 2.5 ULP division that does not support denormals.
7229SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7230 SDLoc SL(Op);
7231 SDValue LHS = Op.getOperand(1);
7232 SDValue RHS = Op.getOperand(2);
7233
7234 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7235
7236 const APFloat K0Val(BitsToFloat(0x6f800000));
7237 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7238
7239 const APFloat K1Val(BitsToFloat(0x2f800000));
7240 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7241
7242 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7243
7244 EVT SetCCVT =
7245 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7246
7247 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7248
7249 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7250
7251 // TODO: Should this propagate fast-math-flags?
7252 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7253
7254 // rcp does not support denormals.
7255 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7256
7257 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7258
7259 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7260}
7261
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00007262SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
Matt Arsenaulta1fe17c2016-07-19 23:16:53 +00007263 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
Eric Christopher538d09d02016-06-07 20:27:12 +00007264 return FastLowered;
Matt Arsenault22ca3f82014-07-15 23:50:10 +00007265
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00007266 SDLoc SL(Op);
7267 SDValue LHS = Op.getOperand(0);
7268 SDValue RHS = Op.getOperand(1);
7269
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007270 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
Matt Arsenault37fefd62016-06-10 02:18:02 +00007271
Wei Dinged0f97f2016-06-09 19:17:15 +00007272 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
Matt Arsenault37fefd62016-06-10 02:18:02 +00007273
Tom Stellard8485fa02016-12-07 02:42:15 +00007274 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7275 RHS, RHS, LHS);
7276 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7277 LHS, RHS, LHS);
Matt Arsenault37fefd62016-06-10 02:18:02 +00007278
Matt Arsenaultdfec5ce2016-07-09 07:48:11 +00007279 // Denominator is scaled to not be denormal, so using rcp is ok.
Tom Stellard8485fa02016-12-07 02:42:15 +00007280 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7281 DenominatorScaled);
7282 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7283 DenominatorScaled);
Matt Arsenault37fefd62016-06-10 02:18:02 +00007284
Tom Stellard8485fa02016-12-07 02:42:15 +00007285 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7286 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7287 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
Matt Arsenault37fefd62016-06-10 02:18:02 +00007288
Tom Stellard8485fa02016-12-07 02:42:15 +00007289 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
Matt Arsenault37fefd62016-06-10 02:18:02 +00007290
Tom Stellard8485fa02016-12-07 02:42:15 +00007291 if (!Subtarget->hasFP32Denormals()) {
7292 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7293 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7294 SL, MVT::i32);
7295 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7296 DAG.getEntryNode(),
7297 EnableDenormValue, BitField);
7298 SDValue Ops[3] = {
7299 NegDivScale0,
7300 EnableDenorm.getValue(0),
7301 EnableDenorm.getValue(1)
7302 };
Matt Arsenault37fefd62016-06-10 02:18:02 +00007303
Tom Stellard8485fa02016-12-07 02:42:15 +00007304 NegDivScale0 = DAG.getMergeValues(Ops, SL);
7305 }
7306
7307 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7308 ApproxRcp, One, NegDivScale0);
7309
7310 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7311 ApproxRcp, Fma0);
7312
7313 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7314 Fma1, Fma1);
7315
7316 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7317 NumeratorScaled, Mul);
7318
7319 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7320
7321 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7322 NumeratorScaled, Fma3);
7323
7324 if (!Subtarget->hasFP32Denormals()) {
7325 const SDValue DisableDenormValue =
7326 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7327 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7328 Fma4.getValue(1),
7329 DisableDenormValue,
7330 BitField,
7331 Fma4.getValue(2));
7332
7333 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7334 DisableDenorm, DAG.getRoot());
7335 DAG.setRoot(OutputChain);
7336 }
Matt Arsenault37fefd62016-06-10 02:18:02 +00007337
Wei Dinged0f97f2016-06-09 19:17:15 +00007338 SDValue Scale = NumeratorScaled.getValue(1);
Tom Stellard8485fa02016-12-07 02:42:15 +00007339 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7340 Fma4, Fma1, Fma3, Scale);
Matt Arsenault37fefd62016-06-10 02:18:02 +00007341
Wei Dinged0f97f2016-06-09 19:17:15 +00007342 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00007343}
7344
7345SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
Matt Arsenault0bbcd8b2015-02-14 04:30:08 +00007346 if (DAG.getTarget().Options.UnsafeFPMath)
Matt Arsenaulta1fe17c2016-07-19 23:16:53 +00007347 return lowerFastUnsafeFDIV(Op, DAG);
Matt Arsenault0bbcd8b2015-02-14 04:30:08 +00007348
7349 SDLoc SL(Op);
7350 SDValue X = Op.getOperand(0);
7351 SDValue Y = Op.getOperand(1);
7352
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007353 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
Matt Arsenault0bbcd8b2015-02-14 04:30:08 +00007354
7355 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7356
7357 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7358
7359 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7360
7361 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7362
7363 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7364
7365 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7366
7367 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7368
7369 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7370
7371 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7372 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7373
7374 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7375 NegDivScale0, Mul, DivScale1);
7376
7377 SDValue Scale;
7378
Matt Arsenaulte4c2e9b2019-06-19 23:54:58 +00007379 if (!Subtarget->hasUsableDivScaleConditionOutput()) {
Matt Arsenault0bbcd8b2015-02-14 04:30:08 +00007380 // Workaround a hardware bug on SI where the condition output from div_scale
7381 // is not usable.
7382
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007383 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
Matt Arsenault0bbcd8b2015-02-14 04:30:08 +00007384
7385 // Figure out if the scale to use for div_fmas.
7386 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7387 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7388 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7389 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7390
7391 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7392 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7393
7394 SDValue Scale0Hi
7395 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7396 SDValue Scale1Hi
7397 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7398
7399 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7400 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7401 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7402 } else {
7403 Scale = DivScale1.getValue(1);
7404 }
7405
7406 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7407 Fma4, Fma3, Mul, Scale);
7408
7409 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00007410}
7411
7412SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7413 EVT VT = Op.getValueType();
7414
7415 if (VT == MVT::f32)
7416 return LowerFDIV32(Op, DAG);
7417
7418 if (VT == MVT::f64)
7419 return LowerFDIV64(Op, DAG);
7420
Matt Arsenault4052a572016-12-22 03:05:41 +00007421 if (VT == MVT::f16)
7422 return LowerFDIV16(Op, DAG);
7423
Matt Arsenaulte9fa3b82014-07-15 20:18:31 +00007424 llvm_unreachable("Unexpected type for fdiv");
7425}
7426
Tom Stellard81d871d2013-11-13 23:36:50 +00007427SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7428 SDLoc DL(Op);
7429 StoreSDNode *Store = cast<StoreSDNode>(Op);
7430 EVT VT = Store->getMemoryVT();
7431
Matt Arsenault95245662016-02-11 05:32:46 +00007432 if (VT == MVT::i1) {
7433 return DAG.getTruncStore(Store->getChain(), DL,
7434 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7435 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
Tom Stellardb02094e2014-07-21 15:45:01 +00007436 }
7437
Matt Arsenaultbcdfee72016-05-02 20:13:51 +00007438 assert(VT.isVector() &&
7439 Store->getValue().getValueType().getScalarType() == MVT::i32);
7440
Matt Arsenaultbcdfee72016-05-02 20:13:51 +00007441 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
Simon Pilgrim266f4392019-06-11 11:00:23 +00007442 *Store->getMemOperand())) {
Matt Arsenaultbcdfee72016-05-02 20:13:51 +00007443 return expandUnalignedStore(Store, DAG);
7444 }
Tom Stellard81d871d2013-11-13 23:36:50 +00007445
Simon Pilgrim266f4392019-06-11 11:00:23 +00007446 unsigned AS = Store->getAddressSpace();
Stanislav Mekhanoshina224f682019-05-01 16:11:11 +00007447 if (Subtarget->hasLDSMisalignedBug() &&
7448 AS == AMDGPUAS::FLAT_ADDRESS &&
7449 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7450 return SplitVectorStore(Op, DAG);
7451 }
7452
Tom Stellardf8e6eaf2016-10-26 14:38:47 +00007453 MachineFunction &MF = DAG.getMachineFunction();
7454 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7455 // If there is a possibilty that flat instruction access scratch memory
7456 // then we need to use the same legalization rules we use for private.
Matt Arsenault0da63502018-08-31 05:49:54 +00007457 if (AS == AMDGPUAS::FLAT_ADDRESS)
Tom Stellardf8e6eaf2016-10-26 14:38:47 +00007458 AS = MFI->hasFlatScratchInit() ?
Matt Arsenault0da63502018-08-31 05:49:54 +00007459 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
Tom Stellardf8e6eaf2016-10-26 14:38:47 +00007460
Matt Arsenaultf2ddbf02016-02-13 04:18:53 +00007461 unsigned NumElements = VT.getVectorNumElements();
Matt Arsenault0da63502018-08-31 05:49:54 +00007462 if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7463 AS == AMDGPUAS::FLAT_ADDRESS) {
Matt Arsenaultf2ddbf02016-02-13 04:18:53 +00007464 if (NumElements > 4)
7465 return SplitVectorStore(Op, DAG);
Tim Renouf361b5b22019-03-21 12:01:21 +00007466 // v3 stores not supported on SI.
7467 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7468 return SplitVectorStore(Op, DAG);
Matt Arsenaultf2ddbf02016-02-13 04:18:53 +00007469 return SDValue();
Matt Arsenault0da63502018-08-31 05:49:54 +00007470 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
Matt Arsenaultf2ddbf02016-02-13 04:18:53 +00007471 switch (Subtarget->getMaxPrivateElementSize()) {
7472 case 4:
Matt Arsenault9c499c32016-04-14 23:31:26 +00007473 return scalarizeVectorStore(Store, DAG);
Matt Arsenaultf2ddbf02016-02-13 04:18:53 +00007474 case 8:
7475 if (NumElements > 2)
7476 return SplitVectorStore(Op, DAG);
7477 return SDValue();
7478 case 16:
Tim Renouf361b5b22019-03-21 12:01:21 +00007479 if (NumElements > 4 || NumElements == 3)
Matt Arsenaultf2ddbf02016-02-13 04:18:53 +00007480 return SplitVectorStore(Op, DAG);
7481 return SDValue();
7482 default:
7483 llvm_unreachable("unsupported private_element_size");
7484 }
Matt Arsenault0da63502018-08-31 05:49:54 +00007485 } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
Farhana Aleenc6c9dc82018-03-16 18:12:00 +00007486 // Use ds_write_b128 if possible.
Marek Olsaka9a58fa2018-04-10 22:48:23 +00007487 if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
Tim Renouf361b5b22019-03-21 12:01:21 +00007488 VT.getStoreSize() == 16 && NumElements != 3)
Farhana Aleenc6c9dc82018-03-16 18:12:00 +00007489 return SDValue();
7490
Matt Arsenaultbcdfee72016-05-02 20:13:51 +00007491 if (NumElements > 2)
7492 return SplitVectorStore(Op, DAG);
Nicolai Haehnle48219372018-10-17 15:37:48 +00007493
7494 // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7495 // address is negative, then the instruction is incorrectly treated as
7496 // out-of-bounds even if base + offsets is in bounds. Split vectorized
7497 // stores here to avoid emitting ds_write2_b32. We may re-combine the
7498 // store later in the SILoadStoreOptimizer.
Matt Arsenaulte4c2e9b2019-06-19 23:54:58 +00007499 if (!Subtarget->hasUsableDSOffset() &&
Nicolai Haehnle48219372018-10-17 15:37:48 +00007500 NumElements == 2 && VT.getStoreSize() == 8 &&
7501 Store->getAlignment() < 8) {
7502 return SplitVectorStore(Op, DAG);
7503 }
7504
Farhana Aleenc6c9dc82018-03-16 18:12:00 +00007505 return SDValue();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +00007506 } else {
Matt Arsenaultf2ddbf02016-02-13 04:18:53 +00007507 llvm_unreachable("unhandled address space");
Matt Arsenault95245662016-02-11 05:32:46 +00007508 }
Tom Stellard81d871d2013-11-13 23:36:50 +00007509}
7510
Matt Arsenaultad14ce82014-07-19 18:44:39 +00007511SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007512 SDLoc DL(Op);
Matt Arsenaultad14ce82014-07-19 18:44:39 +00007513 EVT VT = Op.getValueType();
7514 SDValue Arg = Op.getOperand(0);
David Stuttard20de3e92018-09-14 10:27:19 +00007515 SDValue TrigVal;
7516
Sanjay Patela2607012015-09-16 16:31:21 +00007517 // TODO: Should this propagate fast-math-flags?
David Stuttard20de3e92018-09-14 10:27:19 +00007518
7519 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7520
7521 if (Subtarget->hasTrigReducedRange()) {
7522 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7523 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7524 } else {
7525 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7526 }
Matt Arsenaultad14ce82014-07-19 18:44:39 +00007527
7528 switch (Op.getOpcode()) {
7529 case ISD::FCOS:
David Stuttard20de3e92018-09-14 10:27:19 +00007530 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
Matt Arsenaultad14ce82014-07-19 18:44:39 +00007531 case ISD::FSIN:
David Stuttard20de3e92018-09-14 10:27:19 +00007532 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
Matt Arsenaultad14ce82014-07-19 18:44:39 +00007533 default:
7534 llvm_unreachable("Wrong trig opcode");
7535 }
7536}
7537
Tom Stellard354a43c2016-04-01 18:27:37 +00007538SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7539 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7540 assert(AtomicNode->isCompareAndSwap());
7541 unsigned AS = AtomicNode->getAddressSpace();
7542
7543 // No custom lowering required for local address space
Matt Arsenault0da63502018-08-31 05:49:54 +00007544 if (!isFlatGlobalAddrSpace(AS))
Tom Stellard354a43c2016-04-01 18:27:37 +00007545 return Op;
7546
7547 // Non-local address space requires custom lowering for atomic compare
7548 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7549 SDLoc DL(Op);
7550 SDValue ChainIn = Op.getOperand(0);
7551 SDValue Addr = Op.getOperand(1);
7552 SDValue Old = Op.getOperand(2);
7553 SDValue New = Op.getOperand(3);
7554 EVT VT = Op.getValueType();
7555 MVT SimpleVT = VT.getSimpleVT();
7556 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
7557
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007558 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
Tom Stellard354a43c2016-04-01 18:27:37 +00007559 SDValue Ops[] = { ChainIn, Addr, NewOld };
Matt Arsenault88701812016-06-09 23:42:48 +00007560
7561 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
7562 Ops, VT, AtomicNode->getMemOperand());
Tom Stellard354a43c2016-04-01 18:27:37 +00007563}
7564
Tom Stellard75aadc22012-12-11 21:25:42 +00007565//===----------------------------------------------------------------------===//
7566// Custom DAG optimizations
7567//===----------------------------------------------------------------------===//
7568
Matt Arsenault364a6742014-06-11 17:50:44 +00007569SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
Matt Arsenaulte6986632015-01-14 01:35:22 +00007570 DAGCombinerInfo &DCI) const {
Matt Arsenault364a6742014-06-11 17:50:44 +00007571 EVT VT = N->getValueType(0);
7572 EVT ScalarVT = VT.getScalarType();
7573 if (ScalarVT != MVT::f32)
7574 return SDValue();
7575
7576 SelectionDAG &DAG = DCI.DAG;
7577 SDLoc DL(N);
7578
7579 SDValue Src = N->getOperand(0);
7580 EVT SrcVT = Src.getValueType();
7581
7582 // TODO: We could try to match extracting the higher bytes, which would be
7583 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
7584 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
7585 // about in practice.
Craig Topper80d3bb32018-03-06 19:44:52 +00007586 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
Matt Arsenault364a6742014-06-11 17:50:44 +00007587 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
7588 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
7589 DCI.AddToWorklist(Cvt.getNode());
7590 return Cvt;
7591 }
7592 }
7593
Matt Arsenault364a6742014-06-11 17:50:44 +00007594 return SDValue();
7595}
7596
Matt Arsenaultb2baffa2014-08-15 17:49:05 +00007597// (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
7598
7599// This is a variant of
7600// (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
7601//
7602// The normal DAG combiner will do this, but only if the add has one use since
7603// that would increase the number of instructions.
7604//
7605// This prevents us from seeing a constant offset that can be folded into a
7606// memory instruction's addressing mode. If we know the resulting add offset of
7607// a pointer can be folded into an addressing offset, we can replace the pointer
7608// operand with the add of new constant offset. This eliminates one of the uses,
7609// and may allow the remaining use to also be simplified.
7610//
7611SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
7612 unsigned AddrSpace,
Matt Arsenaultfbe95332017-11-13 05:11:54 +00007613 EVT MemVT,
Matt Arsenaultb2baffa2014-08-15 17:49:05 +00007614 DAGCombinerInfo &DCI) const {
7615 SDValue N0 = N->getOperand(0);
7616 SDValue N1 = N->getOperand(1);
7617
Matt Arsenaultfbe95332017-11-13 05:11:54 +00007618 // We only do this to handle cases where it's profitable when there are
7619 // multiple uses of the add, so defer to the standard combine.
Matt Arsenaultc8903122017-11-14 23:46:42 +00007620 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
7621 N0->hasOneUse())
Matt Arsenaultb2baffa2014-08-15 17:49:05 +00007622 return SDValue();
7623
7624 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
7625 if (!CN1)
7626 return SDValue();
7627
7628 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7629 if (!CAdd)
7630 return SDValue();
7631
Matt Arsenaultb2baffa2014-08-15 17:49:05 +00007632 // If the resulting offset is too large, we can't fold it into the addressing
7633 // mode offset.
7634 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
Matt Arsenaultfbe95332017-11-13 05:11:54 +00007635 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
7636
7637 AddrMode AM;
7638 AM.HasBaseReg = true;
7639 AM.BaseOffs = Offset.getSExtValue();
7640 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
Matt Arsenaultb2baffa2014-08-15 17:49:05 +00007641 return SDValue();
7642
7643 SelectionDAG &DAG = DCI.DAG;
7644 SDLoc SL(N);
7645 EVT VT = N->getValueType(0);
7646
7647 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007648 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
Matt Arsenaultb2baffa2014-08-15 17:49:05 +00007649
Matt Arsenaulte5e0c742017-11-13 05:33:35 +00007650 SDNodeFlags Flags;
7651 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
7652 (N0.getOpcode() == ISD::OR ||
7653 N0->getFlags().hasNoUnsignedWrap()));
7654
7655 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
Matt Arsenaultb2baffa2014-08-15 17:49:05 +00007656}
7657
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00007658SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
7659 DAGCombinerInfo &DCI) const {
7660 SDValue Ptr = N->getBasePtr();
7661 SelectionDAG &DAG = DCI.DAG;
7662 SDLoc SL(N);
7663
7664 // TODO: We could also do this for multiplies.
Matt Arsenaultfbe95332017-11-13 05:11:54 +00007665 if (Ptr.getOpcode() == ISD::SHL) {
7666 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
7667 N->getMemoryVT(), DCI);
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00007668 if (NewPtr) {
7669 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
7670
7671 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
7672 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
7673 }
7674 }
7675
7676 return SDValue();
7677}
7678
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00007679static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
7680 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
7681 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
7682 (Opc == ISD::XOR && Val == 0);
7683}
7684
7685// Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
7686// will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
7687// integer combine opportunities since most 64-bit operations are decomposed
7688// this way. TODO: We won't want this for SALU especially if it is an inline
7689// immediate.
7690SDValue SITargetLowering::splitBinaryBitConstantOp(
7691 DAGCombinerInfo &DCI,
7692 const SDLoc &SL,
7693 unsigned Opc, SDValue LHS,
7694 const ConstantSDNode *CRHS) const {
7695 uint64_t Val = CRHS->getZExtValue();
7696 uint32_t ValLo = Lo_32(Val);
7697 uint32_t ValHi = Hi_32(Val);
7698 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7699
7700 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
7701 bitOpWithConstantIsReducible(Opc, ValHi)) ||
7702 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
7703 // If we need to materialize a 64-bit immediate, it will be split up later
7704 // anyway. Avoid creating the harder to understand 64-bit immediate
7705 // materialization.
7706 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
7707 }
7708
7709 return SDValue();
7710}
7711
Stanislav Mekhanoshin6851ddf2017-06-27 18:25:26 +00007712// Returns true if argument is a boolean value which is not serialized into
7713// memory or argument and does not require v_cmdmask_b32 to be deserialized.
7714static bool isBoolSGPR(SDValue V) {
7715 if (V.getValueType() != MVT::i1)
7716 return false;
7717 switch (V.getOpcode()) {
7718 default: break;
7719 case ISD::SETCC:
7720 case ISD::AND:
7721 case ISD::OR:
7722 case ISD::XOR:
7723 case AMDGPUISD::FP_CLASS:
7724 return true;
7725 }
7726 return false;
7727}
7728
Stanislav Mekhanoshin8fd3c4e2018-06-12 23:50:37 +00007729// If a constant has all zeroes or all ones within each byte return it.
7730// Otherwise return 0.
7731static uint32_t getConstantPermuteMask(uint32_t C) {
7732 // 0xff for any zero byte in the mask
7733 uint32_t ZeroByteMask = 0;
7734 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
7735 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
7736 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
7737 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
7738 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
7739 if ((NonZeroByteMask & C) != NonZeroByteMask)
7740 return 0; // Partial bytes selected.
7741 return C;
7742}
7743
7744// Check if a node selects whole bytes from its operand 0 starting at a byte
7745// boundary while masking the rest. Returns select mask as in the v_perm_b32
7746// or -1 if not succeeded.
7747// Note byte select encoding:
7748// value 0-3 selects corresponding source byte;
7749// value 0xc selects zero;
7750// value 0xff selects 0xff.
7751static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
7752 assert(V.getValueSizeInBits() == 32);
7753
7754 if (V.getNumOperands() != 2)
7755 return ~0;
7756
7757 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
7758 if (!N1)
7759 return ~0;
7760
7761 uint32_t C = N1->getZExtValue();
7762
7763 switch (V.getOpcode()) {
7764 default:
7765 break;
7766 case ISD::AND:
7767 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
7768 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
7769 }
7770 break;
7771
7772 case ISD::OR:
7773 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
7774 return (0x03020100 & ~ConstMask) | ConstMask;
7775 }
7776 break;
7777
7778 case ISD::SHL:
7779 if (C % 8)
7780 return ~0;
7781
7782 return uint32_t((0x030201000c0c0c0cull << C) >> 32);
7783
7784 case ISD::SRL:
7785 if (C % 8)
7786 return ~0;
7787
7788 return uint32_t(0x0c0c0c0c03020100ull >> C);
7789 }
7790
7791 return ~0;
7792}
7793
Matt Arsenaultd0101a22015-01-06 23:00:46 +00007794SDValue SITargetLowering::performAndCombine(SDNode *N,
7795 DAGCombinerInfo &DCI) const {
7796 if (DCI.isBeforeLegalize())
7797 return SDValue();
7798
7799 SelectionDAG &DAG = DCI.DAG;
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00007800 EVT VT = N->getValueType(0);
Matt Arsenaultd0101a22015-01-06 23:00:46 +00007801 SDValue LHS = N->getOperand(0);
7802 SDValue RHS = N->getOperand(1);
7803
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00007804
Stanislav Mekhanoshin53a21292017-05-23 19:54:48 +00007805 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
7806 if (VT == MVT::i64 && CRHS) {
7807 if (SDValue Split
7808 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
7809 return Split;
7810 }
7811
7812 if (CRHS && VT == MVT::i32) {
7813 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
7814 // nb = number of trailing zeroes in mask
7815 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
7816 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
7817 uint64_t Mask = CRHS->getZExtValue();
7818 unsigned Bits = countPopulation(Mask);
7819 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
7820 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
7821 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
7822 unsigned Shift = CShift->getZExtValue();
7823 unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
7824 unsigned Offset = NB + Shift;
7825 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
7826 SDLoc SL(N);
7827 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
7828 LHS->getOperand(0),
7829 DAG.getConstant(Offset, SL, MVT::i32),
7830 DAG.getConstant(Bits, SL, MVT::i32));
7831 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7832 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
7833 DAG.getValueType(NarrowVT));
7834 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
7835 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
7836 return Shl;
7837 }
7838 }
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00007839 }
Stanislav Mekhanoshin8fd3c4e2018-06-12 23:50:37 +00007840
7841 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
7842 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
7843 isa<ConstantSDNode>(LHS.getOperand(2))) {
7844 uint32_t Sel = getConstantPermuteMask(Mask);
7845 if (!Sel)
7846 return SDValue();
7847
7848 // Select 0xc for all zero bytes
7849 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
7850 SDLoc DL(N);
7851 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
7852 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
7853 }
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00007854 }
7855
7856 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
7857 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
7858 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
Matt Arsenaultd0101a22015-01-06 23:00:46 +00007859 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7860 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
7861
7862 SDValue X = LHS.getOperand(0);
7863 SDValue Y = RHS.getOperand(0);
7864 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
7865 return SDValue();
7866
7867 if (LCC == ISD::SETO) {
7868 if (X != LHS.getOperand(1))
7869 return SDValue();
7870
7871 if (RCC == ISD::SETUNE) {
7872 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
7873 if (!C1 || !C1->isInfinity() || C1->isNegative())
7874 return SDValue();
7875
7876 const uint32_t Mask = SIInstrFlags::N_NORMAL |
7877 SIInstrFlags::N_SUBNORMAL |
7878 SIInstrFlags::N_ZERO |
7879 SIInstrFlags::P_ZERO |
7880 SIInstrFlags::P_SUBNORMAL |
7881 SIInstrFlags::P_NORMAL;
7882
7883 static_assert(((~(SIInstrFlags::S_NAN |
7884 SIInstrFlags::Q_NAN |
7885 SIInstrFlags::N_INFINITY |
7886 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
7887 "mask not equal");
7888
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007889 SDLoc DL(N);
7890 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
7891 X, DAG.getConstant(Mask, DL, MVT::i32));
Matt Arsenaultd0101a22015-01-06 23:00:46 +00007892 }
7893 }
7894 }
7895
Matt Arsenault3dcf4ce2018-08-10 18:58:56 +00007896 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
7897 std::swap(LHS, RHS);
7898
7899 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
7900 RHS.hasOneUse()) {
7901 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7902 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
7903 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
7904 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7905 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
7906 (RHS.getOperand(0) == LHS.getOperand(0) &&
7907 LHS.getOperand(0) == LHS.getOperand(1))) {
7908 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
7909 unsigned NewMask = LCC == ISD::SETO ?
7910 Mask->getZExtValue() & ~OrdMask :
7911 Mask->getZExtValue() & OrdMask;
7912
7913 SDLoc DL(N);
7914 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
7915 DAG.getConstant(NewMask, DL, MVT::i32));
7916 }
7917 }
7918
Stanislav Mekhanoshin6851ddf2017-06-27 18:25:26 +00007919 if (VT == MVT::i32 &&
7920 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
7921 // and x, (sext cc from i1) => select cc, x, 0
7922 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
7923 std::swap(LHS, RHS);
7924 if (isBoolSGPR(RHS.getOperand(0)))
7925 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
7926 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
7927 }
7928
Stanislav Mekhanoshin8fd3c4e2018-06-12 23:50:37 +00007929 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
7930 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7931 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
7932 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
7933 uint32_t LHSMask = getPermuteMask(DAG, LHS);
7934 uint32_t RHSMask = getPermuteMask(DAG, RHS);
7935 if (LHSMask != ~0u && RHSMask != ~0u) {
7936 // Canonicalize the expression in an attempt to have fewer unique masks
7937 // and therefore fewer registers used to hold the masks.
7938 if (LHSMask > RHSMask) {
7939 std::swap(LHSMask, RHSMask);
7940 std::swap(LHS, RHS);
7941 }
7942
7943 // Select 0xc for each lane used from source operand. Zero has 0xc mask
7944 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
7945 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7946 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7947
7948 // Check of we need to combine values from two sources within a byte.
7949 if (!(LHSUsedLanes & RHSUsedLanes) &&
7950 // If we select high and lower word keep it for SDWA.
7951 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
7952 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
7953 // Each byte in each mask is either selector mask 0-3, or has higher
7954 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
7955 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
7956 // mask which is not 0xff wins. By anding both masks we have a correct
7957 // result except that 0x0c shall be corrected to give 0x0c only.
7958 uint32_t Mask = LHSMask & RHSMask;
7959 for (unsigned I = 0; I < 32; I += 8) {
7960 uint32_t ByteSel = 0xff << I;
7961 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
7962 Mask &= (0x0c << I) & 0xffffffff;
7963 }
7964
7965 // Add 4 to each active LHS lane. It will not affect any existing 0xff
7966 // or 0x0c.
7967 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
7968 SDLoc DL(N);
7969
7970 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
7971 LHS.getOperand(0), RHS.getOperand(0),
7972 DAG.getConstant(Sel, DL, MVT::i32));
7973 }
7974 }
7975 }
7976
Matt Arsenaultd0101a22015-01-06 23:00:46 +00007977 return SDValue();
7978}
7979
Matt Arsenaultf2290332015-01-06 23:00:39 +00007980SDValue SITargetLowering::performOrCombine(SDNode *N,
7981 DAGCombinerInfo &DCI) const {
7982 SelectionDAG &DAG = DCI.DAG;
7983 SDValue LHS = N->getOperand(0);
7984 SDValue RHS = N->getOperand(1);
7985
Matt Arsenault3b082382016-04-12 18:24:38 +00007986 EVT VT = N->getValueType(0);
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00007987 if (VT == MVT::i1) {
7988 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
7989 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
7990 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
7991 SDValue Src = LHS.getOperand(0);
7992 if (Src != RHS.getOperand(0))
7993 return SDValue();
Matt Arsenault3b082382016-04-12 18:24:38 +00007994
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00007995 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
7996 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7997 if (!CLHS || !CRHS)
7998 return SDValue();
Matt Arsenault3b082382016-04-12 18:24:38 +00007999
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00008000 // Only 10 bits are used.
8001 static const uint32_t MaxMask = 0x3ff;
Matt Arsenault3b082382016-04-12 18:24:38 +00008002
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00008003 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8004 SDLoc DL(N);
8005 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8006 Src, DAG.getConstant(NewMask, DL, MVT::i32));
8007 }
Matt Arsenault3b082382016-04-12 18:24:38 +00008008
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00008009 return SDValue();
8010 }
8011
Stanislav Mekhanoshin8fd3c4e2018-06-12 23:50:37 +00008012 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8013 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8014 LHS.getOpcode() == AMDGPUISD::PERM &&
8015 isa<ConstantSDNode>(LHS.getOperand(2))) {
8016 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8017 if (!Sel)
8018 return SDValue();
8019
8020 Sel |= LHS.getConstantOperandVal(2);
8021 SDLoc DL(N);
8022 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8023 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8024 }
8025
8026 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8027 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8028 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8029 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8030 uint32_t LHSMask = getPermuteMask(DAG, LHS);
8031 uint32_t RHSMask = getPermuteMask(DAG, RHS);
8032 if (LHSMask != ~0u && RHSMask != ~0u) {
8033 // Canonicalize the expression in an attempt to have fewer unique masks
8034 // and therefore fewer registers used to hold the masks.
8035 if (LHSMask > RHSMask) {
8036 std::swap(LHSMask, RHSMask);
8037 std::swap(LHS, RHS);
8038 }
8039
8040 // Select 0xc for each lane used from source operand. Zero has 0xc mask
8041 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8042 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8043 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8044
8045 // Check of we need to combine values from two sources within a byte.
8046 if (!(LHSUsedLanes & RHSUsedLanes) &&
8047 // If we select high and lower word keep it for SDWA.
8048 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8049 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8050 // Kill zero bytes selected by other mask. Zero value is 0xc.
8051 LHSMask &= ~RHSUsedLanes;
8052 RHSMask &= ~LHSUsedLanes;
8053 // Add 4 to each active LHS lane
8054 LHSMask |= LHSUsedLanes & 0x04040404;
8055 // Combine masks
8056 uint32_t Sel = LHSMask | RHSMask;
8057 SDLoc DL(N);
8058
8059 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8060 LHS.getOperand(0), RHS.getOperand(0),
8061 DAG.getConstant(Sel, DL, MVT::i32));
8062 }
8063 }
8064 }
8065
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00008066 if (VT != MVT::i64)
8067 return SDValue();
8068
8069 // TODO: This could be a generic combine with a predicate for extracting the
8070 // high half of an integer being free.
8071
8072 // (or i64:x, (zero_extend i32:y)) ->
8073 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8074 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8075 RHS.getOpcode() != ISD::ZERO_EXTEND)
8076 std::swap(LHS, RHS);
8077
8078 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8079 SDValue ExtSrc = RHS.getOperand(0);
8080 EVT SrcVT = ExtSrc.getValueType();
8081 if (SrcVT == MVT::i32) {
8082 SDLoc SL(N);
8083 SDValue LowLHS, HiBits;
8084 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8085 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8086
8087 DCI.AddToWorklist(LowOr.getNode());
8088 DCI.AddToWorklist(HiBits.getNode());
8089
8090 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8091 LowOr, HiBits);
8092 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
Matt Arsenault3b082382016-04-12 18:24:38 +00008093 }
8094 }
8095
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00008096 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8097 if (CRHS) {
8098 if (SDValue Split
8099 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8100 return Split;
8101 }
Matt Arsenaultf2290332015-01-06 23:00:39 +00008102
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00008103 return SDValue();
8104}
Matt Arsenaultf2290332015-01-06 23:00:39 +00008105
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00008106SDValue SITargetLowering::performXorCombine(SDNode *N,
8107 DAGCombinerInfo &DCI) const {
8108 EVT VT = N->getValueType(0);
8109 if (VT != MVT::i64)
8110 return SDValue();
Matt Arsenaultf2290332015-01-06 23:00:39 +00008111
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00008112 SDValue LHS = N->getOperand(0);
8113 SDValue RHS = N->getOperand(1);
8114
8115 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8116 if (CRHS) {
8117 if (SDValue Split
8118 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8119 return Split;
Matt Arsenaultf2290332015-01-06 23:00:39 +00008120 }
8121
8122 return SDValue();
8123}
8124
Matt Arsenault5cf42712017-04-06 20:58:30 +00008125// Instructions that will be lowered with a final instruction that zeros the
8126// high result bits.
8127// XXX - probably only need to list legal operations.
Matt Arsenault8edfaee2017-03-31 19:53:03 +00008128static bool fp16SrcZerosHighBits(unsigned Opc) {
8129 switch (Opc) {
Matt Arsenault5cf42712017-04-06 20:58:30 +00008130 case ISD::FADD:
8131 case ISD::FSUB:
8132 case ISD::FMUL:
8133 case ISD::FDIV:
8134 case ISD::FREM:
8135 case ISD::FMA:
8136 case ISD::FMAD:
8137 case ISD::FCANONICALIZE:
8138 case ISD::FP_ROUND:
8139 case ISD::UINT_TO_FP:
8140 case ISD::SINT_TO_FP:
8141 case ISD::FABS:
8142 // Fabs is lowered to a bit operation, but it's an and which will clear the
8143 // high bits anyway.
8144 case ISD::FSQRT:
8145 case ISD::FSIN:
8146 case ISD::FCOS:
8147 case ISD::FPOWI:
8148 case ISD::FPOW:
8149 case ISD::FLOG:
8150 case ISD::FLOG2:
8151 case ISD::FLOG10:
8152 case ISD::FEXP:
8153 case ISD::FEXP2:
8154 case ISD::FCEIL:
8155 case ISD::FTRUNC:
8156 case ISD::FRINT:
8157 case ISD::FNEARBYINT:
8158 case ISD::FROUND:
8159 case ISD::FFLOOR:
8160 case ISD::FMINNUM:
8161 case ISD::FMAXNUM:
8162 case AMDGPUISD::FRACT:
8163 case AMDGPUISD::CLAMP:
8164 case AMDGPUISD::COS_HW:
8165 case AMDGPUISD::SIN_HW:
8166 case AMDGPUISD::FMIN3:
8167 case AMDGPUISD::FMAX3:
8168 case AMDGPUISD::FMED3:
8169 case AMDGPUISD::FMAD_FTZ:
8170 case AMDGPUISD::RCP:
8171 case AMDGPUISD::RSQ:
Stanislav Mekhanoshin1a1687f2018-06-27 15:33:33 +00008172 case AMDGPUISD::RCP_IFLAG:
Matt Arsenault5cf42712017-04-06 20:58:30 +00008173 case AMDGPUISD::LDEXP:
Matt Arsenault8edfaee2017-03-31 19:53:03 +00008174 return true;
Matt Arsenault5cf42712017-04-06 20:58:30 +00008175 default:
8176 // fcopysign, select and others may be lowered to 32-bit bit operations
8177 // which don't zero the high bits.
8178 return false;
Matt Arsenault8edfaee2017-03-31 19:53:03 +00008179 }
8180}
8181
8182SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8183 DAGCombinerInfo &DCI) const {
8184 if (!Subtarget->has16BitInsts() ||
8185 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8186 return SDValue();
8187
8188 EVT VT = N->getValueType(0);
8189 if (VT != MVT::i32)
8190 return SDValue();
8191
8192 SDValue Src = N->getOperand(0);
8193 if (Src.getValueType() != MVT::i16)
8194 return SDValue();
8195
8196 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8197 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8198 if (Src.getOpcode() == ISD::BITCAST) {
8199 SDValue BCSrc = Src.getOperand(0);
8200 if (BCSrc.getValueType() == MVT::f16 &&
8201 fp16SrcZerosHighBits(BCSrc.getOpcode()))
8202 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8203 }
8204
8205 return SDValue();
8206}
8207
Ryan Taylor00e063a2019-03-19 16:07:00 +00008208SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8209 DAGCombinerInfo &DCI)
8210 const {
8211 SDValue Src = N->getOperand(0);
8212 auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8213
8214 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8215 VTSign->getVT() == MVT::i8) ||
8216 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8217 VTSign->getVT() == MVT::i16)) &&
8218 Src.hasOneUse()) {
8219 auto *M = cast<MemSDNode>(Src);
8220 SDValue Ops[] = {
8221 Src.getOperand(0), // Chain
8222 Src.getOperand(1), // rsrc
8223 Src.getOperand(2), // vindex
8224 Src.getOperand(3), // voffset
8225 Src.getOperand(4), // soffset
8226 Src.getOperand(5), // offset
8227 Src.getOperand(6),
8228 Src.getOperand(7)
8229 };
8230 // replace with BUFFER_LOAD_BYTE/SHORT
8231 SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8232 Src.getOperand(0).getValueType());
8233 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8234 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8235 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8236 ResList,
8237 Ops, M->getMemoryVT(),
8238 M->getMemOperand());
8239 return DCI.DAG.getMergeValues({BufferLoadSignExt,
8240 BufferLoadSignExt.getValue(1)}, SDLoc(N));
8241 }
8242 return SDValue();
8243}
8244
Matt Arsenaultf2290332015-01-06 23:00:39 +00008245SDValue SITargetLowering::performClassCombine(SDNode *N,
8246 DAGCombinerInfo &DCI) const {
8247 SelectionDAG &DAG = DCI.DAG;
8248 SDValue Mask = N->getOperand(1);
8249
8250 // fp_class x, 0 -> false
8251 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8252 if (CMask->isNullValue())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008253 return DAG.getConstant(0, SDLoc(N), MVT::i1);
Matt Arsenaultf2290332015-01-06 23:00:39 +00008254 }
8255
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00008256 if (N->getOperand(0).isUndef())
8257 return DAG.getUNDEF(MVT::i1);
8258
Matt Arsenaultf2290332015-01-06 23:00:39 +00008259 return SDValue();
8260}
8261
Stanislav Mekhanoshin1a1687f2018-06-27 15:33:33 +00008262SDValue SITargetLowering::performRcpCombine(SDNode *N,
8263 DAGCombinerInfo &DCI) const {
8264 EVT VT = N->getValueType(0);
8265 SDValue N0 = N->getOperand(0);
8266
8267 if (N0.isUndef())
8268 return N0;
8269
8270 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8271 N0.getOpcode() == ISD::SINT_TO_FP)) {
8272 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8273 N->getFlags());
8274 }
8275
8276 return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8277}
8278
Matt Arsenaultf8768bf2018-08-06 21:38:27 +00008279bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8280 unsigned MaxDepth) const {
8281 unsigned Opcode = Op.getOpcode();
8282 if (Opcode == ISD::FCANONICALIZE)
8283 return true;
8284
8285 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8286 auto F = CFP->getValueAPF();
8287 if (F.isNaN() && F.isSignaling())
8288 return false;
8289 return !F.isDenormal() || denormalsEnabledForType(Op.getValueType());
8290 }
8291
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008292 // If source is a result of another standard FP operation it is already in
8293 // canonical form.
Matt Arsenaultf8768bf2018-08-06 21:38:27 +00008294 if (MaxDepth == 0)
8295 return false;
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008296
Matt Arsenaultf8768bf2018-08-06 21:38:27 +00008297 switch (Opcode) {
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008298 // These will flush denorms if required.
8299 case ISD::FADD:
8300 case ISD::FSUB:
8301 case ISD::FMUL:
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008302 case ISD::FCEIL:
8303 case ISD::FFLOOR:
8304 case ISD::FMA:
8305 case ISD::FMAD:
Matt Arsenaultf8768bf2018-08-06 21:38:27 +00008306 case ISD::FSQRT:
8307 case ISD::FDIV:
8308 case ISD::FREM:
Matt Arsenaultce6d61f2018-08-06 21:51:52 +00008309 case ISD::FP_ROUND:
8310 case ISD::FP_EXTEND:
Matt Arsenaultf8768bf2018-08-06 21:38:27 +00008311 case AMDGPUISD::FMUL_LEGACY:
8312 case AMDGPUISD::FMAD_FTZ:
Matt Arsenaultd49ab0b2018-08-06 21:58:11 +00008313 case AMDGPUISD::RCP:
8314 case AMDGPUISD::RSQ:
8315 case AMDGPUISD::RSQ_CLAMP:
8316 case AMDGPUISD::RCP_LEGACY:
8317 case AMDGPUISD::RSQ_LEGACY:
8318 case AMDGPUISD::RCP_IFLAG:
8319 case AMDGPUISD::TRIG_PREOP:
8320 case AMDGPUISD::DIV_SCALE:
8321 case AMDGPUISD::DIV_FMAS:
8322 case AMDGPUISD::DIV_FIXUP:
8323 case AMDGPUISD::FRACT:
8324 case AMDGPUISD::LDEXP:
Matt Arsenault08f3fe42018-08-06 23:01:31 +00008325 case AMDGPUISD::CVT_PKRTZ_F16_F32:
Matt Arsenault940e6072018-08-10 19:20:17 +00008326 case AMDGPUISD::CVT_F32_UBYTE0:
8327 case AMDGPUISD::CVT_F32_UBYTE1:
8328 case AMDGPUISD::CVT_F32_UBYTE2:
8329 case AMDGPUISD::CVT_F32_UBYTE3:
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008330 return true;
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008331
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008332 // It can/will be lowered or combined as a bit operation.
8333 // Need to check their input recursively to handle.
8334 case ISD::FNEG:
8335 case ISD::FABS:
Matt Arsenaultf8768bf2018-08-06 21:38:27 +00008336 case ISD::FCOPYSIGN:
8337 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008338
8339 case ISD::FSIN:
8340 case ISD::FCOS:
8341 case ISD::FSINCOS:
8342 return Op.getValueType().getScalarType() != MVT::f16;
8343
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008344 case ISD::FMINNUM:
Matt Arsenaultd49ab0b2018-08-06 21:58:11 +00008345 case ISD::FMAXNUM:
Matt Arsenault687ec752018-10-22 16:27:27 +00008346 case ISD::FMINNUM_IEEE:
8347 case ISD::FMAXNUM_IEEE:
Matt Arsenaultd49ab0b2018-08-06 21:58:11 +00008348 case AMDGPUISD::CLAMP:
8349 case AMDGPUISD::FMED3:
8350 case AMDGPUISD::FMAX3:
8351 case AMDGPUISD::FMIN3: {
Matt Arsenaultf8768bf2018-08-06 21:38:27 +00008352 // FIXME: Shouldn't treat the generic operations different based these.
Matt Arsenault687ec752018-10-22 16:27:27 +00008353 // However, we aren't really required to flush the result from
8354 // minnum/maxnum..
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008355
Matt Arsenault687ec752018-10-22 16:27:27 +00008356 // snans will be quieted, so we only need to worry about denormals.
Matt Arsenaultf8768bf2018-08-06 21:38:27 +00008357 if (Subtarget->supportsMinMaxDenormModes() ||
Matt Arsenault687ec752018-10-22 16:27:27 +00008358 denormalsEnabledForType(Op.getValueType()))
8359 return true;
8360
8361 // Flushing may be required.
8362 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8363 // targets need to check their input recursively.
8364
8365 // FIXME: Does this apply with clamp? It's implemented with max.
8366 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8367 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8368 return false;
Matt Arsenaultf8768bf2018-08-06 21:38:27 +00008369 }
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008370
Matt Arsenault687ec752018-10-22 16:27:27 +00008371 return true;
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008372 }
Matt Arsenaultf8768bf2018-08-06 21:38:27 +00008373 case ISD::SELECT: {
8374 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8375 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008376 }
Matt Arsenaulte94ee832018-08-06 22:45:51 +00008377 case ISD::BUILD_VECTOR: {
8378 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8379 SDValue SrcOp = Op.getOperand(i);
8380 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8381 return false;
8382 }
8383
8384 return true;
8385 }
8386 case ISD::EXTRACT_VECTOR_ELT:
8387 case ISD::EXTRACT_SUBVECTOR: {
8388 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8389 }
8390 case ISD::INSERT_VECTOR_ELT: {
8391 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8392 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8393 }
8394 case ISD::UNDEF:
8395 // Could be anything.
8396 return false;
Matt Arsenault08f3fe42018-08-06 23:01:31 +00008397
Matt Arsenault687ec752018-10-22 16:27:27 +00008398 case ISD::BITCAST: {
8399 // Hack round the mess we make when legalizing extract_vector_elt
8400 SDValue Src = Op.getOperand(0);
8401 if (Src.getValueType() == MVT::i16 &&
8402 Src.getOpcode() == ISD::TRUNCATE) {
8403 SDValue TruncSrc = Src.getOperand(0);
8404 if (TruncSrc.getValueType() == MVT::i32 &&
8405 TruncSrc.getOpcode() == ISD::BITCAST &&
8406 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8407 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8408 }
8409 }
8410
8411 return false;
8412 }
Matt Arsenault08f3fe42018-08-06 23:01:31 +00008413 case ISD::INTRINSIC_WO_CHAIN: {
8414 unsigned IntrinsicID
8415 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8416 // TODO: Handle more intrinsics
8417 switch (IntrinsicID) {
8418 case Intrinsic::amdgcn_cvt_pkrtz:
Matt Arsenault940e6072018-08-10 19:20:17 +00008419 case Intrinsic::amdgcn_cubeid:
8420 case Intrinsic::amdgcn_frexp_mant:
8421 case Intrinsic::amdgcn_fdot2:
Matt Arsenault08f3fe42018-08-06 23:01:31 +00008422 return true;
8423 default:
8424 break;
8425 }
Matt Arsenault5bb9d792018-08-10 17:57:12 +00008426
8427 LLVM_FALLTHROUGH;
Matt Arsenault08f3fe42018-08-06 23:01:31 +00008428 }
Matt Arsenaultf8768bf2018-08-06 21:38:27 +00008429 default:
8430 return denormalsEnabledForType(Op.getValueType()) &&
8431 DAG.isKnownNeverSNaN(Op);
8432 }
8433
8434 llvm_unreachable("invalid operation");
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008435}
8436
Matt Arsenault9cd90712016-04-14 01:42:16 +00008437// Constant fold canonicalize.
Matt Arsenaultf2a167f2018-08-06 22:10:26 +00008438SDValue SITargetLowering::getCanonicalConstantFP(
8439 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8440 // Flush denormals to 0 if not enabled.
8441 if (C.isDenormal() && !denormalsEnabledForType(VT))
8442 return DAG.getConstantFP(0.0, SL, VT);
8443
8444 if (C.isNaN()) {
8445 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8446 if (C.isSignaling()) {
8447 // Quiet a signaling NaN.
8448 // FIXME: Is this supposed to preserve payload bits?
8449 return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8450 }
8451
8452 // Make sure it is the canonical NaN bitpattern.
8453 //
8454 // TODO: Can we use -1 as the canonical NaN value since it's an inline
8455 // immediate?
8456 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8457 return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8458 }
8459
8460 // Already canonical.
8461 return DAG.getConstantFP(C, SL, VT);
8462}
8463
Matt Arsenaulta29e7622018-08-06 22:30:44 +00008464static bool vectorEltWillFoldAway(SDValue Op) {
8465 return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8466}
8467
Matt Arsenault9cd90712016-04-14 01:42:16 +00008468SDValue SITargetLowering::performFCanonicalizeCombine(
8469 SDNode *N,
8470 DAGCombinerInfo &DCI) const {
Matt Arsenault9cd90712016-04-14 01:42:16 +00008471 SelectionDAG &DAG = DCI.DAG;
Matt Arsenault4aec86d2018-07-31 13:34:31 +00008472 SDValue N0 = N->getOperand(0);
Matt Arsenaulta29e7622018-08-06 22:30:44 +00008473 EVT VT = N->getValueType(0);
Stanislav Mekhanoshin5680b0c2017-07-12 21:20:28 +00008474
Matt Arsenault4aec86d2018-07-31 13:34:31 +00008475 // fcanonicalize undef -> qnan
8476 if (N0.isUndef()) {
Matt Arsenault4aec86d2018-07-31 13:34:31 +00008477 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8478 return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8479 }
8480
Matt Arsenaultf2a167f2018-08-06 22:10:26 +00008481 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
Matt Arsenault9cd90712016-04-14 01:42:16 +00008482 EVT VT = N->getValueType(0);
Matt Arsenaultf2a167f2018-08-06 22:10:26 +00008483 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
Matt Arsenault9cd90712016-04-14 01:42:16 +00008484 }
8485
Matt Arsenaulta29e7622018-08-06 22:30:44 +00008486 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8487 // (fcanonicalize k)
8488 //
8489 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8490
8491 // TODO: This could be better with wider vectors that will be split to v2f16,
8492 // and to consider uses since there aren't that many packed operations.
Matt Arsenaultb5acec12018-08-12 08:42:54 +00008493 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8494 isTypeLegal(MVT::v2f16)) {
Matt Arsenaulta29e7622018-08-06 22:30:44 +00008495 SDLoc SL(N);
8496 SDValue NewElts[2];
8497 SDValue Lo = N0.getOperand(0);
8498 SDValue Hi = N0.getOperand(1);
Matt Arsenaultb5acec12018-08-12 08:42:54 +00008499 EVT EltVT = Lo.getValueType();
8500
Matt Arsenaulta29e7622018-08-06 22:30:44 +00008501 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8502 for (unsigned I = 0; I != 2; ++I) {
8503 SDValue Op = N0.getOperand(I);
Matt Arsenaulta29e7622018-08-06 22:30:44 +00008504 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8505 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8506 CFP->getValueAPF());
8507 } else if (Op.isUndef()) {
Matt Arsenaultb5acec12018-08-12 08:42:54 +00008508 // Handled below based on what the other operand is.
8509 NewElts[I] = Op;
Matt Arsenaulta29e7622018-08-06 22:30:44 +00008510 } else {
8511 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8512 }
8513 }
8514
Matt Arsenaultb5acec12018-08-12 08:42:54 +00008515 // If one half is undef, and one is constant, perfer a splat vector rather
8516 // than the normal qNaN. If it's a register, prefer 0.0 since that's
8517 // cheaper to use and may be free with a packed operation.
8518 if (NewElts[0].isUndef()) {
8519 if (isa<ConstantFPSDNode>(NewElts[1]))
8520 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8521 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8522 }
8523
8524 if (NewElts[1].isUndef()) {
8525 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8526 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8527 }
8528
Matt Arsenaulta29e7622018-08-06 22:30:44 +00008529 return DAG.getBuildVector(VT, SL, NewElts);
8530 }
8531 }
8532
Matt Arsenault687ec752018-10-22 16:27:27 +00008533 unsigned SrcOpc = N0.getOpcode();
8534
8535 // If it's free to do so, push canonicalizes further up the source, which may
8536 // find a canonical source.
8537 //
8538 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
8539 // sNaNs.
8540 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
8541 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8542 if (CRHS && N0.hasOneUse()) {
8543 SDLoc SL(N);
8544 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
8545 N0.getOperand(0));
8546 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
8547 DCI.AddToWorklist(Canon0.getNode());
8548
8549 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
8550 }
8551 }
8552
Matt Arsenaultf2a167f2018-08-06 22:10:26 +00008553 return isCanonicalized(DAG, N0) ? N0 : SDValue();
Matt Arsenault9cd90712016-04-14 01:42:16 +00008554}
8555
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008556static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
8557 switch (Opc) {
8558 case ISD::FMAXNUM:
Matt Arsenault687ec752018-10-22 16:27:27 +00008559 case ISD::FMAXNUM_IEEE:
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008560 return AMDGPUISD::FMAX3;
Matt Arsenault5881f4e2015-06-09 00:52:37 +00008561 case ISD::SMAX:
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008562 return AMDGPUISD::SMAX3;
Matt Arsenault5881f4e2015-06-09 00:52:37 +00008563 case ISD::UMAX:
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008564 return AMDGPUISD::UMAX3;
8565 case ISD::FMINNUM:
Matt Arsenault687ec752018-10-22 16:27:27 +00008566 case ISD::FMINNUM_IEEE:
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008567 return AMDGPUISD::FMIN3;
Matt Arsenault5881f4e2015-06-09 00:52:37 +00008568 case ISD::SMIN:
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008569 return AMDGPUISD::SMIN3;
Matt Arsenault5881f4e2015-06-09 00:52:37 +00008570 case ISD::UMIN:
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008571 return AMDGPUISD::UMIN3;
8572 default:
8573 llvm_unreachable("Not a min/max opcode");
8574 }
8575}
8576
Matt Arsenault10268f92017-02-27 22:40:39 +00008577SDValue SITargetLowering::performIntMed3ImmCombine(
8578 SelectionDAG &DAG, const SDLoc &SL,
8579 SDValue Op0, SDValue Op1, bool Signed) const {
Matt Arsenaultf639c322016-01-28 20:53:42 +00008580 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
8581 if (!K1)
8582 return SDValue();
8583
8584 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
8585 if (!K0)
8586 return SDValue();
8587
Matt Arsenaultf639c322016-01-28 20:53:42 +00008588 if (Signed) {
8589 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
8590 return SDValue();
8591 } else {
8592 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
8593 return SDValue();
8594 }
8595
8596 EVT VT = K0->getValueType(0);
Matt Arsenault10268f92017-02-27 22:40:39 +00008597 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
8598 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
8599 return DAG.getNode(Med3Opc, SL, VT,
8600 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
8601 }
Tom Stellard115a6152016-11-10 16:02:37 +00008602
Matt Arsenault10268f92017-02-27 22:40:39 +00008603 // If there isn't a 16-bit med3 operation, convert to 32-bit.
Tom Stellard115a6152016-11-10 16:02:37 +00008604 MVT NVT = MVT::i32;
8605 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8606
Matt Arsenault10268f92017-02-27 22:40:39 +00008607 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
8608 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
8609 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
Tom Stellard115a6152016-11-10 16:02:37 +00008610
Matt Arsenault10268f92017-02-27 22:40:39 +00008611 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
8612 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
Matt Arsenaultf639c322016-01-28 20:53:42 +00008613}
8614
Matt Arsenault6b114d22017-08-30 01:20:17 +00008615static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
8616 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
8617 return C;
8618
8619 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
8620 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
8621 return C;
8622 }
8623
8624 return nullptr;
8625}
8626
Matt Arsenault2fdf2a12017-02-21 23:35:48 +00008627SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
8628 const SDLoc &SL,
8629 SDValue Op0,
8630 SDValue Op1) const {
Matt Arsenault6b114d22017-08-30 01:20:17 +00008631 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
Matt Arsenaultf639c322016-01-28 20:53:42 +00008632 if (!K1)
8633 return SDValue();
8634
Matt Arsenault6b114d22017-08-30 01:20:17 +00008635 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
Matt Arsenaultf639c322016-01-28 20:53:42 +00008636 if (!K0)
8637 return SDValue();
8638
8639 // Ordered >= (although NaN inputs should have folded away by now).
8640 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
8641 if (Cmp == APFloat::cmpGreaterThan)
8642 return SDValue();
8643
Matt Arsenault055e4dc2019-03-29 19:14:54 +00008644 const MachineFunction &MF = DAG.getMachineFunction();
8645 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8646
Matt Arsenault2fdf2a12017-02-21 23:35:48 +00008647 // TODO: Check IEEE bit enabled?
Matt Arsenault6b114d22017-08-30 01:20:17 +00008648 EVT VT = Op0.getValueType();
Matt Arsenault055e4dc2019-03-29 19:14:54 +00008649 if (Info->getMode().DX10Clamp) {
Matt Arsenault2fdf2a12017-02-21 23:35:48 +00008650 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
8651 // hardware fmed3 behavior converting to a min.
8652 // FIXME: Should this be allowing -0.0?
8653 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
8654 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
8655 }
8656
Matt Arsenault6b114d22017-08-30 01:20:17 +00008657 // med3 for f16 is only available on gfx9+, and not available for v2f16.
8658 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
8659 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
8660 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
8661 // then give the other result, which is different from med3 with a NaN
8662 // input.
8663 SDValue Var = Op0.getOperand(0);
Matt Arsenaultc3dc8e62018-08-03 18:27:52 +00008664 if (!DAG.isKnownNeverSNaN(Var))
Matt Arsenault6b114d22017-08-30 01:20:17 +00008665 return SDValue();
Matt Arsenault2fdf2a12017-02-21 23:35:48 +00008666
Matt Arsenaultebf46142018-09-18 02:34:54 +00008667 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8668
8669 if ((!K0->hasOneUse() ||
8670 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
8671 (!K1->hasOneUse() ||
8672 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
8673 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
8674 Var, SDValue(K0, 0), SDValue(K1, 0));
8675 }
Matt Arsenault6b114d22017-08-30 01:20:17 +00008676 }
Matt Arsenaultf639c322016-01-28 20:53:42 +00008677
Matt Arsenault6b114d22017-08-30 01:20:17 +00008678 return SDValue();
Matt Arsenaultf639c322016-01-28 20:53:42 +00008679}
8680
8681SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
8682 DAGCombinerInfo &DCI) const {
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008683 SelectionDAG &DAG = DCI.DAG;
8684
Matt Arsenault79a45db2017-02-22 23:53:37 +00008685 EVT VT = N->getValueType(0);
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008686 unsigned Opc = N->getOpcode();
8687 SDValue Op0 = N->getOperand(0);
8688 SDValue Op1 = N->getOperand(1);
8689
8690 // Only do this if the inner op has one use since this will just increases
8691 // register pressure for no benefit.
8692
Matt Arsenault79a45db2017-02-22 23:53:37 +00008693 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
Neil Henninge85f6bd2019-03-19 15:50:24 +00008694 !VT.isVector() &&
8695 (VT == MVT::i32 || VT == MVT::f32 ||
8696 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
Matt Arsenault5b39b342016-01-28 20:53:48 +00008697 // max(max(a, b), c) -> max3(a, b, c)
8698 // min(min(a, b), c) -> min3(a, b, c)
8699 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
8700 SDLoc DL(N);
8701 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
8702 DL,
8703 N->getValueType(0),
8704 Op0.getOperand(0),
8705 Op0.getOperand(1),
8706 Op1);
8707 }
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008708
Matt Arsenault5b39b342016-01-28 20:53:48 +00008709 // Try commuted.
8710 // max(a, max(b, c)) -> max3(a, b, c)
8711 // min(a, min(b, c)) -> min3(a, b, c)
8712 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
8713 SDLoc DL(N);
8714 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
8715 DL,
8716 N->getValueType(0),
8717 Op0,
8718 Op1.getOperand(0),
8719 Op1.getOperand(1));
8720 }
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008721 }
8722
Matt Arsenaultf639c322016-01-28 20:53:42 +00008723 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
8724 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
8725 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
8726 return Med3;
8727 }
8728
8729 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
8730 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
8731 return Med3;
8732 }
8733
8734 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
Matt Arsenault5b39b342016-01-28 20:53:48 +00008735 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
Matt Arsenault687ec752018-10-22 16:27:27 +00008736 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
Matt Arsenault5b39b342016-01-28 20:53:48 +00008737 (Opc == AMDGPUISD::FMIN_LEGACY &&
8738 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
Matt Arsenault79a45db2017-02-22 23:53:37 +00008739 (VT == MVT::f32 || VT == MVT::f64 ||
Matt Arsenault6b114d22017-08-30 01:20:17 +00008740 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
8741 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
Matt Arsenault2fdf2a12017-02-21 23:35:48 +00008742 Op0.hasOneUse()) {
Matt Arsenaultf639c322016-01-28 20:53:42 +00008743 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
8744 return Res;
8745 }
8746
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00008747 return SDValue();
8748}
8749
Matt Arsenault2fdf2a12017-02-21 23:35:48 +00008750static bool isClampZeroToOne(SDValue A, SDValue B) {
8751 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
8752 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
8753 // FIXME: Should this be allowing -0.0?
8754 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
8755 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
8756 }
8757 }
8758
8759 return false;
8760}
8761
8762// FIXME: Should only worry about snans for version with chain.
8763SDValue SITargetLowering::performFMed3Combine(SDNode *N,
8764 DAGCombinerInfo &DCI) const {
8765 EVT VT = N->getValueType(0);
8766 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
8767 // NaNs. With a NaN input, the order of the operands may change the result.
8768
8769 SelectionDAG &DAG = DCI.DAG;
8770 SDLoc SL(N);
8771
8772 SDValue Src0 = N->getOperand(0);
8773 SDValue Src1 = N->getOperand(1);
8774 SDValue Src2 = N->getOperand(2);
8775
8776 if (isClampZeroToOne(Src0, Src1)) {
8777 // const_a, const_b, x -> clamp is safe in all cases including signaling
8778 // nans.
8779 // FIXME: Should this be allowing -0.0?
8780 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
8781 }
8782
Matt Arsenault055e4dc2019-03-29 19:14:54 +00008783 const MachineFunction &MF = DAG.getMachineFunction();
8784 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8785
Matt Arsenault2fdf2a12017-02-21 23:35:48 +00008786 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
8787 // handling no dx10-clamp?
Matt Arsenault055e4dc2019-03-29 19:14:54 +00008788 if (Info->getMode().DX10Clamp) {
Matt Arsenault2fdf2a12017-02-21 23:35:48 +00008789 // If NaNs is clamped to 0, we are free to reorder the inputs.
8790
8791 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
8792 std::swap(Src0, Src1);
8793
8794 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
8795 std::swap(Src1, Src2);
8796
8797 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
8798 std::swap(Src0, Src1);
8799
8800 if (isClampZeroToOne(Src1, Src2))
8801 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
8802 }
8803
8804 return SDValue();
8805}
8806
Matt Arsenault1f17c662017-02-22 00:27:34 +00008807SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
8808 DAGCombinerInfo &DCI) const {
8809 SDValue Src0 = N->getOperand(0);
8810 SDValue Src1 = N->getOperand(1);
8811 if (Src0.isUndef() && Src1.isUndef())
8812 return DCI.DAG.getUNDEF(N->getValueType(0));
8813 return SDValue();
8814}
8815
Matt Arsenaultbf5482e2017-05-11 17:26:25 +00008816SDValue SITargetLowering::performExtractVectorEltCombine(
8817 SDNode *N, DAGCombinerInfo &DCI) const {
8818 SDValue Vec = N->getOperand(0);
Matt Arsenault8cbb4882017-09-20 21:01:24 +00008819 SelectionDAG &DAG = DCI.DAG;
Matt Arsenault63bc0e32018-06-15 15:31:36 +00008820
8821 EVT VecVT = Vec.getValueType();
8822 EVT EltVT = VecVT.getVectorElementType();
8823
Matt Arsenaultfcc5ba42018-04-26 19:21:32 +00008824 if ((Vec.getOpcode() == ISD::FNEG ||
8825 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
Matt Arsenaultbf5482e2017-05-11 17:26:25 +00008826 SDLoc SL(N);
8827 EVT EltVT = N->getValueType(0);
8828 SDValue Idx = N->getOperand(1);
8829 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8830 Vec.getOperand(0), Idx);
Matt Arsenaultfcc5ba42018-04-26 19:21:32 +00008831 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
Matt Arsenaultbf5482e2017-05-11 17:26:25 +00008832 }
8833
Farhana Aleene2dfe8a2018-05-01 21:41:12 +00008834 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
8835 // =>
8836 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
8837 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
8838 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
Farhana Aleene24f3ff2018-05-09 21:18:34 +00008839 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
Farhana Aleene2dfe8a2018-05-01 21:41:12 +00008840 SDLoc SL(N);
8841 EVT EltVT = N->getValueType(0);
8842 SDValue Idx = N->getOperand(1);
8843 unsigned Opc = Vec.getOpcode();
8844
8845 switch(Opc) {
8846 default:
Stanislav Mekhanoshinbcb34ac2018-11-13 21:18:21 +00008847 break;
Farhana Aleene2dfe8a2018-05-01 21:41:12 +00008848 // TODO: Support other binary operations.
8849 case ISD::FADD:
Matt Arsenaulta8160732018-08-15 21:34:06 +00008850 case ISD::FSUB:
8851 case ISD::FMUL:
Farhana Aleene2dfe8a2018-05-01 21:41:12 +00008852 case ISD::ADD:
Farhana Aleene24f3ff2018-05-09 21:18:34 +00008853 case ISD::UMIN:
8854 case ISD::UMAX:
8855 case ISD::SMIN:
8856 case ISD::SMAX:
8857 case ISD::FMAXNUM:
Matt Arsenault687ec752018-10-22 16:27:27 +00008858 case ISD::FMINNUM:
8859 case ISD::FMAXNUM_IEEE:
8860 case ISD::FMINNUM_IEEE: {
Matt Arsenaulta8160732018-08-15 21:34:06 +00008861 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8862 Vec.getOperand(0), Idx);
8863 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8864 Vec.getOperand(1), Idx);
8865
8866 DCI.AddToWorklist(Elt0.getNode());
8867 DCI.AddToWorklist(Elt1.getNode());
8868 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
8869 }
Farhana Aleene2dfe8a2018-05-01 21:41:12 +00008870 }
8871 }
Matt Arsenault63bc0e32018-06-15 15:31:36 +00008872
Matt Arsenault63bc0e32018-06-15 15:31:36 +00008873 unsigned VecSize = VecVT.getSizeInBits();
8874 unsigned EltSize = EltVT.getSizeInBits();
8875
Stanislav Mekhanoshinbcb34ac2018-11-13 21:18:21 +00008876 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
8877 // This elminates non-constant index and subsequent movrel or scratch access.
8878 // Sub-dword vectors of size 2 dword or less have better implementation.
8879 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
8880 // instructions.
8881 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
8882 !isa<ConstantSDNode>(N->getOperand(1))) {
8883 SDLoc SL(N);
8884 SDValue Idx = N->getOperand(1);
8885 EVT IdxVT = Idx.getValueType();
8886 SDValue V;
8887 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
8888 SDValue IC = DAG.getConstant(I, SL, IdxVT);
8889 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
8890 if (I == 0)
8891 V = Elt;
8892 else
8893 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
8894 }
8895 return V;
8896 }
8897
8898 if (!DCI.isBeforeLegalize())
8899 return SDValue();
8900
Matt Arsenault63bc0e32018-06-15 15:31:36 +00008901 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
8902 // elements. This exposes more load reduction opportunities by replacing
8903 // multiple small extract_vector_elements with a single 32-bit extract.
8904 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
Matt Arsenaultbf07a502018-08-31 15:39:52 +00008905 if (isa<MemSDNode>(Vec) &&
8906 EltSize <= 16 &&
Matt Arsenault63bc0e32018-06-15 15:31:36 +00008907 EltVT.isByteSized() &&
8908 VecSize > 32 &&
8909 VecSize % 32 == 0 &&
8910 Idx) {
8911 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
8912
8913 unsigned BitIndex = Idx->getZExtValue() * EltSize;
8914 unsigned EltIdx = BitIndex / 32;
8915 unsigned LeftoverBitIdx = BitIndex % 32;
8916 SDLoc SL(N);
8917
8918 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
8919 DCI.AddToWorklist(Cast.getNode());
8920
8921 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
8922 DAG.getConstant(EltIdx, SL, MVT::i32));
8923 DCI.AddToWorklist(Elt.getNode());
8924 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
8925 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
8926 DCI.AddToWorklist(Srl.getNode());
8927
8928 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
8929 DCI.AddToWorklist(Trunc.getNode());
8930 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
8931 }
8932
Matt Arsenaultbf5482e2017-05-11 17:26:25 +00008933 return SDValue();
8934}
8935
Stanislav Mekhanoshin054f8102018-11-19 17:39:20 +00008936SDValue
8937SITargetLowering::performInsertVectorEltCombine(SDNode *N,
8938 DAGCombinerInfo &DCI) const {
8939 SDValue Vec = N->getOperand(0);
8940 SDValue Idx = N->getOperand(2);
8941 EVT VecVT = Vec.getValueType();
8942 EVT EltVT = VecVT.getVectorElementType();
8943 unsigned VecSize = VecVT.getSizeInBits();
8944 unsigned EltSize = EltVT.getSizeInBits();
8945
8946 // INSERT_VECTOR_ELT (<n x e>, var-idx)
8947 // => BUILD_VECTOR n x select (e, const-idx)
8948 // This elminates non-constant index and subsequent movrel or scratch access.
8949 // Sub-dword vectors of size 2 dword or less have better implementation.
8950 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
8951 // instructions.
8952 if (isa<ConstantSDNode>(Idx) ||
8953 VecSize > 256 || (VecSize <= 64 && EltSize < 32))
8954 return SDValue();
8955
8956 SelectionDAG &DAG = DCI.DAG;
8957 SDLoc SL(N);
8958 SDValue Ins = N->getOperand(1);
8959 EVT IdxVT = Idx.getValueType();
8960
Stanislav Mekhanoshin054f8102018-11-19 17:39:20 +00008961 SmallVector<SDValue, 16> Ops;
8962 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
8963 SDValue IC = DAG.getConstant(I, SL, IdxVT);
8964 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
8965 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
8966 Ops.push_back(V);
8967 }
8968
8969 return DAG.getBuildVector(VecVT, SL, Ops);
8970}
8971
Matt Arsenault46e6b7a2016-12-22 04:03:35 +00008972unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
8973 const SDNode *N0,
8974 const SDNode *N1) const {
8975 EVT VT = N0->getValueType(0);
8976
Matt Arsenault770ec862016-12-22 03:55:35 +00008977 // Only do this if we are not trying to support denormals. v_mad_f32 does not
8978 // support denormals ever.
Stanislav Mekhanoshin28a19362019-05-04 04:20:37 +00008979 if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
8980 (VT == MVT::f16 && !Subtarget->hasFP16Denormals() &&
8981 getSubtarget()->hasMadF16())) &&
8982 isOperationLegal(ISD::FMAD, VT))
Matt Arsenault770ec862016-12-22 03:55:35 +00008983 return ISD::FMAD;
8984
8985 const TargetOptions &Options = DAG.getTarget().Options;
Amara Emersond28f0cd42017-05-01 15:17:51 +00008986 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
Michael Berg7acc81b2018-05-04 18:48:20 +00008987 (N0->getFlags().hasAllowContract() &&
8988 N1->getFlags().hasAllowContract())) &&
Matt Arsenault770ec862016-12-22 03:55:35 +00008989 isFMAFasterThanFMulAndFAdd(VT)) {
8990 return ISD::FMA;
8991 }
8992
8993 return 0;
8994}
8995
Stanislav Mekhanoshin871821f2019-02-14 22:11:25 +00008996// For a reassociatable opcode perform:
8997// op x, (op y, z) -> op (op x, z), y, if x and z are uniform
8998SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
8999 SelectionDAG &DAG) const {
9000 EVT VT = N->getValueType(0);
9001 if (VT != MVT::i32 && VT != MVT::i64)
9002 return SDValue();
9003
9004 unsigned Opc = N->getOpcode();
9005 SDValue Op0 = N->getOperand(0);
9006 SDValue Op1 = N->getOperand(1);
9007
9008 if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9009 return SDValue();
9010
9011 if (Op0->isDivergent())
9012 std::swap(Op0, Op1);
9013
9014 if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9015 return SDValue();
9016
9017 SDValue Op2 = Op1.getOperand(1);
9018 Op1 = Op1.getOperand(0);
9019 if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9020 return SDValue();
9021
9022 if (Op1->isDivergent())
9023 std::swap(Op1, Op2);
9024
9025 // If either operand is constant this will conflict with
9026 // DAGCombiner::ReassociateOps().
Stanislav Mekhanoshinda1628e2019-02-26 20:56:25 +00009027 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9028 DAG.isConstantIntBuildVectorOrConstantInt(Op1))
Stanislav Mekhanoshin871821f2019-02-14 22:11:25 +00009029 return SDValue();
9030
9031 SDLoc SL(N);
9032 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9033 return DAG.getNode(Opc, SL, VT, Add1, Op2);
9034}
9035
Matt Arsenault4f6318f2017-11-06 17:04:37 +00009036static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9037 EVT VT,
9038 SDValue N0, SDValue N1, SDValue N2,
9039 bool Signed) {
9040 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9041 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9042 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9043 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9044}
9045
Stanislav Mekhanoshine3eb42c2017-06-21 22:05:06 +00009046SDValue SITargetLowering::performAddCombine(SDNode *N,
9047 DAGCombinerInfo &DCI) const {
9048 SelectionDAG &DAG = DCI.DAG;
9049 EVT VT = N->getValueType(0);
Stanislav Mekhanoshine3eb42c2017-06-21 22:05:06 +00009050 SDLoc SL(N);
9051 SDValue LHS = N->getOperand(0);
9052 SDValue RHS = N->getOperand(1);
9053
Matt Arsenault4f6318f2017-11-06 17:04:37 +00009054 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9055 && Subtarget->hasMad64_32() &&
9056 !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9057 VT.getScalarSizeInBits() <= 64) {
9058 if (LHS.getOpcode() != ISD::MUL)
9059 std::swap(LHS, RHS);
9060
9061 SDValue MulLHS = LHS.getOperand(0);
9062 SDValue MulRHS = LHS.getOperand(1);
9063 SDValue AddRHS = RHS;
9064
9065 // TODO: Maybe restrict if SGPR inputs.
9066 if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9067 numBitsUnsigned(MulRHS, DAG) <= 32) {
9068 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9069 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9070 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9071 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9072 }
9073
9074 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9075 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9076 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9077 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9078 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9079 }
9080
9081 return SDValue();
9082 }
9083
Stanislav Mekhanoshin871821f2019-02-14 22:11:25 +00009084 if (SDValue V = reassociateScalarOps(N, DAG)) {
9085 return V;
9086 }
9087
Farhana Aleen07e61232018-05-02 18:16:39 +00009088 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
Matt Arsenault4f6318f2017-11-06 17:04:37 +00009089 return SDValue();
9090
Stanislav Mekhanoshine3eb42c2017-06-21 22:05:06 +00009091 // add x, zext (setcc) => addcarry x, 0, setcc
9092 // add x, sext (setcc) => subcarry x, 0, setcc
9093 unsigned Opc = LHS.getOpcode();
9094 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
Stanislav Mekhanoshina8b26932017-06-21 22:30:01 +00009095 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
Stanislav Mekhanoshine3eb42c2017-06-21 22:05:06 +00009096 std::swap(RHS, LHS);
9097
9098 Opc = RHS.getOpcode();
Stanislav Mekhanoshina8b26932017-06-21 22:30:01 +00009099 switch (Opc) {
9100 default: break;
9101 case ISD::ZERO_EXTEND:
9102 case ISD::SIGN_EXTEND:
9103 case ISD::ANY_EXTEND: {
Stanislav Mekhanoshine3eb42c2017-06-21 22:05:06 +00009104 auto Cond = RHS.getOperand(0);
Stanislav Mekhanoshin6851ddf2017-06-27 18:25:26 +00009105 if (!isBoolSGPR(Cond))
Stanislav Mekhanoshin3ed38c62017-06-21 23:46:22 +00009106 break;
Stanislav Mekhanoshina8b26932017-06-21 22:30:01 +00009107 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9108 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9109 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9110 return DAG.getNode(Opc, SL, VTList, Args);
9111 }
9112 case ISD::ADDCARRY: {
9113 // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9114 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9115 if (!C || C->getZExtValue() != 0) break;
9116 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9117 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9118 }
9119 }
9120 return SDValue();
9121}
9122
9123SDValue SITargetLowering::performSubCombine(SDNode *N,
9124 DAGCombinerInfo &DCI) const {
9125 SelectionDAG &DAG = DCI.DAG;
9126 EVT VT = N->getValueType(0);
9127
9128 if (VT != MVT::i32)
9129 return SDValue();
9130
9131 SDLoc SL(N);
9132 SDValue LHS = N->getOperand(0);
9133 SDValue RHS = N->getOperand(1);
9134
Stanislav Mekhanoshina8b26932017-06-21 22:30:01 +00009135 if (LHS.getOpcode() == ISD::SUBCARRY) {
9136 // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9137 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
Stanislav Mekhanoshin42e229e2019-02-21 02:58:00 +00009138 if (!C || !C->isNullValue())
Stanislav Mekhanoshina8b26932017-06-21 22:30:01 +00009139 return SDValue();
9140 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9141 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9142 }
9143 return SDValue();
9144}
9145
9146SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9147 DAGCombinerInfo &DCI) const {
9148
9149 if (N->getValueType(0) != MVT::i32)
9150 return SDValue();
9151
9152 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9153 if (!C || C->getZExtValue() != 0)
9154 return SDValue();
9155
9156 SelectionDAG &DAG = DCI.DAG;
9157 SDValue LHS = N->getOperand(0);
9158
9159 // addcarry (add x, y), 0, cc => addcarry x, y, cc
9160 // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9161 unsigned LHSOpc = LHS.getOpcode();
9162 unsigned Opc = N->getOpcode();
9163 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9164 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9165 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9166 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
Stanislav Mekhanoshine3eb42c2017-06-21 22:05:06 +00009167 }
9168 return SDValue();
9169}
9170
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009171SDValue SITargetLowering::performFAddCombine(SDNode *N,
9172 DAGCombinerInfo &DCI) const {
9173 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9174 return SDValue();
9175
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009176 SelectionDAG &DAG = DCI.DAG;
Matt Arsenault770ec862016-12-22 03:55:35 +00009177 EVT VT = N->getValueType(0);
Matt Arsenault770ec862016-12-22 03:55:35 +00009178
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009179 SDLoc SL(N);
9180 SDValue LHS = N->getOperand(0);
9181 SDValue RHS = N->getOperand(1);
9182
9183 // These should really be instruction patterns, but writing patterns with
9184 // source modiifiers is a pain.
9185
9186 // fadd (fadd (a, a), b) -> mad 2.0, a, b
9187 if (LHS.getOpcode() == ISD::FADD) {
9188 SDValue A = LHS.getOperand(0);
9189 if (A == LHS.getOperand(1)) {
Matt Arsenault46e6b7a2016-12-22 04:03:35 +00009190 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
Matt Arsenault770ec862016-12-22 03:55:35 +00009191 if (FusedOp != 0) {
9192 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
Matt Arsenaulte7d8ed32016-12-22 04:03:40 +00009193 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
Matt Arsenault770ec862016-12-22 03:55:35 +00009194 }
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009195 }
9196 }
9197
9198 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9199 if (RHS.getOpcode() == ISD::FADD) {
9200 SDValue A = RHS.getOperand(0);
9201 if (A == RHS.getOperand(1)) {
Matt Arsenault46e6b7a2016-12-22 04:03:35 +00009202 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
Matt Arsenault770ec862016-12-22 03:55:35 +00009203 if (FusedOp != 0) {
9204 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
Matt Arsenaulte7d8ed32016-12-22 04:03:40 +00009205 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
Matt Arsenault770ec862016-12-22 03:55:35 +00009206 }
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009207 }
9208 }
9209
9210 return SDValue();
9211}
9212
9213SDValue SITargetLowering::performFSubCombine(SDNode *N,
9214 DAGCombinerInfo &DCI) const {
9215 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9216 return SDValue();
9217
9218 SelectionDAG &DAG = DCI.DAG;
9219 SDLoc SL(N);
9220 EVT VT = N->getValueType(0);
9221 assert(!VT.isVector());
9222
9223 // Try to get the fneg to fold into the source modifier. This undoes generic
9224 // DAG combines and folds them into the mad.
9225 //
9226 // Only do this if we are not trying to support denormals. v_mad_f32 does
9227 // not support denormals ever.
Matt Arsenault770ec862016-12-22 03:55:35 +00009228 SDValue LHS = N->getOperand(0);
9229 SDValue RHS = N->getOperand(1);
9230 if (LHS.getOpcode() == ISD::FADD) {
9231 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9232 SDValue A = LHS.getOperand(0);
9233 if (A == LHS.getOperand(1)) {
Matt Arsenault46e6b7a2016-12-22 04:03:35 +00009234 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
Matt Arsenault770ec862016-12-22 03:55:35 +00009235 if (FusedOp != 0){
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009236 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9237 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9238
Matt Arsenaulte7d8ed32016-12-22 04:03:40 +00009239 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009240 }
9241 }
Matt Arsenault770ec862016-12-22 03:55:35 +00009242 }
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009243
Matt Arsenault770ec862016-12-22 03:55:35 +00009244 if (RHS.getOpcode() == ISD::FADD) {
9245 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009246
Matt Arsenault770ec862016-12-22 03:55:35 +00009247 SDValue A = RHS.getOperand(0);
9248 if (A == RHS.getOperand(1)) {
Matt Arsenault46e6b7a2016-12-22 04:03:35 +00009249 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
Matt Arsenault770ec862016-12-22 03:55:35 +00009250 if (FusedOp != 0){
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009251 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
Matt Arsenaulte7d8ed32016-12-22 04:03:40 +00009252 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009253 }
9254 }
9255 }
9256
9257 return SDValue();
9258}
9259
Farhana Aleenc370d7b2018-07-16 18:19:59 +00009260SDValue SITargetLowering::performFMACombine(SDNode *N,
9261 DAGCombinerInfo &DCI) const {
9262 SelectionDAG &DAG = DCI.DAG;
9263 EVT VT = N->getValueType(0);
9264 SDLoc SL(N);
9265
Stanislav Mekhanoshin0e858b02019-02-09 00:34:21 +00009266 if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
Farhana Aleenc370d7b2018-07-16 18:19:59 +00009267 return SDValue();
9268
9269 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9270 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9271 SDValue Op1 = N->getOperand(0);
9272 SDValue Op2 = N->getOperand(1);
9273 SDValue FMA = N->getOperand(2);
9274
9275 if (FMA.getOpcode() != ISD::FMA ||
9276 Op1.getOpcode() != ISD::FP_EXTEND ||
9277 Op2.getOpcode() != ISD::FP_EXTEND)
9278 return SDValue();
9279
9280 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9281 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9282 // is sufficient to allow generaing fdot2.
9283 const TargetOptions &Options = DAG.getTarget().Options;
9284 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9285 (N->getFlags().hasAllowContract() &&
9286 FMA->getFlags().hasAllowContract())) {
9287 Op1 = Op1.getOperand(0);
9288 Op2 = Op2.getOperand(0);
9289 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9290 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9291 return SDValue();
9292
9293 SDValue Vec1 = Op1.getOperand(0);
9294 SDValue Idx1 = Op1.getOperand(1);
9295 SDValue Vec2 = Op2.getOperand(0);
9296
9297 SDValue FMAOp1 = FMA.getOperand(0);
9298 SDValue FMAOp2 = FMA.getOperand(1);
9299 SDValue FMAAcc = FMA.getOperand(2);
9300
9301 if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9302 FMAOp2.getOpcode() != ISD::FP_EXTEND)
9303 return SDValue();
9304
9305 FMAOp1 = FMAOp1.getOperand(0);
9306 FMAOp2 = FMAOp2.getOperand(0);
9307 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9308 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9309 return SDValue();
9310
9311 SDValue Vec3 = FMAOp1.getOperand(0);
9312 SDValue Vec4 = FMAOp2.getOperand(0);
9313 SDValue Idx2 = FMAOp1.getOperand(1);
9314
9315 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9316 // Idx1 and Idx2 cannot be the same.
9317 Idx1 == Idx2)
9318 return SDValue();
9319
9320 if (Vec1 == Vec2 || Vec3 == Vec4)
9321 return SDValue();
9322
9323 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9324 return SDValue();
9325
9326 if ((Vec1 == Vec3 && Vec2 == Vec4) ||
Konstantin Zhuravlyovbb30ef72018-08-01 01:31:30 +00009327 (Vec1 == Vec4 && Vec2 == Vec3)) {
9328 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9329 DAG.getTargetConstant(0, SL, MVT::i1));
9330 }
Farhana Aleenc370d7b2018-07-16 18:19:59 +00009331 }
9332 return SDValue();
9333}
9334
Matt Arsenault6f6233d2015-01-06 23:00:41 +00009335SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9336 DAGCombinerInfo &DCI) const {
9337 SelectionDAG &DAG = DCI.DAG;
9338 SDLoc SL(N);
9339
9340 SDValue LHS = N->getOperand(0);
9341 SDValue RHS = N->getOperand(1);
9342 EVT VT = LHS.getValueType();
Stanislav Mekhanoshinc9bd53a2017-06-27 18:53:03 +00009343 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9344
9345 auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9346 if (!CRHS) {
9347 CRHS = dyn_cast<ConstantSDNode>(LHS);
9348 if (CRHS) {
9349 std::swap(LHS, RHS);
9350 CC = getSetCCSwappedOperands(CC);
9351 }
9352 }
9353
Stanislav Mekhanoshin3b117942018-06-16 03:46:59 +00009354 if (CRHS) {
9355 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9356 isBoolSGPR(LHS.getOperand(0))) {
9357 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9358 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9359 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
9360 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
9361 if ((CRHS->isAllOnesValue() &&
9362 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9363 (CRHS->isNullValue() &&
9364 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9365 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9366 DAG.getConstant(-1, SL, MVT::i1));
9367 if ((CRHS->isAllOnesValue() &&
9368 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9369 (CRHS->isNullValue() &&
9370 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9371 return LHS.getOperand(0);
9372 }
9373
9374 uint64_t CRHSVal = CRHS->getZExtValue();
9375 if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9376 LHS.getOpcode() == ISD::SELECT &&
9377 isa<ConstantSDNode>(LHS.getOperand(1)) &&
9378 isa<ConstantSDNode>(LHS.getOperand(2)) &&
9379 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9380 isBoolSGPR(LHS.getOperand(0))) {
9381 // Given CT != FT:
9382 // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9383 // setcc (select cc, CT, CF), CF, ne => cc
9384 // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9385 // setcc (select cc, CT, CF), CT, eq => cc
9386 uint64_t CT = LHS.getConstantOperandVal(1);
9387 uint64_t CF = LHS.getConstantOperandVal(2);
9388
9389 if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9390 (CT == CRHSVal && CC == ISD::SETNE))
9391 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9392 DAG.getConstant(-1, SL, MVT::i1));
9393 if ((CF == CRHSVal && CC == ISD::SETNE) ||
9394 (CT == CRHSVal && CC == ISD::SETEQ))
9395 return LHS.getOperand(0);
9396 }
Stanislav Mekhanoshinc9bd53a2017-06-27 18:53:03 +00009397 }
Matt Arsenault6f6233d2015-01-06 23:00:41 +00009398
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +00009399 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9400 VT != MVT::f16))
Matt Arsenault6f6233d2015-01-06 23:00:41 +00009401 return SDValue();
9402
Matt Arsenault8ad00d32018-08-10 18:58:41 +00009403 // Match isinf/isfinite pattern
Matt Arsenault6f6233d2015-01-06 23:00:41 +00009404 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
Matt Arsenault8ad00d32018-08-10 18:58:41 +00009405 // (fcmp one (fabs x), inf) -> (fp_class x,
9406 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9407 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
Matt Arsenault6f6233d2015-01-06 23:00:41 +00009408 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9409 if (!CRHS)
9410 return SDValue();
9411
9412 const APFloat &APF = CRHS->getValueAPF();
9413 if (APF.isInfinity() && !APF.isNegative()) {
Matt Arsenault8ad00d32018-08-10 18:58:41 +00009414 const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9415 SIInstrFlags::N_INFINITY;
9416 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9417 SIInstrFlags::P_ZERO |
9418 SIInstrFlags::N_NORMAL |
9419 SIInstrFlags::P_NORMAL |
9420 SIInstrFlags::N_SUBNORMAL |
9421 SIInstrFlags::P_SUBNORMAL;
9422 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009423 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9424 DAG.getConstant(Mask, SL, MVT::i32));
Matt Arsenault6f6233d2015-01-06 23:00:41 +00009425 }
9426 }
9427
9428 return SDValue();
9429}
9430
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009431SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9432 DAGCombinerInfo &DCI) const {
9433 SelectionDAG &DAG = DCI.DAG;
9434 SDLoc SL(N);
9435 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9436
9437 SDValue Src = N->getOperand(0);
9438 SDValue Srl = N->getOperand(0);
9439 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
9440 Srl = Srl.getOperand(0);
9441
9442 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
9443 if (Srl.getOpcode() == ISD::SRL) {
9444 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9445 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9446 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
9447
9448 if (const ConstantSDNode *C =
9449 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
9450 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
9451 EVT(MVT::i32));
9452
9453 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
9454 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
9455 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
9456 MVT::f32, Srl);
9457 }
9458 }
9459 }
9460
9461 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9462
Craig Topperd0af7e82017-04-28 05:31:46 +00009463 KnownBits Known;
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009464 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9465 !DCI.isBeforeLegalizeOps());
9466 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Stanislav Mekhanoshined0d6c62019-01-09 02:24:22 +00009467 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009468 DCI.CommitTargetLoweringOpt(TLO);
9469 }
9470
9471 return SDValue();
9472}
9473
Tom Stellard1b95fed2018-05-24 05:28:34 +00009474SDValue SITargetLowering::performClampCombine(SDNode *N,
9475 DAGCombinerInfo &DCI) const {
9476 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9477 if (!CSrc)
9478 return SDValue();
9479
Matt Arsenault055e4dc2019-03-29 19:14:54 +00009480 const MachineFunction &MF = DCI.DAG.getMachineFunction();
Tom Stellard1b95fed2018-05-24 05:28:34 +00009481 const APFloat &F = CSrc->getValueAPF();
9482 APFloat Zero = APFloat::getZero(F.getSemantics());
9483 APFloat::cmpResult Cmp0 = F.compare(Zero);
9484 if (Cmp0 == APFloat::cmpLessThan ||
Matt Arsenault055e4dc2019-03-29 19:14:54 +00009485 (Cmp0 == APFloat::cmpUnordered &&
9486 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
Tom Stellard1b95fed2018-05-24 05:28:34 +00009487 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9488 }
9489
9490 APFloat One(F.getSemantics(), "1.0");
9491 APFloat::cmpResult Cmp1 = F.compare(One);
9492 if (Cmp1 == APFloat::cmpGreaterThan)
9493 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9494
9495 return SDValue(CSrc, 0);
9496}
9497
9498
Tom Stellard75aadc22012-12-11 21:25:42 +00009499SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9500 DAGCombinerInfo &DCI) const {
Stanislav Mekhanoshin443a7f92018-11-27 15:13:37 +00009501 if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9502 return SDValue();
Tom Stellard75aadc22012-12-11 21:25:42 +00009503 switch (N->getOpcode()) {
Matt Arsenault22b4c252014-12-21 16:48:42 +00009504 default:
9505 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
Stanislav Mekhanoshine3eb42c2017-06-21 22:05:06 +00009506 case ISD::ADD:
9507 return performAddCombine(N, DCI);
Stanislav Mekhanoshina8b26932017-06-21 22:30:01 +00009508 case ISD::SUB:
9509 return performSubCombine(N, DCI);
9510 case ISD::ADDCARRY:
9511 case ISD::SUBCARRY:
9512 return performAddCarrySubCarryCombine(N, DCI);
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009513 case ISD::FADD:
9514 return performFAddCombine(N, DCI);
9515 case ISD::FSUB:
9516 return performFSubCombine(N, DCI);
Matt Arsenault6f6233d2015-01-06 23:00:41 +00009517 case ISD::SETCC:
9518 return performSetCCCombine(N, DCI);
Matt Arsenault5b39b342016-01-28 20:53:48 +00009519 case ISD::FMAXNUM:
Matt Arsenaultcc3c2b32014-11-14 20:08:52 +00009520 case ISD::FMINNUM:
Matt Arsenault687ec752018-10-22 16:27:27 +00009521 case ISD::FMAXNUM_IEEE:
9522 case ISD::FMINNUM_IEEE:
Matt Arsenault5881f4e2015-06-09 00:52:37 +00009523 case ISD::SMAX:
9524 case ISD::SMIN:
9525 case ISD::UMAX:
Matt Arsenault5b39b342016-01-28 20:53:48 +00009526 case ISD::UMIN:
9527 case AMDGPUISD::FMIN_LEGACY:
Stanislav Mekhanoshin443a7f92018-11-27 15:13:37 +00009528 case AMDGPUISD::FMAX_LEGACY:
9529 return performMinMaxCombine(N, DCI);
Farhana Aleenc370d7b2018-07-16 18:19:59 +00009530 case ISD::FMA:
9531 return performFMACombine(N, DCI);
Matt Arsenault90083d32018-06-07 09:54:49 +00009532 case ISD::LOAD: {
9533 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
9534 return Widended;
9535 LLVM_FALLTHROUGH;
9536 }
Matt Arsenaultb2baffa2014-08-15 17:49:05 +00009537 case ISD::STORE:
9538 case ISD::ATOMIC_LOAD:
9539 case ISD::ATOMIC_STORE:
9540 case ISD::ATOMIC_CMP_SWAP:
9541 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
9542 case ISD::ATOMIC_SWAP:
9543 case ISD::ATOMIC_LOAD_ADD:
9544 case ISD::ATOMIC_LOAD_SUB:
9545 case ISD::ATOMIC_LOAD_AND:
9546 case ISD::ATOMIC_LOAD_OR:
9547 case ISD::ATOMIC_LOAD_XOR:
9548 case ISD::ATOMIC_LOAD_NAND:
9549 case ISD::ATOMIC_LOAD_MIN:
9550 case ISD::ATOMIC_LOAD_MAX:
9551 case ISD::ATOMIC_LOAD_UMIN:
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +00009552 case ISD::ATOMIC_LOAD_UMAX:
Matt Arsenaulta5840c32019-01-22 18:36:06 +00009553 case ISD::ATOMIC_LOAD_FADD:
Matt Arsenaulta9dbdca2016-04-12 14:05:04 +00009554 case AMDGPUISD::ATOMIC_INC:
Daniil Fukalovd5fca552018-01-17 14:05:05 +00009555 case AMDGPUISD::ATOMIC_DEC:
Daniil Fukalovd5fca552018-01-17 14:05:05 +00009556 case AMDGPUISD::ATOMIC_LOAD_FMIN:
Matt Arsenaulta5840c32019-01-22 18:36:06 +00009557 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
Matt Arsenaultb2baffa2014-08-15 17:49:05 +00009558 if (DCI.isBeforeLegalize())
9559 break;
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009560 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
Matt Arsenaultd0101a22015-01-06 23:00:46 +00009561 case ISD::AND:
9562 return performAndCombine(N, DCI);
Matt Arsenaultf2290332015-01-06 23:00:39 +00009563 case ISD::OR:
9564 return performOrCombine(N, DCI);
Matt Arsenaultfa5f7672016-09-14 15:19:03 +00009565 case ISD::XOR:
9566 return performXorCombine(N, DCI);
Matt Arsenault8edfaee2017-03-31 19:53:03 +00009567 case ISD::ZERO_EXTEND:
9568 return performZeroExtendCombine(N, DCI);
Ryan Taylor00e063a2019-03-19 16:07:00 +00009569 case ISD::SIGN_EXTEND_INREG:
9570 return performSignExtendInRegCombine(N , DCI);
Matt Arsenaultf2290332015-01-06 23:00:39 +00009571 case AMDGPUISD::FP_CLASS:
9572 return performClassCombine(N, DCI);
Matt Arsenault9cd90712016-04-14 01:42:16 +00009573 case ISD::FCANONICALIZE:
9574 return performFCanonicalizeCombine(N, DCI);
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00009575 case AMDGPUISD::RCP:
Stanislav Mekhanoshin1a1687f2018-06-27 15:33:33 +00009576 return performRcpCombine(N, DCI);
9577 case AMDGPUISD::FRACT:
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00009578 case AMDGPUISD::RSQ:
Matt Arsenault32fc5272016-07-26 16:45:45 +00009579 case AMDGPUISD::RCP_LEGACY:
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00009580 case AMDGPUISD::RSQ_LEGACY:
Stanislav Mekhanoshin1a1687f2018-06-27 15:33:33 +00009581 case AMDGPUISD::RCP_IFLAG:
Matt Arsenaultb6d8c372016-06-20 18:33:56 +00009582 case AMDGPUISD::RSQ_CLAMP:
9583 case AMDGPUISD::LDEXP: {
9584 SDValue Src = N->getOperand(0);
9585 if (Src.isUndef())
9586 return Src;
9587 break;
9588 }
Matt Arsenaultd8b73d52016-12-22 03:44:42 +00009589 case ISD::SINT_TO_FP:
9590 case ISD::UINT_TO_FP:
9591 return performUCharToFloatCombine(N, DCI);
9592 case AMDGPUISD::CVT_F32_UBYTE0:
9593 case AMDGPUISD::CVT_F32_UBYTE1:
9594 case AMDGPUISD::CVT_F32_UBYTE2:
9595 case AMDGPUISD::CVT_F32_UBYTE3:
9596 return performCvtF32UByteNCombine(N, DCI);
Matt Arsenault2fdf2a12017-02-21 23:35:48 +00009597 case AMDGPUISD::FMED3:
9598 return performFMed3Combine(N, DCI);
Matt Arsenault1f17c662017-02-22 00:27:34 +00009599 case AMDGPUISD::CVT_PKRTZ_F16_F32:
9600 return performCvtPkRTZCombine(N, DCI);
Tom Stellard1b95fed2018-05-24 05:28:34 +00009601 case AMDGPUISD::CLAMP:
9602 return performClampCombine(N, DCI);
Matt Arsenaulteb522e62017-02-27 22:15:25 +00009603 case ISD::SCALAR_TO_VECTOR: {
9604 SelectionDAG &DAG = DCI.DAG;
9605 EVT VT = N->getValueType(0);
9606
9607 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
9608 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
9609 SDLoc SL(N);
9610 SDValue Src = N->getOperand(0);
9611 EVT EltVT = Src.getValueType();
9612 if (EltVT == MVT::f16)
9613 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
9614
9615 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
9616 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
9617 }
9618
9619 break;
9620 }
Matt Arsenaultbf5482e2017-05-11 17:26:25 +00009621 case ISD::EXTRACT_VECTOR_ELT:
9622 return performExtractVectorEltCombine(N, DCI);
Stanislav Mekhanoshin054f8102018-11-19 17:39:20 +00009623 case ISD::INSERT_VECTOR_ELT:
9624 return performInsertVectorEltCombine(N, DCI);
Matt Arsenaultb2baffa2014-08-15 17:49:05 +00009625 }
Matt Arsenault5565f65e2014-05-22 18:09:07 +00009626 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
Tom Stellard75aadc22012-12-11 21:25:42 +00009627}
Christian Konigd910b7d2013-02-26 17:52:16 +00009628
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009629/// Helper function for adjustWritemask
Benjamin Kramer635e3682013-05-23 15:43:05 +00009630static unsigned SubIdx2Lane(unsigned Idx) {
Christian Konig8e06e2a2013-04-10 08:39:08 +00009631 switch (Idx) {
9632 default: return 0;
9633 case AMDGPU::sub0: return 0;
9634 case AMDGPU::sub1: return 1;
9635 case AMDGPU::sub2: return 2;
9636 case AMDGPU::sub3: return 3;
David Stuttardf77079f2019-01-14 11:55:24 +00009637 case AMDGPU::sub4: return 4; // Possible with TFE/LWE
Christian Konig8e06e2a2013-04-10 08:39:08 +00009638 }
9639}
9640
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009641/// Adjust the writemask of MIMG instructions
Matt Arsenault68f05052017-12-04 22:18:27 +00009642SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
9643 SelectionDAG &DAG) const {
Nicolai Haehnlef2674312018-06-21 13:36:01 +00009644 unsigned Opcode = Node->getMachineOpcode();
9645
9646 // Subtract 1 because the vdata output is not a MachineSDNode operand.
9647 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
9648 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
9649 return Node; // not implemented for D16
9650
David Stuttardf77079f2019-01-14 11:55:24 +00009651 SDNode *Users[5] = { nullptr };
Tom Stellard54774e52013-10-23 02:53:47 +00009652 unsigned Lane = 0;
Nicolai Haehnlef2674312018-06-21 13:36:01 +00009653 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
Nikolay Haustov2f684f12016-02-26 09:51:05 +00009654 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
Tom Stellard54774e52013-10-23 02:53:47 +00009655 unsigned NewDmask = 0;
David Stuttardf77079f2019-01-14 11:55:24 +00009656 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
9657 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
9658 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
9659 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
9660 unsigned TFCLane = 0;
Matt Arsenault856777d2017-12-08 20:00:57 +00009661 bool HasChain = Node->getNumValues() > 1;
9662
9663 if (OldDmask == 0) {
9664 // These are folded out, but on the chance it happens don't assert.
9665 return Node;
9666 }
Christian Konig8e06e2a2013-04-10 08:39:08 +00009667
David Stuttardf77079f2019-01-14 11:55:24 +00009668 unsigned OldBitsSet = countPopulation(OldDmask);
9669 // Work out which is the TFE/LWE lane if that is enabled.
9670 if (UsesTFC) {
9671 TFCLane = OldBitsSet;
9672 }
9673
Christian Konig8e06e2a2013-04-10 08:39:08 +00009674 // Try to figure out the used register components
9675 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
9676 I != E; ++I) {
9677
Matt Arsenault93e65ea2017-02-22 21:16:41 +00009678 // Don't look at users of the chain.
9679 if (I.getUse().getResNo() != 0)
9680 continue;
9681
Christian Konig8e06e2a2013-04-10 08:39:08 +00009682 // Abort if we can't understand the usage
9683 if (!I->isMachineOpcode() ||
9684 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
Matt Arsenault68f05052017-12-04 22:18:27 +00009685 return Node;
Christian Konig8e06e2a2013-04-10 08:39:08 +00009686
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +00009687 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
Tom Stellard54774e52013-10-23 02:53:47 +00009688 // Note that subregs are packed, i.e. Lane==0 is the first bit set
9689 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
9690 // set, etc.
Christian Konig8b1ed282013-04-10 08:39:16 +00009691 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
Christian Konig8e06e2a2013-04-10 08:39:08 +00009692
David Stuttardf77079f2019-01-14 11:55:24 +00009693 // Check if the use is for the TFE/LWE generated result at VGPRn+1.
9694 if (UsesTFC && Lane == TFCLane) {
9695 Users[Lane] = *I;
9696 } else {
9697 // Set which texture component corresponds to the lane.
9698 unsigned Comp;
9699 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
9700 Comp = countTrailingZeros(Dmask);
9701 Dmask &= ~(1 << Comp);
9702 }
9703
9704 // Abort if we have more than one user per component.
9705 if (Users[Lane])
9706 return Node;
9707
9708 Users[Lane] = *I;
9709 NewDmask |= 1 << Comp;
Tom Stellard54774e52013-10-23 02:53:47 +00009710 }
Christian Konig8e06e2a2013-04-10 08:39:08 +00009711 }
9712
David Stuttardf77079f2019-01-14 11:55:24 +00009713 // Don't allow 0 dmask, as hardware assumes one channel enabled.
9714 bool NoChannels = !NewDmask;
9715 if (NoChannels) {
David Stuttardfc2a7472019-03-20 09:29:55 +00009716 if (!UsesTFC) {
9717 // No uses of the result and not using TFC. Then do nothing.
9718 return Node;
9719 }
David Stuttardf77079f2019-01-14 11:55:24 +00009720 // If the original dmask has one channel - then nothing to do
9721 if (OldBitsSet == 1)
9722 return Node;
9723 // Use an arbitrary dmask - required for the instruction to work
9724 NewDmask = 1;
9725 }
Tom Stellard54774e52013-10-23 02:53:47 +00009726 // Abort if there's no change
9727 if (NewDmask == OldDmask)
Matt Arsenault68f05052017-12-04 22:18:27 +00009728 return Node;
9729
9730 unsigned BitsSet = countPopulation(NewDmask);
9731
David Stuttardf77079f2019-01-14 11:55:24 +00009732 // Check for TFE or LWE - increase the number of channels by one to account
9733 // for the extra return value
9734 // This will need adjustment for D16 if this is also included in
9735 // adjustWriteMask (this function) but at present D16 are excluded.
9736 unsigned NewChannels = BitsSet + UsesTFC;
9737
9738 int NewOpcode =
9739 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
Matt Arsenault68f05052017-12-04 22:18:27 +00009740 assert(NewOpcode != -1 &&
9741 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
9742 "failed to find equivalent MIMG op");
Christian Konig8e06e2a2013-04-10 08:39:08 +00009743
9744 // Adjust the writemask in the node
Matt Arsenault68f05052017-12-04 22:18:27 +00009745 SmallVector<SDValue, 12> Ops;
Nikolay Haustov2f684f12016-02-26 09:51:05 +00009746 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009747 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
Nikolay Haustov2f684f12016-02-26 09:51:05 +00009748 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
Christian Konig8e06e2a2013-04-10 08:39:08 +00009749
Matt Arsenault68f05052017-12-04 22:18:27 +00009750 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
9751
David Stuttardf77079f2019-01-14 11:55:24 +00009752 MVT ResultVT = NewChannels == 1 ?
9753 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
9754 NewChannels == 5 ? 8 : NewChannels);
Matt Arsenault856777d2017-12-08 20:00:57 +00009755 SDVTList NewVTList = HasChain ?
9756 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
9757
Matt Arsenault68f05052017-12-04 22:18:27 +00009758
9759 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
9760 NewVTList, Ops);
Matt Arsenaultecad0d532017-12-08 20:00:45 +00009761
Matt Arsenault856777d2017-12-08 20:00:57 +00009762 if (HasChain) {
9763 // Update chain.
Chandler Carruth66654b72018-08-14 23:30:32 +00009764 DAG.setNodeMemRefs(NewNode, Node->memoperands());
Matt Arsenault856777d2017-12-08 20:00:57 +00009765 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
9766 }
Matt Arsenault68f05052017-12-04 22:18:27 +00009767
David Stuttardf77079f2019-01-14 11:55:24 +00009768 if (NewChannels == 1) {
Matt Arsenault68f05052017-12-04 22:18:27 +00009769 assert(Node->hasNUsesOfValue(1, 0));
9770 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
9771 SDLoc(Node), Users[Lane]->getValueType(0),
9772 SDValue(NewNode, 0));
Christian Konig8b1ed282013-04-10 08:39:16 +00009773 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
Matt Arsenault68f05052017-12-04 22:18:27 +00009774 return nullptr;
Christian Konig8b1ed282013-04-10 08:39:16 +00009775 }
9776
Christian Konig8e06e2a2013-04-10 08:39:08 +00009777 // Update the users of the node with the new indices
David Stuttardf77079f2019-01-14 11:55:24 +00009778 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
Christian Konig8e06e2a2013-04-10 08:39:08 +00009779 SDNode *User = Users[i];
David Stuttardf77079f2019-01-14 11:55:24 +00009780 if (!User) {
9781 // Handle the special case of NoChannels. We set NewDmask to 1 above, but
9782 // Users[0] is still nullptr because channel 0 doesn't really have a use.
9783 if (i || !NoChannels)
9784 continue;
9785 } else {
9786 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
9787 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
9788 }
Christian Konig8e06e2a2013-04-10 08:39:08 +00009789
9790 switch (Idx) {
9791 default: break;
9792 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
9793 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
9794 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
David Stuttardf77079f2019-01-14 11:55:24 +00009795 case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
Christian Konig8e06e2a2013-04-10 08:39:08 +00009796 }
9797 }
Matt Arsenault68f05052017-12-04 22:18:27 +00009798
9799 DAG.RemoveDeadNode(Node);
9800 return nullptr;
Christian Konig8e06e2a2013-04-10 08:39:08 +00009801}
9802
Tom Stellardc98ee202015-07-16 19:40:07 +00009803static bool isFrameIndexOp(SDValue Op) {
9804 if (Op.getOpcode() == ISD::AssertZext)
9805 Op = Op.getOperand(0);
9806
9807 return isa<FrameIndexSDNode>(Op);
9808}
9809
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009810/// Legalize target independent instructions (e.g. INSERT_SUBREG)
Tom Stellard3457a842014-10-09 19:06:00 +00009811/// with frame index operands.
9812/// LLVM assumes that inputs are to these instructions are registers.
Matt Arsenault0d0d6c22017-04-12 21:58:23 +00009813SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
9814 SelectionDAG &DAG) const {
9815 if (Node->getOpcode() == ISD::CopyToReg) {
9816 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
9817 SDValue SrcVal = Node->getOperand(2);
9818
9819 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
9820 // to try understanding copies to physical registers.
9821 if (SrcVal.getValueType() == MVT::i1 &&
9822 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
9823 SDLoc SL(Node);
9824 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
9825 SDValue VReg = DAG.getRegister(
9826 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
9827
9828 SDNode *Glued = Node->getGluedNode();
9829 SDValue ToVReg
9830 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
9831 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
9832 SDValue ToResultReg
9833 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
9834 VReg, ToVReg.getValue(1));
9835 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
9836 DAG.RemoveDeadNode(Node);
9837 return ToResultReg.getNode();
9838 }
9839 }
Tom Stellard8dd392e2014-10-09 18:09:15 +00009840
9841 SmallVector<SDValue, 8> Ops;
Tom Stellard3457a842014-10-09 19:06:00 +00009842 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
Tom Stellardc98ee202015-07-16 19:40:07 +00009843 if (!isFrameIndexOp(Node->getOperand(i))) {
Tom Stellard3457a842014-10-09 19:06:00 +00009844 Ops.push_back(Node->getOperand(i));
Tom Stellard8dd392e2014-10-09 18:09:15 +00009845 continue;
9846 }
9847
Tom Stellard3457a842014-10-09 19:06:00 +00009848 SDLoc DL(Node);
Tom Stellard8dd392e2014-10-09 18:09:15 +00009849 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
Tom Stellard3457a842014-10-09 19:06:00 +00009850 Node->getOperand(i).getValueType(),
9851 Node->getOperand(i)), 0));
Tom Stellard8dd392e2014-10-09 18:09:15 +00009852 }
9853
Mark Searles4e3d6162017-10-16 23:38:53 +00009854 return DAG.UpdateNodeOperands(Node, Ops);
Tom Stellard8dd392e2014-10-09 18:09:15 +00009855}
9856
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009857/// Fold the instructions after selecting them.
Matt Arsenault68f05052017-12-04 22:18:27 +00009858/// Returns null if users were already updated.
Christian Konig8e06e2a2013-04-10 08:39:08 +00009859SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
9860 SelectionDAG &DAG) const {
Matt Arsenault43e92fe2016-06-24 06:30:11 +00009861 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
Nicolai Haehnlef2c64db2016-02-18 16:44:18 +00009862 unsigned Opcode = Node->getMachineOpcode();
Christian Konig8e06e2a2013-04-10 08:39:08 +00009863
Nicolai Haehnlec06bfa12016-07-11 21:59:43 +00009864 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
Nicolai Haehnlef2674312018-06-21 13:36:01 +00009865 !TII->isGather4(Opcode)) {
Matt Arsenault68f05052017-12-04 22:18:27 +00009866 return adjustWritemask(Node, DAG);
9867 }
Christian Konig8e06e2a2013-04-10 08:39:08 +00009868
Nicolai Haehnlef2c64db2016-02-18 16:44:18 +00009869 if (Opcode == AMDGPU::INSERT_SUBREG ||
9870 Opcode == AMDGPU::REG_SEQUENCE) {
Tom Stellard8dd392e2014-10-09 18:09:15 +00009871 legalizeTargetIndependentNode(Node, DAG);
9872 return Node;
9873 }
Matt Arsenault206f8262017-08-01 20:49:41 +00009874
9875 switch (Opcode) {
9876 case AMDGPU::V_DIV_SCALE_F32:
9877 case AMDGPU::V_DIV_SCALE_F64: {
9878 // Satisfy the operand register constraint when one of the inputs is
9879 // undefined. Ordinarily each undef value will have its own implicit_def of
9880 // a vreg, so force these to use a single register.
9881 SDValue Src0 = Node->getOperand(0);
9882 SDValue Src1 = Node->getOperand(1);
9883 SDValue Src2 = Node->getOperand(2);
9884
9885 if ((Src0.isMachineOpcode() &&
9886 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
9887 (Src0 == Src1 || Src0 == Src2))
9888 break;
9889
9890 MVT VT = Src0.getValueType().getSimpleVT();
Alexander Timofeevba447ba2019-05-26 20:33:26 +00009891 const TargetRegisterClass *RC =
9892 getRegClassFor(VT, Src0.getNode()->isDivergent());
Matt Arsenault206f8262017-08-01 20:49:41 +00009893
9894 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
9895 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
9896
9897 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
9898 UndefReg, Src0, SDValue());
9899
9900 // src0 must be the same register as src1 or src2, even if the value is
9901 // undefined, so make sure we don't violate this constraint.
9902 if (Src0.isMachineOpcode() &&
9903 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
9904 if (Src1.isMachineOpcode() &&
9905 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
9906 Src0 = Src1;
9907 else if (Src2.isMachineOpcode() &&
9908 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
9909 Src0 = Src2;
9910 else {
9911 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
9912 Src0 = UndefReg;
9913 Src1 = UndefReg;
9914 }
9915 } else
9916 break;
9917
9918 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
9919 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
9920 Ops.push_back(Node->getOperand(I));
9921
9922 Ops.push_back(ImpDef.getValue(1));
9923 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
9924 }
Stanislav Mekhanoshin5f581c92019-06-12 17:52:51 +00009925 case AMDGPU::V_PERMLANE16_B32:
9926 case AMDGPU::V_PERMLANEX16_B32: {
9927 ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0));
9928 ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2));
9929 if (!FI->getZExtValue() && !BC->getZExtValue())
9930 break;
9931 SDValue VDstIn = Node->getOperand(6);
9932 if (VDstIn.isMachineOpcode()
9933 && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF)
9934 break;
9935 MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
9936 SDLoc(Node), MVT::i32);
9937 SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1),
9938 SDValue(BC, 0), Node->getOperand(3),
9939 Node->getOperand(4), Node->getOperand(5),
9940 SDValue(ImpDef, 0), Node->getOperand(7) };
9941 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
9942 }
Matt Arsenault206f8262017-08-01 20:49:41 +00009943 default:
9944 break;
9945 }
9946
Tom Stellard654d6692015-01-08 15:08:17 +00009947 return Node;
Christian Konig8e06e2a2013-04-10 08:39:08 +00009948}
Christian Konig8b1ed282013-04-10 08:39:16 +00009949
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009950/// Assign the register class depending on the number of
Christian Konig8b1ed282013-04-10 08:39:16 +00009951/// bits set in the writemask
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00009952void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
Christian Konig8b1ed282013-04-10 08:39:16 +00009953 SDNode *Node) const {
Matt Arsenault43e92fe2016-06-24 06:30:11 +00009954 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
Matt Arsenault7ac9c4a2014-09-08 15:07:31 +00009955
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00009956 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
Matt Arsenault6005fcb2015-10-21 21:51:02 +00009957
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00009958 if (TII->isVOP3(MI.getOpcode())) {
Matt Arsenault6005fcb2015-10-21 21:51:02 +00009959 // Make sure constant bus requirements are respected.
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00009960 TII->legalizeOperandsVOP3(MRI, MI);
Matt Arsenault6005fcb2015-10-21 21:51:02 +00009961 return;
9962 }
Matt Arsenaultcb0ac3d2014-09-26 17:54:59 +00009963
Matt Arsenault7ac9c4a2014-09-08 15:07:31 +00009964 // Replace unused atomics with the no return version.
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00009965 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
Matt Arsenault7ac9c4a2014-09-08 15:07:31 +00009966 if (NoRetAtomicOp != -1) {
9967 if (!Node->hasAnyUseOfValue(0)) {
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00009968 MI.setDesc(TII->get(NoRetAtomicOp));
9969 MI.RemoveOperand(0);
Tom Stellard354a43c2016-04-01 18:27:37 +00009970 return;
Matt Arsenault7ac9c4a2014-09-08 15:07:31 +00009971 }
9972
Tom Stellard354a43c2016-04-01 18:27:37 +00009973 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
9974 // instruction, because the return type of these instructions is a vec2 of
9975 // the memory type, so it can be tied to the input operand.
9976 // This means these instructions always have a use, so we need to add a
9977 // special case to check if the atomic has only one extract_subreg use,
9978 // which itself has no uses.
9979 if ((Node->hasNUsesOfValue(1, 0) &&
Nicolai Haehnle750082d2016-04-15 14:42:36 +00009980 Node->use_begin()->isMachineOpcode() &&
Tom Stellard354a43c2016-04-01 18:27:37 +00009981 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
9982 !Node->use_begin()->hasAnyUseOfValue(0))) {
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00009983 unsigned Def = MI.getOperand(0).getReg();
Tom Stellard354a43c2016-04-01 18:27:37 +00009984
9985 // Change this into a noret atomic.
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00009986 MI.setDesc(TII->get(NoRetAtomicOp));
9987 MI.RemoveOperand(0);
Tom Stellard354a43c2016-04-01 18:27:37 +00009988
9989 // If we only remove the def operand from the atomic instruction, the
9990 // extract_subreg will be left with a use of a vreg without a def.
9991 // So we need to insert an implicit_def to avoid machine verifier
9992 // errors.
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00009993 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
Tom Stellard354a43c2016-04-01 18:27:37 +00009994 TII->get(AMDGPU::IMPLICIT_DEF), Def);
9995 }
Matt Arsenault7ac9c4a2014-09-08 15:07:31 +00009996 return;
9997 }
Christian Konig8b1ed282013-04-10 08:39:16 +00009998}
Tom Stellard0518ff82013-06-03 17:39:58 +00009999
Benjamin Kramerbdc49562016-06-12 15:39:02 +000010000static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10001 uint64_t Val) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010002 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
Matt Arsenault485defe2014-11-05 19:01:17 +000010003 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10004}
10005
10006MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +000010007 const SDLoc &DL,
Matt Arsenault485defe2014-11-05 19:01:17 +000010008 SDValue Ptr) const {
Matt Arsenault43e92fe2016-06-24 06:30:11 +000010009 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
Matt Arsenault485defe2014-11-05 19:01:17 +000010010
Matt Arsenault2d6fdb82015-09-25 17:08:42 +000010011 // Build the half of the subregister with the constants before building the
10012 // full 128-bit register. If we are building multiple resource descriptors,
10013 // this will allow CSEing of the 2-component register.
10014 const SDValue Ops0[] = {
10015 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10016 buildSMovImm32(DAG, DL, 0),
10017 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10018 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10019 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10020 };
Matt Arsenault485defe2014-11-05 19:01:17 +000010021
Matt Arsenault2d6fdb82015-09-25 17:08:42 +000010022 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10023 MVT::v2i32, Ops0), 0);
Matt Arsenault485defe2014-11-05 19:01:17 +000010024
Matt Arsenault2d6fdb82015-09-25 17:08:42 +000010025 // Combine the constants and the pointer.
10026 const SDValue Ops1[] = {
10027 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
10028 Ptr,
10029 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10030 SubRegHi,
10031 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10032 };
Matt Arsenault485defe2014-11-05 19:01:17 +000010033
Matt Arsenault2d6fdb82015-09-25 17:08:42 +000010034 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
Matt Arsenault485defe2014-11-05 19:01:17 +000010035}
10036
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010037/// Return a resource descriptor with the 'Add TID' bit enabled
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000010038/// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10039/// of the resource descriptor) to create an offset, which is added to
10040/// the resource pointer.
Benjamin Kramerbdc49562016-06-12 15:39:02 +000010041MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10042 SDValue Ptr, uint32_t RsrcDword1,
Matt Arsenaultf3cd4512014-11-05 19:01:19 +000010043 uint64_t RsrcDword2And3) const {
10044 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10045 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10046 if (RsrcDword1) {
10047 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010048 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10049 0);
Matt Arsenaultf3cd4512014-11-05 19:01:19 +000010050 }
10051
10052 SDValue DataLo = buildSMovImm32(DAG, DL,
10053 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10054 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10055
10056 const SDValue Ops[] = {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010057 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
Matt Arsenaultf3cd4512014-11-05 19:01:19 +000010058 PtrLo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010059 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
Matt Arsenaultf3cd4512014-11-05 19:01:19 +000010060 PtrHi,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010061 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
Matt Arsenaultf3cd4512014-11-05 19:01:19 +000010062 DataLo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010063 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
Matt Arsenaultf3cd4512014-11-05 19:01:19 +000010064 DataHi,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010065 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
Matt Arsenaultf3cd4512014-11-05 19:01:19 +000010066 };
10067
10068 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10069}
10070
Tom Stellardd7e6f132015-04-08 01:09:26 +000010071//===----------------------------------------------------------------------===//
10072// SI Inline Assembly Support
10073//===----------------------------------------------------------------------===//
10074
10075std::pair<unsigned, const TargetRegisterClass *>
10076SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
Benjamin Kramer9bfb6272015-07-05 19:29:18 +000010077 StringRef Constraint,
Tom Stellardd7e6f132015-04-08 01:09:26 +000010078 MVT VT) const {
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010079 const TargetRegisterClass *RC = nullptr;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010080 if (Constraint.size() == 1) {
10081 switch (Constraint[0]) {
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010082 default:
10083 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010084 case 's':
10085 case 'r':
10086 switch (VT.getSizeInBits()) {
10087 default:
10088 return std::make_pair(0U, nullptr);
10089 case 32:
Matt Arsenault9e910142016-12-20 19:06:12 +000010090 case 16:
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010091 RC = &AMDGPU::SReg_32_XM0RegClass;
10092 break;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010093 case 64:
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010094 RC = &AMDGPU::SGPR_64RegClass;
10095 break;
Tim Renouf361b5b22019-03-21 12:01:21 +000010096 case 96:
10097 RC = &AMDGPU::SReg_96RegClass;
10098 break;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010099 case 128:
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010100 RC = &AMDGPU::SReg_128RegClass;
10101 break;
Tim Renouf033f99a2019-03-22 10:11:21 +000010102 case 160:
10103 RC = &AMDGPU::SReg_160RegClass;
10104 break;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010105 case 256:
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010106 RC = &AMDGPU::SReg_256RegClass;
10107 break;
Matt Arsenaulte0bf7d02017-02-21 19:12:08 +000010108 case 512:
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010109 RC = &AMDGPU::SReg_512RegClass;
10110 break;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010111 }
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010112 break;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010113 case 'v':
10114 switch (VT.getSizeInBits()) {
10115 default:
10116 return std::make_pair(0U, nullptr);
10117 case 32:
Matt Arsenault9e910142016-12-20 19:06:12 +000010118 case 16:
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010119 RC = &AMDGPU::VGPR_32RegClass;
10120 break;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010121 case 64:
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010122 RC = &AMDGPU::VReg_64RegClass;
10123 break;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010124 case 96:
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010125 RC = &AMDGPU::VReg_96RegClass;
10126 break;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010127 case 128:
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010128 RC = &AMDGPU::VReg_128RegClass;
10129 break;
Tim Renouf033f99a2019-03-22 10:11:21 +000010130 case 160:
10131 RC = &AMDGPU::VReg_160RegClass;
10132 break;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010133 case 256:
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010134 RC = &AMDGPU::VReg_256RegClass;
10135 break;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010136 case 512:
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010137 RC = &AMDGPU::VReg_512RegClass;
10138 break;
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010139 }
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010140 break;
Tom Stellardd7e6f132015-04-08 01:09:26 +000010141 }
Daniil Fukalovc9a098b2018-06-08 16:29:04 +000010142 // We actually support i128, i16 and f16 as inline parameters
10143 // even if they are not reported as legal
10144 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10145 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10146 return std::make_pair(0U, RC);
Tom Stellardd7e6f132015-04-08 01:09:26 +000010147 }
10148
10149 if (Constraint.size() > 1) {
Tom Stellardd7e6f132015-04-08 01:09:26 +000010150 if (Constraint[1] == 'v') {
10151 RC = &AMDGPU::VGPR_32RegClass;
10152 } else if (Constraint[1] == 's') {
10153 RC = &AMDGPU::SGPR_32RegClass;
10154 }
10155
10156 if (RC) {
Matt Arsenault0b554ed2015-06-23 02:05:55 +000010157 uint32_t Idx;
10158 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10159 if (!Failed && Idx < RC->getNumRegs())
Tom Stellardd7e6f132015-04-08 01:09:26 +000010160 return std::make_pair(RC->getRegister(Idx), RC);
10161 }
10162 }
10163 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10164}
Tom Stellardb3c3bda2015-12-10 02:12:53 +000010165
10166SITargetLowering::ConstraintType
10167SITargetLowering::getConstraintType(StringRef Constraint) const {
10168 if (Constraint.size() == 1) {
10169 switch (Constraint[0]) {
10170 default: break;
10171 case 's':
10172 case 'v':
10173 return C_RegisterClass;
10174 }
10175 }
10176 return TargetLowering::getConstraintType(Constraint);
10177}
Matt Arsenault1cc47f82017-07-18 16:44:56 +000010178
10179// Figure out which registers should be reserved for stack access. Only after
10180// the function is legalized do we know all of the non-spill stack objects or if
10181// calls are present.
10182void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10183 MachineRegisterInfo &MRI = MF.getRegInfo();
10184 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +000010185 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
Tom Stellardc5a154d2018-06-28 23:47:12 +000010186 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
Matt Arsenault1cc47f82017-07-18 16:44:56 +000010187
10188 if (Info->isEntryFunction()) {
10189 // Callable functions have fixed registers used for stack access.
10190 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10191 }
10192
Matt Arsenaultb812b7a2019-06-05 22:20:47 +000010193 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10194 Info->getStackPtrOffsetReg()));
10195 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10196 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
Matt Arsenault1cc47f82017-07-18 16:44:56 +000010197
Matt Arsenaultbc6d07c2019-03-14 22:54:43 +000010198 // We need to worry about replacing the default register with itself in case
10199 // of MIR testcases missing the MFI.
10200 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10201 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10202
10203 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10204 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10205
10206 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) {
10207 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
10208 Info->getScratchWaveOffsetReg());
10209 }
Matt Arsenault1cc47f82017-07-18 16:44:56 +000010210
Stanislav Mekhanoshind4b500c2018-05-31 05:36:04 +000010211 Info->limitOccupancy(MF);
10212
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +000010213 if (ST.isWave32() && !MF.empty()) {
10214 // Add VCC_HI def because many instructions marked as imp-use VCC where
10215 // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10216 // having a use of undef.
10217
10218 const SIInstrInfo *TII = ST.getInstrInfo();
10219 DebugLoc DL;
10220
10221 MachineBasicBlock &MBB = MF.front();
10222 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10223 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10224
10225 for (auto &MBB : MF) {
10226 for (auto &MI : MBB) {
10227 TII->fixImplicitOperands(MI);
10228 }
10229 }
10230 }
10231
Matt Arsenault1cc47f82017-07-18 16:44:56 +000010232 TargetLoweringBase::finalizeLowering(MF);
10233}
Matt Arsenault45b98182017-11-15 00:45:43 +000010234
10235void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10236 KnownBits &Known,
10237 const APInt &DemandedElts,
10238 const SelectionDAG &DAG,
10239 unsigned Depth) const {
10240 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10241 DAG, Depth);
10242
Matt Arsenault5c714cb2019-05-23 19:38:14 +000010243 // Set the high bits to zero based on the maximum allowed scratch size per
10244 // wave. We can't use vaddr in MUBUF instructions if we don't know the address
Matt Arsenault45b98182017-11-15 00:45:43 +000010245 // calculation won't overflow, so assume the sign bit is never set.
Matt Arsenault5c714cb2019-05-23 19:38:14 +000010246 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
Matt Arsenault45b98182017-11-15 00:45:43 +000010247}
Tom Stellard264c1712018-06-13 15:06:37 +000010248
Stanislav Mekhanoshin93f15c92019-05-03 21:17:29 +000010249unsigned SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10250 const unsigned PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10251 const unsigned CacheLineAlign = 6; // log2(64)
10252
10253 // Pre-GFX10 target did not benefit from loop alignment
10254 if (!ML || DisableLoopAlignment ||
10255 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10256 getSubtarget()->hasInstFwdPrefetchBug())
10257 return PrefAlign;
10258
10259 // On GFX10 I$ is 4 x 64 bytes cache lines.
10260 // By default prefetcher keeps one cache line behind and reads two ahead.
10261 // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10262 // behind and one ahead.
10263 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10264 // If loop fits 64 bytes it always spans no more than two cache lines and
10265 // does not need an alignment.
10266 // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10267 // Else if loop is less or equal 192 bytes we need two lines behind.
10268
10269 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10270 const MachineBasicBlock *Header = ML->getHeader();
10271 if (Header->getAlignment() != PrefAlign)
10272 return Header->getAlignment(); // Already processed.
10273
10274 unsigned LoopSize = 0;
10275 for (const MachineBasicBlock *MBB : ML->blocks()) {
10276 // If inner loop block is aligned assume in average half of the alignment
10277 // size to be added as nops.
10278 if (MBB != Header)
10279 LoopSize += (1 << MBB->getAlignment()) / 2;
10280
10281 for (const MachineInstr &MI : *MBB) {
10282 LoopSize += TII->getInstSizeInBytes(MI);
10283 if (LoopSize > 192)
10284 return PrefAlign;
10285 }
10286 }
10287
10288 if (LoopSize <= 64)
10289 return PrefAlign;
10290
10291 if (LoopSize <= 128)
10292 return CacheLineAlign;
10293
10294 // If any of parent loops is surrounded by prefetch instructions do not
10295 // insert new for inner loop, which would reset parent's settings.
10296 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10297 if (MachineBasicBlock *Exit = P->getExitBlock()) {
10298 auto I = Exit->getFirstNonDebugInstr();
10299 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10300 return CacheLineAlign;
10301 }
10302 }
10303
10304 MachineBasicBlock *Pre = ML->getLoopPreheader();
10305 MachineBasicBlock *Exit = ML->getExitBlock();
10306
10307 if (Pre && Exit) {
10308 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10309 TII->get(AMDGPU::S_INST_PREFETCH))
10310 .addImm(1); // prefetch 2 lines behind PC
10311
10312 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10313 TII->get(AMDGPU::S_INST_PREFETCH))
10314 .addImm(2); // prefetch 1 line behind PC
10315 }
10316
10317 return CacheLineAlign;
10318}
10319
Nicolai Haehnlea9cc92c2018-11-30 22:55:29 +000010320LLVM_ATTRIBUTE_UNUSED
10321static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10322 assert(N->getOpcode() == ISD::CopyFromReg);
10323 do {
10324 // Follow the chain until we find an INLINEASM node.
10325 N = N->getOperand(0).getNode();
Craig Topper784929d2019-02-08 20:48:56 +000010326 if (N->getOpcode() == ISD::INLINEASM ||
10327 N->getOpcode() == ISD::INLINEASM_BR)
Nicolai Haehnlea9cc92c2018-11-30 22:55:29 +000010328 return true;
10329 } while (N->getOpcode() == ISD::CopyFromReg);
10330 return false;
10331}
10332
Tom Stellard264c1712018-06-13 15:06:37 +000010333bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
Nicolai Haehnle35617ed2018-08-30 14:21:36 +000010334 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
Tom Stellard264c1712018-06-13 15:06:37 +000010335{
10336 switch (N->getOpcode()) {
Tom Stellard264c1712018-06-13 15:06:37 +000010337 case ISD::CopyFromReg:
10338 {
Nicolai Haehnlea9cc92c2018-11-30 22:55:29 +000010339 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10340 const MachineFunction * MF = FLI->MF;
10341 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10342 const MachineRegisterInfo &MRI = MF->getRegInfo();
10343 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10344 unsigned Reg = R->getReg();
10345 if (TRI.isPhysicalRegister(Reg))
10346 return !TRI.isSGPRReg(MRI, Reg);
Tom Stellard264c1712018-06-13 15:06:37 +000010347
Nicolai Haehnlea9cc92c2018-11-30 22:55:29 +000010348 if (MRI.isLiveIn(Reg)) {
10349 // workitem.id.x workitem.id.y workitem.id.z
10350 // Any VGPR formal argument is also considered divergent
10351 if (!TRI.isSGPRReg(MRI, Reg))
10352 return true;
10353 // Formal arguments of non-entry functions
10354 // are conservatively considered divergent
10355 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10356 return true;
10357 return false;
Tom Stellard264c1712018-06-13 15:06:37 +000010358 }
Nicolai Haehnlea9cc92c2018-11-30 22:55:29 +000010359 const Value *V = FLI->getValueFromVirtualReg(Reg);
10360 if (V)
10361 return KDA->isDivergent(V);
10362 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10363 return !TRI.isSGPRReg(MRI, Reg);
Tom Stellard264c1712018-06-13 15:06:37 +000010364 }
10365 break;
10366 case ISD::LOAD: {
Matt Arsenault813613c2018-09-04 18:58:19 +000010367 const LoadSDNode *L = cast<LoadSDNode>(N);
10368 unsigned AS = L->getAddressSpace();
10369 // A flat load may access private memory.
10370 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
Tom Stellard264c1712018-06-13 15:06:37 +000010371 } break;
10372 case ISD::CALLSEQ_END:
10373 return true;
10374 break;
10375 case ISD::INTRINSIC_WO_CHAIN:
10376 {
10377
10378 }
10379 return AMDGPU::isIntrinsicSourceOfDivergence(
10380 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10381 case ISD::INTRINSIC_W_CHAIN:
10382 return AMDGPU::isIntrinsicSourceOfDivergence(
10383 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10384 // In some cases intrinsics that are a source of divergence have been
10385 // lowered to AMDGPUISD so we also need to check those too.
10386 case AMDGPUISD::INTERP_MOV:
10387 case AMDGPUISD::INTERP_P1:
10388 case AMDGPUISD::INTERP_P2:
10389 return true;
10390 }
10391 return false;
10392}
Matt Arsenaultf8768bf2018-08-06 21:38:27 +000010393
10394bool SITargetLowering::denormalsEnabledForType(EVT VT) const {
10395 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10396 case MVT::f32:
10397 return Subtarget->hasFP32Denormals();
10398 case MVT::f64:
10399 return Subtarget->hasFP64Denormals();
10400 case MVT::f16:
10401 return Subtarget->hasFP16Denormals();
10402 default:
10403 return false;
10404 }
10405}
Matt Arsenault687ec752018-10-22 16:27:27 +000010406
10407bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10408 const SelectionDAG &DAG,
10409 bool SNaN,
10410 unsigned Depth) const {
10411 if (Op.getOpcode() == AMDGPUISD::CLAMP) {
Matt Arsenault055e4dc2019-03-29 19:14:54 +000010412 const MachineFunction &MF = DAG.getMachineFunction();
10413 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10414
10415 if (Info->getMode().DX10Clamp)
Matt Arsenault687ec752018-10-22 16:27:27 +000010416 return true; // Clamped to 0.
10417 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10418 }
10419
10420 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10421 SNaN, Depth);
10422}
Matt Arsenaulta5840c32019-01-22 18:36:06 +000010423
10424TargetLowering::AtomicExpansionKind
10425SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10426 switch (RMW->getOperation()) {
10427 case AtomicRMWInst::FAdd: {
10428 Type *Ty = RMW->getType();
10429
10430 // We don't have a way to support 16-bit atomics now, so just leave them
10431 // as-is.
10432 if (Ty->isHalfTy())
10433 return AtomicExpansionKind::None;
10434
10435 if (!Ty->isFloatTy())
10436 return AtomicExpansionKind::CmpXChg;
10437
10438 // TODO: Do have these for flat. Older targets also had them for buffers.
10439 unsigned AS = RMW->getPointerAddressSpace();
10440 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10441 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10442 }
10443 default:
10444 break;
10445 }
10446
10447 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10448}