blob: 9361b25db144f8265595ccc858d127cf19c79970 [file] [log] [blame]
Tom Stellard6596ba72014-11-21 22:06:37 +00001//===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===//
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 Stellard6596ba72014-11-21 22:06:37 +00006//
7/// \file
8//===----------------------------------------------------------------------===//
9//
10
11#include "AMDGPU.h"
12#include "AMDGPUSubtarget.h"
13#include "SIInstrInfo.h"
Matt Arsenault3cb39042017-02-27 19:35:42 +000014#include "SIMachineFunctionInfo.h"
Tom Stellard44b30b42018-05-22 02:03:23 +000015#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
Matt Arsenaultff3f9122017-06-20 18:56:32 +000016#include "llvm/ADT/DepthFirstIterator.h"
Matthias Braunf8422972017-12-13 02:51:04 +000017#include "llvm/CodeGen/LiveIntervals.h"
Tom Stellard6596ba72014-11-21 22:06:37 +000018#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/MachineRegisterInfo.h"
Tom Stellard6596ba72014-11-21 22:06:37 +000021#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000022#include "llvm/Support/raw_ostream.h"
Tom Stellard6596ba72014-11-21 22:06:37 +000023#include "llvm/Target/TargetMachine.h"
24
25#define DEBUG_TYPE "si-fold-operands"
26using namespace llvm;
27
28namespace {
29
Tom Stellardbb763e62015-01-07 17:42:16 +000030struct FoldCandidate {
31 MachineInstr *UseMI;
Matt Arsenault2bc198a2016-09-14 15:51:33 +000032 union {
33 MachineOperand *OpToFold;
34 uint64_t ImmToFold;
35 int FrameIndexToFold;
36 };
Matt Arsenaultde6c4212018-08-28 18:34:24 +000037 int ShrinkOpcode;
Matt Arsenault2bc198a2016-09-14 15:51:33 +000038 unsigned char UseOpNo;
39 MachineOperand::MachineOperandType Kind;
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +000040 bool Commuted;
Tom Stellardbb763e62015-01-07 17:42:16 +000041
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +000042 FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp,
Matt Arsenaultde6c4212018-08-28 18:34:24 +000043 bool Commuted_ = false,
44 int ShrinkOp = -1) :
45 UseMI(MI), OpToFold(nullptr), ShrinkOpcode(ShrinkOp), UseOpNo(OpNo),
46 Kind(FoldOp->getType()),
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +000047 Commuted(Commuted_) {
Tom Stellard05992972015-01-07 22:44:19 +000048 if (FoldOp->isImm()) {
Tom Stellard05992972015-01-07 22:44:19 +000049 ImmToFold = FoldOp->getImm();
Matt Arsenault2bc198a2016-09-14 15:51:33 +000050 } else if (FoldOp->isFI()) {
51 FrameIndexToFold = FoldOp->getIndex();
Tom Stellard05992972015-01-07 22:44:19 +000052 } else {
53 assert(FoldOp->isReg());
54 OpToFold = FoldOp;
55 }
56 }
Tom Stellardbb763e62015-01-07 17:42:16 +000057
Matt Arsenault2bc198a2016-09-14 15:51:33 +000058 bool isFI() const {
59 return Kind == MachineOperand::MO_FrameIndex;
60 }
61
Tom Stellardbb763e62015-01-07 17:42:16 +000062 bool isImm() const {
Matt Arsenault2bc198a2016-09-14 15:51:33 +000063 return Kind == MachineOperand::MO_Immediate;
64 }
65
66 bool isReg() const {
67 return Kind == MachineOperand::MO_Register;
Tom Stellardbb763e62015-01-07 17:42:16 +000068 }
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +000069
70 bool isCommuted() const {
71 return Commuted;
72 }
Matt Arsenaultde6c4212018-08-28 18:34:24 +000073
74 bool needsShrink() const {
75 return ShrinkOpcode != -1;
76 }
77
78 int getShrinkOpcode() const {
79 return ShrinkOpcode;
80 }
Tom Stellardbb763e62015-01-07 17:42:16 +000081};
82
Matt Arsenault51818c12017-01-10 23:32:04 +000083class SIFoldOperands : public MachineFunctionPass {
84public:
85 static char ID;
86 MachineRegisterInfo *MRI;
87 const SIInstrInfo *TII;
88 const SIRegisterInfo *TRI;
Tom Stellard5bfbae52018-07-11 20:59:01 +000089 const GCNSubtarget *ST;
Matt Arsenault51818c12017-01-10 23:32:04 +000090
91 void foldOperand(MachineOperand &OpToFold,
92 MachineInstr *UseMI,
93 unsigned UseOpIdx,
94 SmallVectorImpl<FoldCandidate> &FoldList,
95 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
96
97 void foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const;
98
Matt Arsenaultd5c65152017-02-22 23:27:53 +000099 const MachineOperand *isClamp(const MachineInstr &MI) const;
100 bool tryFoldClamp(MachineInstr &MI);
101
Matt Arsenault3cb39042017-02-27 19:35:42 +0000102 std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
103 bool tryFoldOMod(MachineInstr &MI);
104
Matt Arsenault51818c12017-01-10 23:32:04 +0000105public:
106 SIFoldOperands() : MachineFunctionPass(ID) {
107 initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry());
108 }
109
110 bool runOnMachineFunction(MachineFunction &MF) override;
111
112 StringRef getPassName() const override { return "SI Fold Operands"; }
113
114 void getAnalysisUsage(AnalysisUsage &AU) const override {
115 AU.setPreservesCFG();
116 MachineFunctionPass::getAnalysisUsage(AU);
117 }
118};
119
Tom Stellard6596ba72014-11-21 22:06:37 +0000120} // End anonymous namespace.
121
Matt Arsenault427c5482016-02-11 06:15:34 +0000122INITIALIZE_PASS(SIFoldOperands, DEBUG_TYPE,
123 "SI Fold Operands", false, false)
Tom Stellard6596ba72014-11-21 22:06:37 +0000124
125char SIFoldOperands::ID = 0;
126
127char &llvm::SIFoldOperandsID = SIFoldOperands::ID;
128
Matt Arsenault69e30012017-01-11 22:00:02 +0000129// Wrapper around isInlineConstant that understands special cases when
130// instruction types are replaced during operand folding.
131static bool isInlineConstantIfFolded(const SIInstrInfo *TII,
132 const MachineInstr &UseMI,
133 unsigned OpNo,
134 const MachineOperand &OpToFold) {
135 if (TII->isInlineConstant(UseMI, OpNo, OpToFold))
136 return true;
137
138 unsigned Opc = UseMI.getOpcode();
139 switch (Opc) {
140 case AMDGPU::V_MAC_F32_e64:
Matt Arsenault0084adc2018-04-30 19:08:16 +0000141 case AMDGPU::V_MAC_F16_e64:
142 case AMDGPU::V_FMAC_F32_e64: {
Matt Arsenault69e30012017-01-11 22:00:02 +0000143 // Special case for mac. Since this is replaced with mad when folded into
144 // src2, we need to check the legality for the final instruction.
145 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
146 if (static_cast<int>(OpNo) == Src2Idx) {
Matt Arsenault0084adc2018-04-30 19:08:16 +0000147 bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e64;
Matt Arsenault69e30012017-01-11 22:00:02 +0000148 bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
Matt Arsenault0084adc2018-04-30 19:08:16 +0000149
150 unsigned Opc = IsFMA ?
151 AMDGPU::V_FMA_F32 : (IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16);
152 const MCInstrDesc &MadDesc = TII->get(Opc);
Matt Arsenault69e30012017-01-11 22:00:02 +0000153 return TII->isInlineConstant(OpToFold, MadDesc.OpInfo[OpNo].OperandType);
154 }
Simon Pilgrim0f5b3502017-07-07 10:18:57 +0000155 return false;
Matt Arsenault69e30012017-01-11 22:00:02 +0000156 }
157 default:
158 return false;
159 }
160}
161
Tom Stellard6596ba72014-11-21 22:06:37 +0000162FunctionPass *llvm::createSIFoldOperandsPass() {
163 return new SIFoldOperands();
164}
165
Tom Stellardbb763e62015-01-07 17:42:16 +0000166static bool updateOperand(FoldCandidate &Fold,
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000167 const SIInstrInfo &TII,
Tom Stellard6596ba72014-11-21 22:06:37 +0000168 const TargetRegisterInfo &TRI) {
Tom Stellardbb763e62015-01-07 17:42:16 +0000169 MachineInstr *MI = Fold.UseMI;
170 MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
Tom Stellard6596ba72014-11-21 22:06:37 +0000171 assert(Old.isReg());
172
Tom Stellardbb763e62015-01-07 17:42:16 +0000173 if (Fold.isImm()) {
Stanislav Mekhanoshin8b20b7d2018-04-17 23:09:05 +0000174 if (MI->getDesc().TSFlags & SIInstrFlags::IsPacked) {
Stanislav Mekhanoshin160f8572018-04-19 21:16:50 +0000175 // Set op_sel/op_sel_hi on this operand or bail out if op_sel is
176 // already set.
Stanislav Mekhanoshin8b20b7d2018-04-17 23:09:05 +0000177 unsigned Opcode = MI->getOpcode();
178 int OpNo = MI->getOperandNo(&Old);
179 int ModIdx = -1;
180 if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0))
181 ModIdx = AMDGPU::OpName::src0_modifiers;
182 else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1))
183 ModIdx = AMDGPU::OpName::src1_modifiers;
184 else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2))
185 ModIdx = AMDGPU::OpName::src2_modifiers;
186 assert(ModIdx != -1);
187 ModIdx = AMDGPU::getNamedOperandIdx(Opcode, ModIdx);
188 MachineOperand &Mod = MI->getOperand(ModIdx);
189 unsigned Val = Mod.getImm();
190 if ((Val & SISrcMods::OP_SEL_0) || !(Val & SISrcMods::OP_SEL_1))
191 return false;
Stanislav Mekhanoshin160f8572018-04-19 21:16:50 +0000192 // If upper part is all zero we do not need op_sel_hi.
193 if (!isUInt<16>(Fold.ImmToFold)) {
194 if (!(Fold.ImmToFold & 0xffff)) {
195 Mod.setImm(Mod.getImm() | SISrcMods::OP_SEL_0);
196 Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
Stanislav Mekhanoshina4bfb3c2018-04-24 18:17:55 +0000197 Old.ChangeToImmediate((Fold.ImmToFold >> 16) & 0xffff);
Stanislav Mekhanoshin160f8572018-04-19 21:16:50 +0000198 return true;
199 }
200 Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
201 }
Stanislav Mekhanoshin8b20b7d2018-04-17 23:09:05 +0000202 }
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000203
204 if (Fold.needsShrink()) {
205 MachineBasicBlock *MBB = MI->getParent();
206 auto Liveness = MBB->computeRegisterLiveness(&TRI, AMDGPU::VCC, MI);
207 if (Liveness != MachineBasicBlock::LQR_Dead)
208 return false;
209
Matt Arsenault44a8a752018-08-28 18:44:16 +0000210 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000211 int Op32 = Fold.getShrinkOpcode();
212 MachineOperand &Dst0 = MI->getOperand(0);
213 MachineOperand &Dst1 = MI->getOperand(1);
214 assert(Dst0.isDef() && Dst1.isDef());
215
Matt Arsenault44a8a752018-08-28 18:44:16 +0000216 bool HaveNonDbgCarryUse = !MRI.use_nodbg_empty(Dst1.getReg());
217
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000218 const TargetRegisterClass *Dst0RC = MRI.getRegClass(Dst0.getReg());
219 unsigned NewReg0 = MRI.createVirtualRegister(Dst0RC);
220 const TargetRegisterClass *Dst1RC = MRI.getRegClass(Dst1.getReg());
221 unsigned NewReg1 = MRI.createVirtualRegister(Dst1RC);
222
223 MachineInstr *Inst32 = TII.buildShrunkInst(*MI, Op32);
224
Matt Arsenault44a8a752018-08-28 18:44:16 +0000225 if (HaveNonDbgCarryUse) {
226 BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::COPY), Dst1.getReg())
227 .addReg(AMDGPU::VCC, RegState::Kill);
228 }
229
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000230 // Keep the old instruction around to avoid breaking iterators, but
231 // replace the outputs with dummy registers.
232 Dst0.setReg(NewReg0);
233 Dst1.setReg(NewReg1);
234
235 if (Fold.isCommuted())
236 TII.commuteInstruction(*Inst32, false);
237 return true;
238 }
239
Tom Stellardbb763e62015-01-07 17:42:16 +0000240 Old.ChangeToImmediate(Fold.ImmToFold);
Tom Stellard6596ba72014-11-21 22:06:37 +0000241 return true;
242 }
243
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000244 assert(!Fold.needsShrink() && "not handled");
245
Matt Arsenault2bc198a2016-09-14 15:51:33 +0000246 if (Fold.isFI()) {
247 Old.ChangeToFrameIndex(Fold.FrameIndexToFold);
248 return true;
249 }
250
Tom Stellardbb763e62015-01-07 17:42:16 +0000251 MachineOperand *New = Fold.OpToFold;
252 if (TargetRegisterInfo::isVirtualRegister(Old.getReg()) &&
253 TargetRegisterInfo::isVirtualRegister(New->getReg())) {
254 Old.substVirtReg(New->getReg(), New->getSubReg(), TRI);
Matt Arsenault76858f52017-06-20 18:41:31 +0000255
256 Old.setIsUndef(New->isUndef());
Tom Stellard6596ba72014-11-21 22:06:37 +0000257 return true;
258 }
259
Tom Stellard6596ba72014-11-21 22:06:37 +0000260 // FIXME: Handle physical registers.
261
262 return false;
263}
264
Matt Arsenault51818c12017-01-10 23:32:04 +0000265static bool isUseMIInFoldList(ArrayRef<FoldCandidate> FoldList,
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000266 const MachineInstr *MI) {
267 for (auto Candidate : FoldList) {
268 if (Candidate.UseMI == MI)
269 return true;
270 }
271 return false;
272}
273
Matt Arsenault51818c12017-01-10 23:32:04 +0000274static bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
Tom Stellard05992972015-01-07 22:44:19 +0000275 MachineInstr *MI, unsigned OpNo,
276 MachineOperand *OpToFold,
277 const SIInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000278 if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000279
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000280 // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000281 unsigned Opc = MI->getOpcode();
Matt Arsenault0084adc2018-04-30 19:08:16 +0000282 if ((Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64 ||
283 Opc == AMDGPU::V_FMAC_F32_e64) &&
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000284 (int)OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)) {
Matt Arsenault0084adc2018-04-30 19:08:16 +0000285 bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e64;
Matt Arsenault69e30012017-01-11 22:00:02 +0000286 bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
Matt Arsenault0084adc2018-04-30 19:08:16 +0000287 unsigned NewOpc = IsFMA ?
288 AMDGPU::V_FMA_F32 : (IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16);
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000289
290 // Check if changing this to a v_mad_{f16, f32} instruction will allow us
291 // to fold the operand.
Matt Arsenault0084adc2018-04-30 19:08:16 +0000292 MI->setDesc(TII->get(NewOpc));
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000293 bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold, TII);
294 if (FoldAsMAD) {
295 MI->untieRegOperand(OpNo);
296 return true;
297 }
298 MI->setDesc(TII->get(Opc));
299 }
300
Tom Stellard8485fa02016-12-07 02:42:15 +0000301 // Special case for s_setreg_b32
302 if (Opc == AMDGPU::S_SETREG_B32 && OpToFold->isImm()) {
303 MI->setDesc(TII->get(AMDGPU::S_SETREG_IMM32_B32));
304 FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
305 return true;
306 }
307
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000308 // If we are already folding into another operand of MI, then
309 // we can't commute the instruction, otherwise we risk making the
310 // other fold illegal.
311 if (isUseMIInFoldList(FoldList, MI))
312 return false;
313
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000314 unsigned CommuteOpNo = OpNo;
315
Tom Stellard05992972015-01-07 22:44:19 +0000316 // Operand is not legal, so try to commute the instruction to
317 // see if this makes it possible to fold.
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000318 unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex;
319 unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000320 bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1);
Tom Stellard05992972015-01-07 22:44:19 +0000321
322 if (CanCommute) {
323 if (CommuteIdx0 == OpNo)
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000324 CommuteOpNo = CommuteIdx1;
Tom Stellard05992972015-01-07 22:44:19 +0000325 else if (CommuteIdx1 == OpNo)
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000326 CommuteOpNo = CommuteIdx0;
Tom Stellard05992972015-01-07 22:44:19 +0000327 }
328
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000329
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000330 // One of operands might be an Imm operand, and OpNo may refer to it after
331 // the call of commuteInstruction() below. Such situations are avoided
332 // here explicitly as OpNo must be a register operand to be a candidate
333 // for memory folding.
334 if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() ||
335 !MI->getOperand(CommuteIdx1).isReg()))
336 return false;
337
338 if (!CanCommute ||
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000339 !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1))
Tom Stellard05992972015-01-07 22:44:19 +0000340 return false;
341
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000342 if (!TII->isOperandLegal(*MI, CommuteOpNo, OpToFold)) {
343 if ((Opc == AMDGPU::V_ADD_I32_e64 ||
344 Opc == AMDGPU::V_SUB_I32_e64 ||
345 Opc == AMDGPU::V_SUBREV_I32_e64) && // FIXME
346 OpToFold->isImm()) {
347 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
348
349 // Verify the other operand is a VGPR, otherwise we would violate the
350 // constant bus restriction.
351 unsigned OtherIdx = CommuteOpNo == CommuteIdx0 ? CommuteIdx1 : CommuteIdx0;
352 MachineOperand &OtherOp = MI->getOperand(OtherIdx);
353 if (!OtherOp.isReg() ||
354 !TII->getRegisterInfo().isVGPR(MRI, OtherOp.getReg()))
355 return false;
356
Fangrui Song9cca2272018-08-28 19:19:03 +0000357 assert(MI->getOperand(1).isDef());
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000358
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000359 int Op32 = AMDGPU::getVOPe32(Opc);
360 FoldList.push_back(FoldCandidate(MI, CommuteOpNo, OpToFold, true,
361 Op32));
362 return true;
363 }
364
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +0000365 TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1);
Tom Stellard05992972015-01-07 22:44:19 +0000366 return false;
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +0000367 }
368
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000369 FoldList.push_back(FoldCandidate(MI, CommuteOpNo, OpToFold, true));
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +0000370 return true;
Tom Stellard05992972015-01-07 22:44:19 +0000371 }
372
373 FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
374 return true;
375}
376
Matt Arsenault5e63a042016-10-06 18:12:13 +0000377// If the use operand doesn't care about the value, this may be an operand only
378// used for register indexing, in which case it is unsafe to fold.
Stanislav Mekhanoshin56ea4882017-05-30 16:49:24 +0000379static bool isUseSafeToFold(const SIInstrInfo *TII,
380 const MachineInstr &MI,
Matt Arsenault5e63a042016-10-06 18:12:13 +0000381 const MachineOperand &UseMO) {
Stanislav Mekhanoshin56ea4882017-05-30 16:49:24 +0000382 return !UseMO.isUndef() && !TII->isSDWA(MI);
Matt Arsenault5e63a042016-10-06 18:12:13 +0000383 //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg());
384}
385
Matt Arsenault51818c12017-01-10 23:32:04 +0000386void SIFoldOperands::foldOperand(
387 MachineOperand &OpToFold,
388 MachineInstr *UseMI,
389 unsigned UseOpIdx,
390 SmallVectorImpl<FoldCandidate> &FoldList,
391 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000392 const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
393
Stanislav Mekhanoshin56ea4882017-05-30 16:49:24 +0000394 if (!isUseSafeToFold(TII, *UseMI, UseOp))
Matt Arsenault5e63a042016-10-06 18:12:13 +0000395 return;
396
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000397 // FIXME: Fold operands with subregs.
Matt Arsenault3661e902016-08-15 16:18:36 +0000398 if (UseOp.isReg() && OpToFold.isReg()) {
399 if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister)
400 return;
401
402 // Don't fold subregister extracts into tied operands, only if it is a full
403 // copy since a subregister use tied to a full register def doesn't really
404 // make sense. e.g. don't fold:
405 //
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +0000406 // %1 = COPY %0:sub1
407 // %2<tied3> = V_MAC_{F16, F32} %3, %4, %1<tied0>
Matt Arsenault3661e902016-08-15 16:18:36 +0000408 //
409 // into
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +0000410 // %2<tied3> = V_MAC_{F16, F32} %3, %4, %0:sub1<tied0>
Matt Arsenault3661e902016-08-15 16:18:36 +0000411 if (UseOp.isTied() && OpToFold.getSubReg() != AMDGPU::NoSubRegister)
412 return;
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000413 }
414
Tom Stellard9a197672015-09-09 15:43:26 +0000415 // Special case for REG_SEQUENCE: We can't fold literals into
416 // REG_SEQUENCE instructions, so we have to fold them into the
417 // uses of REG_SEQUENCE.
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000418 if (UseMI->isRegSequence()) {
Tom Stellard9a197672015-09-09 15:43:26 +0000419 unsigned RegSeqDstReg = UseMI->getOperand(0).getReg();
420 unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
421
422 for (MachineRegisterInfo::use_iterator
Matt Arsenault51818c12017-01-10 23:32:04 +0000423 RSUse = MRI->use_begin(RegSeqDstReg), RSE = MRI->use_end();
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000424 RSUse != RSE; ++RSUse) {
Tom Stellard9a197672015-09-09 15:43:26 +0000425
426 MachineInstr *RSUseMI = RSUse->getParent();
427 if (RSUse->getSubReg() != RegSeqDstSubReg)
428 continue;
429
430 foldOperand(OpToFold, RSUseMI, RSUse.getOperandNo(), FoldList,
Matt Arsenault51818c12017-01-10 23:32:04 +0000431 CopiesToReplace);
Tom Stellard9a197672015-09-09 15:43:26 +0000432 }
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000433
Tom Stellard9a197672015-09-09 15:43:26 +0000434 return;
435 }
436
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000437
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000438 bool FoldingImm = OpToFold.isImm();
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000439
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000440 if (FoldingImm && UseMI->isCopy()) {
441 unsigned DestReg = UseMI->getOperand(0).getReg();
442 const TargetRegisterClass *DestRC
443 = TargetRegisterInfo::isVirtualRegister(DestReg) ?
Matt Arsenault51818c12017-01-10 23:32:04 +0000444 MRI->getRegClass(DestReg) :
445 TRI->getPhysRegClass(DestReg);
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000446
Alexander Timofeev201f8922018-08-30 13:55:04 +0000447 unsigned SrcReg = UseMI->getOperand(1).getReg();
448 if (TargetRegisterInfo::isVirtualRegister(DestReg) &&
449 TargetRegisterInfo::isVirtualRegister(SrcReg)) {
450 const TargetRegisterClass * SrcRC = MRI->getRegClass(SrcReg);
451 if (TRI->isSGPRClass(SrcRC) && TRI->hasVGPRs(DestRC)) {
452 MachineRegisterInfo::use_iterator NextUse;
453 SmallVector<FoldCandidate, 4> CopyUses;
454 for (MachineRegisterInfo::use_iterator
455 Use = MRI->use_begin(DestReg), E = MRI->use_end();
456 Use != E; Use = NextUse) {
457 NextUse = std::next(Use);
458 FoldCandidate FC = FoldCandidate(Use->getParent(),
459 Use.getOperandNo(), &UseMI->getOperand(1));
460 CopyUses.push_back(FC);
461 }
462 for (auto & F : CopyUses) {
463 foldOperand(*F.OpToFold, F.UseMI, F.UseOpNo,
464 FoldList, CopiesToReplace);
465 }
466 }
467 }
468
469 // In order to fold immediates into copies, we need to change the
470 // copy to a MOV.
471
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000472 unsigned MovOp = TII->getMovOpcode(DestRC);
473 if (MovOp == AMDGPU::COPY)
474 return;
475
476 UseMI->setDesc(TII->get(MovOp));
477 CopiesToReplace.push_back(UseMI);
478 } else {
Stanislav Mekhanoshinb080adf2018-09-27 18:55:20 +0000479 if (UseMI->isCopy() && OpToFold.isReg() &&
480 TargetRegisterInfo::isVirtualRegister(UseMI->getOperand(0).getReg()) &&
481 TargetRegisterInfo::isVirtualRegister(UseMI->getOperand(1).getReg()) &&
482 TRI->isVGPR(*MRI, UseMI->getOperand(0).getReg()) &&
483 TRI->isVGPR(*MRI, UseMI->getOperand(1).getReg()) &&
484 !UseMI->getOperand(1).getSubReg()) {
485 UseMI->getOperand(1).setReg(OpToFold.getReg());
486 UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
487 UseMI->getOperand(1).setIsKill(false);
488 CopiesToReplace.push_back(UseMI);
489 OpToFold.setIsKill(false);
490 return;
491 }
492
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000493 const MCInstrDesc &UseDesc = UseMI->getDesc();
494
495 // Don't fold into target independent nodes. Target independent opcodes
496 // don't have defined register classes.
497 if (UseDesc.isVariadic() ||
Matt Arsenaultc908e3f2018-02-08 01:12:46 +0000498 UseOp.isImplicit() ||
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000499 UseDesc.OpInfo[UseOpIdx].RegClass == -1)
500 return;
501 }
502
503 if (!FoldingImm) {
504 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
505
506 // FIXME: We could try to change the instruction from 64-bit to 32-bit
507 // to enable more folding opportunites. The shrink operands pass
508 // already does this.
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000509 return;
510 }
511
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000512
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000513 const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
514 const TargetRegisterClass *FoldRC =
Matt Arsenault51818c12017-01-10 23:32:04 +0000515 TRI->getRegClass(FoldDesc.OpInfo[0].RegClass);
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000516
Matt Arsenault4bd72362016-12-10 00:39:12 +0000517
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000518 // Split 64-bit constants into 32-bits for folding.
519 if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
520 unsigned UseReg = UseOp.getReg();
521 const TargetRegisterClass *UseRC
522 = TargetRegisterInfo::isVirtualRegister(UseReg) ?
Matt Arsenault51818c12017-01-10 23:32:04 +0000523 MRI->getRegClass(UseReg) :
524 TRI->getPhysRegClass(UseReg);
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000525
526 if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
527 return;
528
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000529 APInt Imm(64, OpToFold.getImm());
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000530 if (UseOp.getSubReg() == AMDGPU::sub0) {
531 Imm = Imm.getLoBits(32);
532 } else {
533 assert(UseOp.getSubReg() == AMDGPU::sub1);
534 Imm = Imm.getHiBits(32);
535 }
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000536
537 MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
538 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII);
539 return;
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000540 }
541
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000542
543
544 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000545}
546
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000547static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
Matt Arsenault51818c12017-01-10 23:32:04 +0000548 uint32_t LHS, uint32_t RHS) {
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000549 switch (Opcode) {
550 case AMDGPU::V_AND_B32_e64:
Matt Arsenault51818c12017-01-10 23:32:04 +0000551 case AMDGPU::V_AND_B32_e32:
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000552 case AMDGPU::S_AND_B32:
553 Result = LHS & RHS;
554 return true;
555 case AMDGPU::V_OR_B32_e64:
Matt Arsenault51818c12017-01-10 23:32:04 +0000556 case AMDGPU::V_OR_B32_e32:
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000557 case AMDGPU::S_OR_B32:
558 Result = LHS | RHS;
559 return true;
560 case AMDGPU::V_XOR_B32_e64:
Matt Arsenault51818c12017-01-10 23:32:04 +0000561 case AMDGPU::V_XOR_B32_e32:
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000562 case AMDGPU::S_XOR_B32:
563 Result = LHS ^ RHS;
564 return true;
Matt Arsenault51818c12017-01-10 23:32:04 +0000565 case AMDGPU::V_LSHL_B32_e64:
566 case AMDGPU::V_LSHL_B32_e32:
567 case AMDGPU::S_LSHL_B32:
568 // The instruction ignores the high bits for out of bounds shifts.
569 Result = LHS << (RHS & 31);
570 return true;
571 case AMDGPU::V_LSHLREV_B32_e64:
572 case AMDGPU::V_LSHLREV_B32_e32:
573 Result = RHS << (LHS & 31);
574 return true;
575 case AMDGPU::V_LSHR_B32_e64:
576 case AMDGPU::V_LSHR_B32_e32:
577 case AMDGPU::S_LSHR_B32:
578 Result = LHS >> (RHS & 31);
579 return true;
580 case AMDGPU::V_LSHRREV_B32_e64:
581 case AMDGPU::V_LSHRREV_B32_e32:
582 Result = RHS >> (LHS & 31);
583 return true;
584 case AMDGPU::V_ASHR_I32_e64:
585 case AMDGPU::V_ASHR_I32_e32:
586 case AMDGPU::S_ASHR_I32:
587 Result = static_cast<int32_t>(LHS) >> (RHS & 31);
588 return true;
589 case AMDGPU::V_ASHRREV_I32_e64:
590 case AMDGPU::V_ASHRREV_I32_e32:
591 Result = static_cast<int32_t>(RHS) >> (LHS & 31);
592 return true;
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000593 default:
594 return false;
595 }
596}
597
598static unsigned getMovOpc(bool IsScalar) {
599 return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
600}
601
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000602/// Remove any leftover implicit operands from mutating the instruction. e.g.
603/// if we replace an s_and_b32 with a copy, we don't need the implicit scc def
604/// anymore.
605static void stripExtraCopyOperands(MachineInstr &MI) {
606 const MCInstrDesc &Desc = MI.getDesc();
607 unsigned NumOps = Desc.getNumOperands() +
608 Desc.getNumImplicitUses() +
609 Desc.getNumImplicitDefs();
610
611 for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
612 MI.RemoveOperand(I);
613}
614
615static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
616 MI.setDesc(NewDesc);
617 stripExtraCopyOperands(MI);
618}
619
Matt Arsenault51818c12017-01-10 23:32:04 +0000620static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI,
621 MachineOperand &Op) {
622 if (Op.isReg()) {
623 // If this has a subregister, it obviously is a register source.
Matt Arsenaultcbda7ff2018-03-10 16:05:35 +0000624 if (Op.getSubReg() != AMDGPU::NoSubRegister ||
625 !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
Matt Arsenault51818c12017-01-10 23:32:04 +0000626 return &Op;
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000627
Matt Arsenault51818c12017-01-10 23:32:04 +0000628 MachineInstr *Def = MRI.getVRegDef(Op.getReg());
Matt Arsenault7f67b352017-06-20 18:28:02 +0000629 if (Def && Def->isMoveImmediate()) {
Matt Arsenault51818c12017-01-10 23:32:04 +0000630 MachineOperand &ImmSrc = Def->getOperand(1);
631 if (ImmSrc.isImm())
632 return &ImmSrc;
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000633 }
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000634 }
635
Matt Arsenault51818c12017-01-10 23:32:04 +0000636 return &Op;
637}
638
639// Try to simplify operations with a constant that may appear after instruction
640// selection.
641// TODO: See if a frame index with a fixed offset can fold.
642static bool tryConstantFoldOp(MachineRegisterInfo &MRI,
643 const SIInstrInfo *TII,
644 MachineInstr *MI,
645 MachineOperand *ImmOp) {
646 unsigned Opc = MI->getOpcode();
647 if (Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
648 Opc == AMDGPU::S_NOT_B32) {
649 MI->getOperand(1).ChangeToImmediate(~ImmOp->getImm());
650 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
651 return true;
652 }
653
654 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
655 if (Src1Idx == -1)
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000656 return false;
657
658 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
Matt Arsenault51818c12017-01-10 23:32:04 +0000659 MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx));
660 MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx));
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000661
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000662 if (!Src0->isImm() && !Src1->isImm())
663 return false;
664
Matt Arsenault0d1b3932018-08-06 15:40:20 +0000665 if (MI->getOpcode() == AMDGPU::V_LSHL_OR_B32) {
666 if (Src0->isImm() && Src0->getImm() == 0) {
667 // v_lshl_or_b32 0, X, Y -> copy Y
668 // v_lshl_or_b32 0, X, K -> v_mov_b32 K
669 bool UseCopy = TII->getNamedOperand(*MI, AMDGPU::OpName::src2)->isReg();
670 MI->RemoveOperand(Src1Idx);
671 MI->RemoveOperand(Src0Idx);
672
673 MI->setDesc(TII->get(UseCopy ? AMDGPU::COPY : AMDGPU::V_MOV_B32_e32));
674 return true;
675 }
676 }
677
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000678 // and k0, k1 -> v_mov_b32 (k0 & k1)
679 // or k0, k1 -> v_mov_b32 (k0 | k1)
680 // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
681 if (Src0->isImm() && Src1->isImm()) {
682 int32_t NewImm;
683 if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
684 return false;
685
686 const SIRegisterInfo &TRI = TII->getRegisterInfo();
687 bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg());
688
Matt Arsenault51818c12017-01-10 23:32:04 +0000689 // Be careful to change the right operand, src0 may belong to a different
690 // instruction.
691 MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000692 MI->RemoveOperand(Src1Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000693 mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000694 return true;
695 }
696
Matt Arsenault51818c12017-01-10 23:32:04 +0000697 if (!MI->isCommutable())
698 return false;
699
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000700 if (Src0->isImm() && !Src1->isImm()) {
701 std::swap(Src0, Src1);
702 std::swap(Src0Idx, Src1Idx);
703 }
704
705 int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
Matt Arsenault51818c12017-01-10 23:32:04 +0000706 if (Opc == AMDGPU::V_OR_B32_e64 ||
707 Opc == AMDGPU::V_OR_B32_e32 ||
708 Opc == AMDGPU::S_OR_B32) {
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000709 if (Src1Val == 0) {
710 // y = or x, 0 => y = copy x
711 MI->RemoveOperand(Src1Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000712 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000713 } else if (Src1Val == -1) {
714 // y = or x, -1 => y = v_mov_b32 -1
715 MI->RemoveOperand(Src1Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000716 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000717 } else
718 return false;
719
720 return true;
721 }
722
723 if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 ||
Matt Arsenault51818c12017-01-10 23:32:04 +0000724 MI->getOpcode() == AMDGPU::V_AND_B32_e32 ||
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000725 MI->getOpcode() == AMDGPU::S_AND_B32) {
726 if (Src1Val == 0) {
727 // y = and x, 0 => y = v_mov_b32 0
728 MI->RemoveOperand(Src0Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000729 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000730 } else if (Src1Val == -1) {
731 // y = and x, -1 => y = copy x
732 MI->RemoveOperand(Src1Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000733 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
734 stripExtraCopyOperands(*MI);
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000735 } else
736 return false;
737
738 return true;
739 }
740
741 if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 ||
Matt Arsenault51818c12017-01-10 23:32:04 +0000742 MI->getOpcode() == AMDGPU::V_XOR_B32_e32 ||
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000743 MI->getOpcode() == AMDGPU::S_XOR_B32) {
744 if (Src1Val == 0) {
745 // y = xor x, 0 => y = copy x
746 MI->RemoveOperand(Src1Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000747 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
Matt Arsenault51818c12017-01-10 23:32:04 +0000748 return true;
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000749 }
750 }
751
752 return false;
753}
754
Stanislav Mekhanoshin70603dc2017-03-24 18:55:20 +0000755// Try to fold an instruction into a simpler one
756static bool tryFoldInst(const SIInstrInfo *TII,
757 MachineInstr *MI) {
758 unsigned Opc = MI->getOpcode();
759
760 if (Opc == AMDGPU::V_CNDMASK_B32_e32 ||
761 Opc == AMDGPU::V_CNDMASK_B32_e64 ||
762 Opc == AMDGPU::V_CNDMASK_B64_PSEUDO) {
763 const MachineOperand *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
764 const MachineOperand *Src1 = TII->getNamedOperand(*MI, AMDGPU::OpName::src1);
765 if (Src1->isIdenticalTo(*Src0)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000766 LLVM_DEBUG(dbgs() << "Folded " << *MI << " into ");
Stanislav Mekhanoshin70603dc2017-03-24 18:55:20 +0000767 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
768 if (Src2Idx != -1)
769 MI->RemoveOperand(Src2Idx);
770 MI->RemoveOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
771 mutateCopyOp(*MI, TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY
772 : getMovOpc(false)));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000773 LLVM_DEBUG(dbgs() << *MI << '\n');
Stanislav Mekhanoshin70603dc2017-03-24 18:55:20 +0000774 return true;
775 }
776 }
777
778 return false;
779}
780
Matt Arsenault51818c12017-01-10 23:32:04 +0000781void SIFoldOperands::foldInstOperand(MachineInstr &MI,
782 MachineOperand &OpToFold) const {
783 // We need mutate the operands of new mov instructions to add implicit
784 // uses of EXEC, but adding them invalidates the use_iterator, so defer
785 // this.
786 SmallVector<MachineInstr *, 4> CopiesToReplace;
787 SmallVector<FoldCandidate, 4> FoldList;
788 MachineOperand &Dst = MI.getOperand(0);
789
790 bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
791 if (FoldingImm) {
792 unsigned NumLiteralUses = 0;
793 MachineOperand *NonInlineUse = nullptr;
794 int NonInlineUseOpNo = -1;
795
Vitaly Buka74503982017-10-15 05:35:02 +0000796 MachineRegisterInfo::use_iterator NextUse;
Matt Arsenault51818c12017-01-10 23:32:04 +0000797 for (MachineRegisterInfo::use_iterator
798 Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
799 Use != E; Use = NextUse) {
800 NextUse = std::next(Use);
801 MachineInstr *UseMI = Use->getParent();
802 unsigned OpNo = Use.getOperandNo();
803
804 // Folding the immediate may reveal operations that can be constant
805 // folded or replaced with a copy. This can happen for example after
806 // frame indices are lowered to constants or from splitting 64-bit
807 // constants.
808 //
809 // We may also encounter cases where one or both operands are
810 // immediates materialized into a register, which would ordinarily not
811 // be folded due to multiple uses or operand constraints.
812
813 if (OpToFold.isImm() && tryConstantFoldOp(*MRI, TII, UseMI, &OpToFold)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000814 LLVM_DEBUG(dbgs() << "Constant folded " << *UseMI << '\n');
Matt Arsenault51818c12017-01-10 23:32:04 +0000815
816 // Some constant folding cases change the same immediate's use to a new
817 // instruction, e.g. and x, 0 -> 0. Make sure we re-visit the user
818 // again. The same constant folded instruction could also have a second
819 // use operand.
820 NextUse = MRI->use_begin(Dst.getReg());
Nicolai Haehnlea253e4c2017-07-18 14:54:41 +0000821 FoldList.clear();
Matt Arsenault51818c12017-01-10 23:32:04 +0000822 continue;
823 }
824
825 // Try to fold any inline immediate uses, and then only fold other
826 // constants if they have one use.
827 //
828 // The legality of the inline immediate must be checked based on the use
829 // operand, not the defining instruction, because 32-bit instructions
830 // with 32-bit inline immediate sources may be used to materialize
831 // constants used in 16-bit operands.
832 //
833 // e.g. it is unsafe to fold:
834 // s_mov_b32 s0, 1.0 // materializes 0x3f800000
835 // v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00
836
837 // Folding immediates with more than one use will increase program size.
838 // FIXME: This will also reduce register usage, which may be better
839 // in some cases. A better heuristic is needed.
Matt Arsenault69e30012017-01-11 22:00:02 +0000840 if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) {
Matt Arsenault51818c12017-01-10 23:32:04 +0000841 foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
842 } else {
843 if (++NumLiteralUses == 1) {
844 NonInlineUse = &*Use;
845 NonInlineUseOpNo = OpNo;
846 }
847 }
848 }
849
850 if (NumLiteralUses == 1) {
851 MachineInstr *UseMI = NonInlineUse->getParent();
852 foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace);
853 }
854 } else {
855 // Folding register.
Alexander Timofeev993e2792019-01-03 19:55:32 +0000856 SmallVector <MachineRegisterInfo::use_iterator, 4> UsesToProcess;
Matt Arsenault51818c12017-01-10 23:32:04 +0000857 for (MachineRegisterInfo::use_iterator
858 Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
859 Use != E; ++Use) {
Alexander Timofeev993e2792019-01-03 19:55:32 +0000860 UsesToProcess.push_back(Use);
861 }
862 for (auto U : UsesToProcess) {
863 MachineInstr *UseMI = U->getParent();
Matt Arsenault51818c12017-01-10 23:32:04 +0000864
Alexander Timofeev993e2792019-01-03 19:55:32 +0000865 foldOperand(OpToFold, UseMI, U.getOperandNo(),
866 FoldList, CopiesToReplace);
Matt Arsenault51818c12017-01-10 23:32:04 +0000867 }
868 }
869
870 MachineFunction *MF = MI.getParent()->getParent();
871 // Make sure we add EXEC uses to any new v_mov instructions created.
872 for (MachineInstr *Copy : CopiesToReplace)
873 Copy->addImplicitDefUseOperands(*MF);
874
875 for (FoldCandidate &Fold : FoldList) {
Matt Arsenaultde6c4212018-08-28 18:34:24 +0000876 if (updateOperand(Fold, *TII, *TRI)) {
Matt Arsenault51818c12017-01-10 23:32:04 +0000877 // Clear kill flags.
878 if (Fold.isReg()) {
879 assert(Fold.OpToFold && Fold.OpToFold->isReg());
880 // FIXME: Probably shouldn't bother trying to fold if not an
881 // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
882 // copies.
883 MRI->clearKillFlags(Fold.OpToFold->getReg());
884 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000885 LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
886 << static_cast<int>(Fold.UseOpNo) << " of "
887 << *Fold.UseMI << '\n');
Stanislav Mekhanoshin70603dc2017-03-24 18:55:20 +0000888 tryFoldInst(TII, Fold.UseMI);
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +0000889 } else if (Fold.isCommuted()) {
890 // Restoring instruction's original operand order if fold has failed.
891 TII->commuteInstruction(*Fold.UseMI, false);
Matt Arsenault51818c12017-01-10 23:32:04 +0000892 }
893 }
894}
895
Matt Arsenaultf48e5c92017-10-05 00:13:20 +0000896// Clamp patterns are canonically selected to v_max_* instructions, so only
897// handle them.
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000898const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
899 unsigned Op = MI.getOpcode();
900 switch (Op) {
901 case AMDGPU::V_MAX_F32_e64:
Matt Arsenault79a45db2017-02-22 23:53:37 +0000902 case AMDGPU::V_MAX_F16_e64:
Matt Arsenaultab4a5cd2017-08-31 23:53:50 +0000903 case AMDGPU::V_MAX_F64:
904 case AMDGPU::V_PK_MAX_F16: {
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000905 if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
906 return nullptr;
907
908 // Make sure sources are identical.
909 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
910 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
Stanislav Mekhanoshin286a4222017-06-05 01:03:04 +0000911 if (!Src0->isReg() || !Src1->isReg() ||
Matt Arsenaultaafff872017-10-05 00:13:17 +0000912 Src0->getReg() != Src1->getReg() ||
Stanislav Mekhanoshin286a4222017-06-05 01:03:04 +0000913 Src0->getSubReg() != Src1->getSubReg() ||
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000914 Src0->getSubReg() != AMDGPU::NoSubRegister)
915 return nullptr;
916
917 // Can't fold up if we have modifiers.
Matt Arsenaultab4a5cd2017-08-31 23:53:50 +0000918 if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
919 return nullptr;
920
921 unsigned Src0Mods
922 = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
923 unsigned Src1Mods
924 = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
925
926 // Having a 0 op_sel_hi would require swizzling the output in the source
927 // instruction, which we can't do.
Stanislav Mekhanoshinda644c02019-03-13 21:15:52 +0000928 unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1
929 : 0u;
Matt Arsenaultab4a5cd2017-08-31 23:53:50 +0000930 if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000931 return nullptr;
932 return Src0;
933 }
934 default:
935 return nullptr;
936 }
937}
938
939// We obviously have multiple uses in a clamp since the register is used twice
940// in the same instruction.
941static bool hasOneNonDBGUseInst(const MachineRegisterInfo &MRI, unsigned Reg) {
942 int Count = 0;
943 for (auto I = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
944 I != E; ++I) {
945 if (++Count > 1)
946 return false;
947 }
948
949 return true;
950}
951
Matt Arsenault8cbb4882017-09-20 21:01:24 +0000952// FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000953bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
954 const MachineOperand *ClampSrc = isClamp(MI);
955 if (!ClampSrc || !hasOneNonDBGUseInst(*MRI, ClampSrc->getReg()))
956 return false;
957
958 MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
Matt Arsenaultab4a5cd2017-08-31 23:53:50 +0000959
960 // The type of clamp must be compatible.
961 if (TII->getClampMask(*Def) != TII->getClampMask(MI))
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000962 return false;
Matt Arsenaultab4a5cd2017-08-31 23:53:50 +0000963
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000964 MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
965 if (!DefClamp)
966 return false;
967
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000968 LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def
969 << '\n');
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000970
971 // Clamp is applied after omod, so it is OK if omod is set.
972 DefClamp->setImm(1);
973 MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
974 MI.eraseFromParent();
975 return true;
976}
977
Matt Arsenault3cb39042017-02-27 19:35:42 +0000978static int getOModValue(unsigned Opc, int64_t Val) {
979 switch (Opc) {
980 case AMDGPU::V_MUL_F32_e64: {
981 switch (static_cast<uint32_t>(Val)) {
982 case 0x3f000000: // 0.5
983 return SIOutMods::DIV2;
984 case 0x40000000: // 2.0
985 return SIOutMods::MUL2;
986 case 0x40800000: // 4.0
987 return SIOutMods::MUL4;
988 default:
989 return SIOutMods::NONE;
990 }
991 }
992 case AMDGPU::V_MUL_F16_e64: {
993 switch (static_cast<uint16_t>(Val)) {
994 case 0x3800: // 0.5
995 return SIOutMods::DIV2;
996 case 0x4000: // 2.0
997 return SIOutMods::MUL2;
998 case 0x4400: // 4.0
999 return SIOutMods::MUL4;
1000 default:
1001 return SIOutMods::NONE;
1002 }
1003 }
1004 default:
1005 llvm_unreachable("invalid mul opcode");
1006 }
1007}
1008
1009// FIXME: Does this really not support denormals with f16?
1010// FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
1011// handled, so will anything other than that break?
1012std::pair<const MachineOperand *, int>
1013SIFoldOperands::isOMod(const MachineInstr &MI) const {
1014 unsigned Op = MI.getOpcode();
1015 switch (Op) {
1016 case AMDGPU::V_MUL_F32_e64:
1017 case AMDGPU::V_MUL_F16_e64: {
1018 // If output denormals are enabled, omod is ignored.
1019 if ((Op == AMDGPU::V_MUL_F32_e64 && ST->hasFP32Denormals()) ||
1020 (Op == AMDGPU::V_MUL_F16_e64 && ST->hasFP16Denormals()))
1021 return std::make_pair(nullptr, SIOutMods::NONE);
1022
1023 const MachineOperand *RegOp = nullptr;
1024 const MachineOperand *ImmOp = nullptr;
1025 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1026 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1027 if (Src0->isImm()) {
1028 ImmOp = Src0;
1029 RegOp = Src1;
1030 } else if (Src1->isImm()) {
1031 ImmOp = Src1;
1032 RegOp = Src0;
1033 } else
1034 return std::make_pair(nullptr, SIOutMods::NONE);
1035
1036 int OMod = getOModValue(Op, ImmOp->getImm());
1037 if (OMod == SIOutMods::NONE ||
1038 TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1039 TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
1040 TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
1041 TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
1042 return std::make_pair(nullptr, SIOutMods::NONE);
1043
1044 return std::make_pair(RegOp, OMod);
1045 }
1046 case AMDGPU::V_ADD_F32_e64:
1047 case AMDGPU::V_ADD_F16_e64: {
1048 // If output denormals are enabled, omod is ignored.
1049 if ((Op == AMDGPU::V_ADD_F32_e64 && ST->hasFP32Denormals()) ||
1050 (Op == AMDGPU::V_ADD_F16_e64 && ST->hasFP16Denormals()))
1051 return std::make_pair(nullptr, SIOutMods::NONE);
1052
1053 // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
1054 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1055 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1056
1057 if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
1058 Src0->getSubReg() == Src1->getSubReg() &&
1059 !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
1060 !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
1061 !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
1062 !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1063 return std::make_pair(Src0, SIOutMods::MUL2);
1064
1065 return std::make_pair(nullptr, SIOutMods::NONE);
1066 }
1067 default:
1068 return std::make_pair(nullptr, SIOutMods::NONE);
1069 }
1070}
1071
1072// FIXME: Does this need to check IEEE bit on function?
1073bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
1074 const MachineOperand *RegOp;
1075 int OMod;
1076 std::tie(RegOp, OMod) = isOMod(MI);
1077 if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
1078 RegOp->getSubReg() != AMDGPU::NoSubRegister ||
1079 !hasOneNonDBGUseInst(*MRI, RegOp->getReg()))
1080 return false;
1081
1082 MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
1083 MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
1084 if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
1085 return false;
1086
1087 // Clamp is applied after omod. If the source already has clamp set, don't
1088 // fold it.
1089 if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
1090 return false;
1091
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001092 LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def << '\n');
Matt Arsenault3cb39042017-02-27 19:35:42 +00001093
1094 DefOMod->setImm(OMod);
1095 MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1096 MI.eraseFromParent();
1097 return true;
1098}
1099
Tom Stellard6596ba72014-11-21 22:06:37 +00001100bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001101 if (skipFunction(MF.getFunction()))
Andrew Kaylor7de74af2016-04-25 22:23:44 +00001102 return false;
1103
Matt Arsenault51818c12017-01-10 23:32:04 +00001104 MRI = &MF.getRegInfo();
Tom Stellard5bfbae52018-07-11 20:59:01 +00001105 ST = &MF.getSubtarget<GCNSubtarget>();
Matt Arsenaultd5c65152017-02-22 23:27:53 +00001106 TII = ST->getInstrInfo();
Matt Arsenault51818c12017-01-10 23:32:04 +00001107 TRI = &TII->getRegisterInfo();
Tom Stellard6596ba72014-11-21 22:06:37 +00001108
Matt Arsenault3cb39042017-02-27 19:35:42 +00001109 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1110
1111 // omod is ignored by hardware if IEEE bit is enabled. omod also does not
1112 // correctly handle signed zeros.
1113 //
Matt Arsenault13b0db92018-08-12 08:44:25 +00001114 bool IsIEEEMode = ST->enableIEEEBit(MF);
1115 bool HasNSZ = MFI->hasNoSignedZerosFPMath();
Matt Arsenault3cb39042017-02-27 19:35:42 +00001116
Matt Arsenaultff3f9122017-06-20 18:56:32 +00001117 for (MachineBasicBlock *MBB : depth_first(&MF)) {
Tom Stellard6596ba72014-11-21 22:06:37 +00001118 MachineBasicBlock::iterator I, Next;
Matt Arsenaultff3f9122017-06-20 18:56:32 +00001119 for (I = MBB->begin(); I != MBB->end(); I = Next) {
Tom Stellard6596ba72014-11-21 22:06:37 +00001120 Next = std::next(I);
1121 MachineInstr &MI = *I;
1122
Stanislav Mekhanoshin70603dc2017-03-24 18:55:20 +00001123 tryFoldInst(TII, &MI);
1124
Sam Kolton27e0f8b2017-03-31 11:42:43 +00001125 if (!TII->isFoldableCopy(MI)) {
Matt Arsenault13b0db92018-08-12 08:44:25 +00001126 // TODO: Omod might be OK if there is NSZ only on the source
1127 // instruction, and not the omod multiply.
1128 if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) ||
1129 !tryFoldOMod(MI))
Matt Arsenault3cb39042017-02-27 19:35:42 +00001130 tryFoldClamp(MI);
Tom Stellard6596ba72014-11-21 22:06:37 +00001131 continue;
Matt Arsenaultd5c65152017-02-22 23:27:53 +00001132 }
Tom Stellard6596ba72014-11-21 22:06:37 +00001133
1134 MachineOperand &OpToFold = MI.getOperand(1);
Matt Arsenault2bc198a2016-09-14 15:51:33 +00001135 bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
Tom Stellard26cc18d2015-01-07 22:18:27 +00001136
Matt Arsenault51818c12017-01-10 23:32:04 +00001137 // FIXME: We could also be folding things like TargetIndexes.
Tom Stellard05992972015-01-07 22:44:19 +00001138 if (!FoldingImm && !OpToFold.isReg())
1139 continue;
1140
Tom Stellard6596ba72014-11-21 22:06:37 +00001141 if (OpToFold.isReg() &&
Nicolai Haehnle82fc9622016-01-07 17:10:29 +00001142 !TargetRegisterInfo::isVirtualRegister(OpToFold.getReg()))
Tom Stellard6596ba72014-11-21 22:06:37 +00001143 continue;
1144
Marek Olsak926c56f2016-01-13 11:44:29 +00001145 // Prevent folding operands backwards in the function. For example,
1146 // the COPY opcode must not be replaced by 1 in this example:
1147 //
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +00001148 // %3 = COPY %vgpr0; VGPR_32:%3
Marek Olsak926c56f2016-01-13 11:44:29 +00001149 // ...
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +00001150 // %vgpr0 = V_MOV_B32_e32 1, implicit %exec
Marek Olsak926c56f2016-01-13 11:44:29 +00001151 MachineOperand &Dst = MI.getOperand(0);
1152 if (Dst.isReg() &&
1153 !TargetRegisterInfo::isVirtualRegister(Dst.getReg()))
1154 continue;
1155
Matt Arsenault51818c12017-01-10 23:32:04 +00001156 foldInstOperand(MI, OpToFold);
Tom Stellard6596ba72014-11-21 22:06:37 +00001157 }
1158 }
1159 return false;
1160}