LLVM 17.0.0git
SIFoldOperands.cpp
Go to the documentation of this file.
1//===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7/// \file
8//===----------------------------------------------------------------------===//
9//
10
11#include "AMDGPU.h"
12#include "GCNSubtarget.h"
18
19#define DEBUG_TYPE "si-fold-operands"
20using namespace llvm;
21
22namespace {
23
24struct FoldCandidate {
26 union {
27 MachineOperand *OpToFold;
28 uint64_t ImmToFold;
29 int FrameIndexToFold;
30 };
31 int ShrinkOpcode;
32 unsigned UseOpNo;
34 bool Commuted;
35
36 FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp,
37 bool Commuted_ = false,
38 int ShrinkOp = -1) :
39 UseMI(MI), OpToFold(nullptr), ShrinkOpcode(ShrinkOp), UseOpNo(OpNo),
40 Kind(FoldOp->getType()),
41 Commuted(Commuted_) {
42 if (FoldOp->isImm()) {
43 ImmToFold = FoldOp->getImm();
44 } else if (FoldOp->isFI()) {
45 FrameIndexToFold = FoldOp->getIndex();
46 } else {
47 assert(FoldOp->isReg() || FoldOp->isGlobal());
48 OpToFold = FoldOp;
49 }
50 }
51
52 bool isFI() const {
53 return Kind == MachineOperand::MO_FrameIndex;
54 }
55
56 bool isImm() const {
57 return Kind == MachineOperand::MO_Immediate;
58 }
59
60 bool isReg() const {
61 return Kind == MachineOperand::MO_Register;
62 }
63
64 bool isGlobal() const { return Kind == MachineOperand::MO_GlobalAddress; }
65
66 bool needsShrink() const { return ShrinkOpcode != -1; }
67};
68
69class SIFoldOperands : public MachineFunctionPass {
70public:
71 static char ID;
73 const SIInstrInfo *TII;
74 const SIRegisterInfo *TRI;
75 const GCNSubtarget *ST;
76 const SIMachineFunctionInfo *MFI;
77
78 bool frameIndexMayFold(const MachineInstr &UseMI, int OpNo,
79 const MachineOperand &OpToFold) const;
80
81 bool updateOperand(FoldCandidate &Fold) const;
82
83 bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
84 MachineInstr *MI, unsigned OpNo,
85 MachineOperand *OpToFold) const;
86 bool isUseSafeToFold(const MachineInstr &MI,
87 const MachineOperand &UseMO) const;
88 bool
89 getRegSeqInit(SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs,
90 Register UseReg, uint8_t OpTy) const;
91 bool tryToFoldACImm(const MachineOperand &OpToFold, MachineInstr *UseMI,
92 unsigned UseOpIdx,
93 SmallVectorImpl<FoldCandidate> &FoldList) const;
94 void foldOperand(MachineOperand &OpToFold,
96 int UseOpIdx,
98 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
99
100 MachineOperand *getImmOrMaterializedImm(MachineOperand &Op) const;
101 bool tryConstantFoldOp(MachineInstr *MI) const;
102 bool tryFoldCndMask(MachineInstr &MI) const;
103 bool tryFoldZeroHighBits(MachineInstr &MI) const;
104 bool foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const;
105 bool tryFoldFoldableCopy(MachineInstr &MI,
106 MachineOperand *&CurrentKnownM0Val) const;
107
108 const MachineOperand *isClamp(const MachineInstr &MI) const;
109 bool tryFoldClamp(MachineInstr &MI);
110
111 std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
112 bool tryFoldOMod(MachineInstr &MI);
113 bool tryFoldRegSequence(MachineInstr &MI);
114 bool tryFoldLCSSAPhi(MachineInstr &MI);
115 bool tryFoldLoad(MachineInstr &MI);
116
117public:
118 SIFoldOperands() : MachineFunctionPass(ID) {
120 }
121
122 bool runOnMachineFunction(MachineFunction &MF) override;
123
124 StringRef getPassName() const override { return "SI Fold Operands"; }
125
126 void getAnalysisUsage(AnalysisUsage &AU) const override {
127 AU.setPreservesCFG();
129 }
130};
131
132} // End anonymous namespace.
133
134INITIALIZE_PASS(SIFoldOperands, DEBUG_TYPE,
135 "SI Fold Operands", false, false)
136
137char SIFoldOperands::ID = 0;
138
139char &llvm::SIFoldOperandsID = SIFoldOperands::ID;
140
141// Map multiply-accumulate opcode to corresponding multiply-add opcode if any.
142static unsigned macToMad(unsigned Opc) {
143 switch (Opc) {
144 case AMDGPU::V_MAC_F32_e64:
145 return AMDGPU::V_MAD_F32_e64;
146 case AMDGPU::V_MAC_F16_e64:
147 return AMDGPU::V_MAD_F16_e64;
148 case AMDGPU::V_FMAC_F32_e64:
149 return AMDGPU::V_FMA_F32_e64;
150 case AMDGPU::V_FMAC_F16_e64:
151 return AMDGPU::V_FMA_F16_gfx9_e64;
152 case AMDGPU::V_FMAC_F16_t16_e64:
153 return AMDGPU::V_FMA_F16_gfx9_e64;
154 case AMDGPU::V_FMAC_LEGACY_F32_e64:
155 return AMDGPU::V_FMA_LEGACY_F32_e64;
156 case AMDGPU::V_FMAC_F64_e64:
157 return AMDGPU::V_FMA_F64_e64;
158 }
159 return AMDGPU::INSTRUCTION_LIST_END;
160}
161
162// TODO: Add heuristic that the frame index might not fit in the addressing mode
163// immediate offset to avoid materializing in loops.
164bool SIFoldOperands::frameIndexMayFold(const MachineInstr &UseMI, int OpNo,
165 const MachineOperand &OpToFold) const {
166 if (!OpToFold.isFI())
167 return false;
168
169 const unsigned Opc = UseMI.getOpcode();
170 if (TII->isMUBUF(UseMI))
171 return OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
172 if (!TII->isFLATScratch(UseMI))
173 return false;
174
175 int SIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::saddr);
176 if (OpNo == SIdx)
177 return true;
178
179 int VIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
180 return OpNo == VIdx && SIdx == -1;
181}
182
184 return new SIFoldOperands();
185}
186
187bool SIFoldOperands::updateOperand(FoldCandidate &Fold) const {
188 MachineInstr *MI = Fold.UseMI;
189 MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
190 assert(Old.isReg());
191
192
193 const uint64_t TSFlags = MI->getDesc().TSFlags;
194 if (Fold.isImm()) {
196 (!ST->hasDOTOpSelHazard() || !(TSFlags & SIInstrFlags::IsDOT)) &&
197 AMDGPU::isFoldableLiteralV216(Fold.ImmToFold,
198 ST->hasInv2PiInlineImm())) {
199 // Set op_sel/op_sel_hi on this operand or bail out if op_sel is
200 // already set.
201 unsigned Opcode = MI->getOpcode();
202 int OpNo = MI->getOperandNo(&Old);
203 int ModIdx = -1;
204 if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0))
205 ModIdx = AMDGPU::OpName::src0_modifiers;
206 else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1))
207 ModIdx = AMDGPU::OpName::src1_modifiers;
208 else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2))
209 ModIdx = AMDGPU::OpName::src2_modifiers;
210 assert(ModIdx != -1);
211 ModIdx = AMDGPU::getNamedOperandIdx(Opcode, ModIdx);
212 MachineOperand &Mod = MI->getOperand(ModIdx);
213 unsigned Val = Mod.getImm();
214 if (!(Val & SISrcMods::OP_SEL_0) && (Val & SISrcMods::OP_SEL_1)) {
215 // Only apply the following transformation if that operand requires
216 // a packed immediate.
217 switch (TII->get(Opcode).operands()[OpNo].OperandType) {
218 case AMDGPU::OPERAND_REG_IMM_V2FP16:
219 case AMDGPU::OPERAND_REG_IMM_V2INT16:
220 case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
221 case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
222 // If upper part is all zero we do not need op_sel_hi.
223 if (!isUInt<16>(Fold.ImmToFold)) {
224 if (!(Fold.ImmToFold & 0xffff)) {
225 Mod.setImm(Mod.getImm() | SISrcMods::OP_SEL_0);
226 Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
227 Old.ChangeToImmediate((Fold.ImmToFold >> 16) & 0xffff);
228 return true;
229 }
230 Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
231 Old.ChangeToImmediate(Fold.ImmToFold & 0xffff);
232 return true;
233 }
234 break;
235 default:
236 break;
237 }
238 }
239 }
240 }
241
242 if ((Fold.isImm() || Fold.isFI() || Fold.isGlobal()) && Fold.needsShrink()) {
243 MachineBasicBlock *MBB = MI->getParent();
244 auto Liveness = MBB->computeRegisterLiveness(TRI, AMDGPU::VCC, MI, 16);
245 if (Liveness != MachineBasicBlock::LQR_Dead) {
246 LLVM_DEBUG(dbgs() << "Not shrinking " << MI << " due to vcc liveness\n");
247 return false;
248 }
249
250 int Op32 = Fold.ShrinkOpcode;
251 MachineOperand &Dst0 = MI->getOperand(0);
252 MachineOperand &Dst1 = MI->getOperand(1);
253 assert(Dst0.isDef() && Dst1.isDef());
254
255 bool HaveNonDbgCarryUse = !MRI->use_nodbg_empty(Dst1.getReg());
256
257 const TargetRegisterClass *Dst0RC = MRI->getRegClass(Dst0.getReg());
258 Register NewReg0 = MRI->createVirtualRegister(Dst0RC);
259
260 MachineInstr *Inst32 = TII->buildShrunkInst(*MI, Op32);
261
262 if (HaveNonDbgCarryUse) {
263 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(AMDGPU::COPY),
264 Dst1.getReg())
265 .addReg(AMDGPU::VCC, RegState::Kill);
266 }
267
268 // Keep the old instruction around to avoid breaking iterators, but
269 // replace it with a dummy instruction to remove uses.
270 //
271 // FIXME: We should not invert how this pass looks at operands to avoid
272 // this. Should track set of foldable movs instead of looking for uses
273 // when looking at a use.
274 Dst0.setReg(NewReg0);
275 for (unsigned I = MI->getNumOperands() - 1; I > 0; --I)
276 MI->removeOperand(I);
277 MI->setDesc(TII->get(AMDGPU::IMPLICIT_DEF));
278
279 if (Fold.Commuted)
280 TII->commuteInstruction(*Inst32, false);
281 return true;
282 }
283
284 assert(!Fold.needsShrink() && "not handled");
285
286 if (Fold.isImm()) {
287 if (Old.isTied()) {
288 int NewMFMAOpc = AMDGPU::getMFMAEarlyClobberOp(MI->getOpcode());
289 if (NewMFMAOpc == -1)
290 return false;
291 MI->setDesc(TII->get(NewMFMAOpc));
292 MI->untieRegOperand(0);
293 }
294 Old.ChangeToImmediate(Fold.ImmToFold);
295 return true;
296 }
297
298 if (Fold.isGlobal()) {
299 Old.ChangeToGA(Fold.OpToFold->getGlobal(), Fold.OpToFold->getOffset(),
300 Fold.OpToFold->getTargetFlags());
301 return true;
302 }
303
304 if (Fold.isFI()) {
305 Old.ChangeToFrameIndex(Fold.FrameIndexToFold);
306 return true;
307 }
308
309 MachineOperand *New = Fold.OpToFold;
310 Old.substVirtReg(New->getReg(), New->getSubReg(), *TRI);
311 Old.setIsUndef(New->isUndef());
312 return true;
313}
314
316 const MachineInstr *MI) {
317 return any_of(FoldList, [&](const auto &C) { return C.UseMI == MI; });
318}
319
321 MachineInstr *MI, unsigned OpNo,
322 MachineOperand *FoldOp, bool Commuted = false,
323 int ShrinkOp = -1) {
324 // Skip additional folding on the same operand.
325 for (FoldCandidate &Fold : FoldList)
326 if (Fold.UseMI == MI && Fold.UseOpNo == OpNo)
327 return;
328 LLVM_DEBUG(dbgs() << "Append " << (Commuted ? "commuted" : "normal")
329 << " operand " << OpNo << "\n " << *MI);
330 FoldList.emplace_back(MI, OpNo, FoldOp, Commuted, ShrinkOp);
331}
332
333bool SIFoldOperands::tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
334 MachineInstr *MI, unsigned OpNo,
335 MachineOperand *OpToFold) const {
336 if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
337 // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
338 unsigned Opc = MI->getOpcode();
339 unsigned NewOpc = macToMad(Opc);
340 if (NewOpc != AMDGPU::INSTRUCTION_LIST_END) {
341 // Check if changing this to a v_mad_{f16, f32} instruction will allow us
342 // to fold the operand.
343 MI->setDesc(TII->get(NewOpc));
344 bool AddOpSel = !AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel) &&
345 AMDGPU::hasNamedOperand(NewOpc, AMDGPU::OpName::op_sel);
346 if (AddOpSel)
347 MI->addOperand(MachineOperand::CreateImm(0));
348 bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold);
349 if (FoldAsMAD) {
350 MI->untieRegOperand(OpNo);
351 return true;
352 }
353 if (AddOpSel)
354 MI->removeOperand(MI->getNumExplicitOperands() - 1);
355 MI->setDesc(TII->get(Opc));
356 }
357
358 // Special case for s_setreg_b32
359 if (OpToFold->isImm()) {
360 unsigned ImmOpc = 0;
361 if (Opc == AMDGPU::S_SETREG_B32)
362 ImmOpc = AMDGPU::S_SETREG_IMM32_B32;
363 else if (Opc == AMDGPU::S_SETREG_B32_mode)
364 ImmOpc = AMDGPU::S_SETREG_IMM32_B32_mode;
365 if (ImmOpc) {
366 MI->setDesc(TII->get(ImmOpc));
367 appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
368 return true;
369 }
370 }
371
372 // If we are already folding into another operand of MI, then
373 // we can't commute the instruction, otherwise we risk making the
374 // other fold illegal.
375 if (isUseMIInFoldList(FoldList, MI))
376 return false;
377
378 unsigned CommuteOpNo = OpNo;
379
380 // Operand is not legal, so try to commute the instruction to
381 // see if this makes it possible to fold.
382 unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex;
383 unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
384 bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1);
385
386 if (CanCommute) {
387 if (CommuteIdx0 == OpNo)
388 CommuteOpNo = CommuteIdx1;
389 else if (CommuteIdx1 == OpNo)
390 CommuteOpNo = CommuteIdx0;
391 }
392
393
394 // One of operands might be an Imm operand, and OpNo may refer to it after
395 // the call of commuteInstruction() below. Such situations are avoided
396 // here explicitly as OpNo must be a register operand to be a candidate
397 // for memory folding.
398 if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() ||
399 !MI->getOperand(CommuteIdx1).isReg()))
400 return false;
401
402 if (!CanCommute ||
403 !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1))
404 return false;
405
406 if (!TII->isOperandLegal(*MI, CommuteOpNo, OpToFold)) {
407 if ((Opc == AMDGPU::V_ADD_CO_U32_e64 ||
408 Opc == AMDGPU::V_SUB_CO_U32_e64 ||
409 Opc == AMDGPU::V_SUBREV_CO_U32_e64) && // FIXME
410 (OpToFold->isImm() || OpToFold->isFI() || OpToFold->isGlobal())) {
411
412 // Verify the other operand is a VGPR, otherwise we would violate the
413 // constant bus restriction.
414 unsigned OtherIdx = CommuteOpNo == CommuteIdx0 ? CommuteIdx1 : CommuteIdx0;
415 MachineOperand &OtherOp = MI->getOperand(OtherIdx);
416 if (!OtherOp.isReg() ||
417 !TII->getRegisterInfo().isVGPR(*MRI, OtherOp.getReg()))
418 return false;
419
420 assert(MI->getOperand(1).isDef());
421
422 // Make sure to get the 32-bit version of the commuted opcode.
423 unsigned MaybeCommutedOpc = MI->getOpcode();
424 int Op32 = AMDGPU::getVOPe32(MaybeCommutedOpc);
425
426 appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, true, Op32);
427 return true;
428 }
429
430 TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1);
431 return false;
432 }
433
434 appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, true);
435 return true;
436 }
437
438 // Check the case where we might introduce a second constant operand to a
439 // scalar instruction
440 if (TII->isSALU(MI->getOpcode())) {
441 const MCInstrDesc &InstDesc = MI->getDesc();
442 const MCOperandInfo &OpInfo = InstDesc.operands()[OpNo];
443
444 // Fine if the operand can be encoded as an inline constant
445 if (!OpToFold->isReg() && !TII->isInlineConstant(*OpToFold, OpInfo)) {
446 // Otherwise check for another constant
447 for (unsigned i = 0, e = InstDesc.getNumOperands(); i != e; ++i) {
448 auto &Op = MI->getOperand(i);
449 if (OpNo != i && !Op.isReg() && !TII->isInlineConstant(Op, OpInfo))
450 return false;
451 }
452 }
453 }
454
455 appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
456 return true;
457}
458
459bool SIFoldOperands::isUseSafeToFold(const MachineInstr &MI,
460 const MachineOperand &UseMO) const {
461 // Operands of SDWA instructions must be registers.
462 return !TII->isSDWA(MI);
463}
464
465// Find a def of the UseReg, check if it is a reg_sequence and find initializers
466// for each subreg, tracking it to foldable inline immediate if possible.
467// Returns true on success.
468bool SIFoldOperands::getRegSeqInit(
469 SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs,
470 Register UseReg, uint8_t OpTy) const {
471 MachineInstr *Def = MRI->getVRegDef(UseReg);
472 if (!Def || !Def->isRegSequence())
473 return false;
474
475 for (unsigned I = 1, E = Def->getNumExplicitOperands(); I < E; I += 2) {
476 MachineOperand *Sub = &Def->getOperand(I);
477 assert(Sub->isReg());
478
479 for (MachineInstr *SubDef = MRI->getVRegDef(Sub->getReg());
480 SubDef && Sub->isReg() && Sub->getReg().isVirtual() &&
481 !Sub->getSubReg() && TII->isFoldableCopy(*SubDef);
482 SubDef = MRI->getVRegDef(Sub->getReg())) {
483 MachineOperand *Op = &SubDef->getOperand(1);
484 if (Op->isImm()) {
485 if (TII->isInlineConstant(*Op, OpTy))
486 Sub = Op;
487 break;
488 }
489 if (!Op->isReg() || Op->getReg().isPhysical())
490 break;
491 Sub = Op;
492 }
493
494 Defs.emplace_back(Sub, Def->getOperand(I + 1).getImm());
495 }
496
497 return true;
498}
499
500bool SIFoldOperands::tryToFoldACImm(
501 const MachineOperand &OpToFold, MachineInstr *UseMI, unsigned UseOpIdx,
502 SmallVectorImpl<FoldCandidate> &FoldList) const {
503 const MCInstrDesc &Desc = UseMI->getDesc();
504 if (UseOpIdx >= Desc.getNumOperands())
505 return false;
506
507 uint8_t OpTy = Desc.operands()[UseOpIdx].OperandType;
508 if ((OpTy < AMDGPU::OPERAND_REG_INLINE_AC_FIRST ||
509 OpTy > AMDGPU::OPERAND_REG_INLINE_AC_LAST) &&
510 (OpTy < AMDGPU::OPERAND_REG_INLINE_C_FIRST ||
511 OpTy > AMDGPU::OPERAND_REG_INLINE_C_LAST))
512 return false;
513
514 if (OpToFold.isImm() && TII->isInlineConstant(OpToFold, OpTy) &&
515 TII->isOperandLegal(*UseMI, UseOpIdx, &OpToFold)) {
517 return true;
518 }
519
520 if (!OpToFold.isReg())
521 return false;
522
523 Register UseReg = OpToFold.getReg();
524 if (!UseReg.isVirtual())
525 return false;
526
527 if (isUseMIInFoldList(FoldList, UseMI))
528 return false;
529
530 // Maybe it is just a COPY of an immediate itself.
531 MachineInstr *Def = MRI->getVRegDef(UseReg);
533 if (!UseOp.getSubReg() && Def && TII->isFoldableCopy(*Def)) {
534 MachineOperand &DefOp = Def->getOperand(1);
535 if (DefOp.isImm() && TII->isInlineConstant(DefOp, OpTy) &&
536 TII->isOperandLegal(*UseMI, UseOpIdx, &DefOp)) {
538 return true;
539 }
540 }
541
543 if (!getRegSeqInit(Defs, UseReg, OpTy))
544 return false;
545
546 int32_t Imm;
547 for (unsigned I = 0, E = Defs.size(); I != E; ++I) {
548 const MachineOperand *Op = Defs[I].first;
549 if (!Op->isImm())
550 return false;
551
552 auto SubImm = Op->getImm();
553 if (!I) {
554 Imm = SubImm;
555 if (!TII->isInlineConstant(*Op, OpTy) ||
556 !TII->isOperandLegal(*UseMI, UseOpIdx, Op))
557 return false;
558
559 continue;
560 }
561 if (Imm != SubImm)
562 return false; // Can only fold splat constants
563 }
564
565 appendFoldCandidate(FoldList, UseMI, UseOpIdx, Defs[0].first);
566 return true;
567}
568
569void SIFoldOperands::foldOperand(
570 MachineOperand &OpToFold,
572 int UseOpIdx,
574 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
575 const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
576
577 if (!isUseSafeToFold(*UseMI, UseOp))
578 return;
579
580 // FIXME: Fold operands with subregs.
581 if (UseOp.isReg() && OpToFold.isReg() &&
582 (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister))
583 return;
584
585 // Special case for REG_SEQUENCE: We can't fold literals into
586 // REG_SEQUENCE instructions, so we have to fold them into the
587 // uses of REG_SEQUENCE.
588 if (UseMI->isRegSequence()) {
589 Register RegSeqDstReg = UseMI->getOperand(0).getReg();
590 unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
591
592 for (auto &RSUse : make_early_inc_range(MRI->use_nodbg_operands(RegSeqDstReg))) {
593 MachineInstr *RSUseMI = RSUse.getParent();
594
595 if (tryToFoldACImm(UseMI->getOperand(0), RSUseMI,
596 RSUseMI->getOperandNo(&RSUse), FoldList))
597 continue;
598
599 if (RSUse.getSubReg() != RegSeqDstSubReg)
600 continue;
601
602 foldOperand(OpToFold, RSUseMI, RSUseMI->getOperandNo(&RSUse), FoldList,
603 CopiesToReplace);
604 }
605
606 return;
607 }
608
609 if (tryToFoldACImm(OpToFold, UseMI, UseOpIdx, FoldList))
610 return;
611
612 if (frameIndexMayFold(*UseMI, UseOpIdx, OpToFold)) {
613 // Verify that this is a stack access.
614 // FIXME: Should probably use stack pseudos before frame lowering.
615
616 if (TII->isMUBUF(*UseMI)) {
617 if (TII->getNamedOperand(*UseMI, AMDGPU::OpName::srsrc)->getReg() !=
618 MFI->getScratchRSrcReg())
619 return;
620
621 // Ensure this is either relative to the current frame or the current
622 // wave.
623 MachineOperand &SOff =
624 *TII->getNamedOperand(*UseMI, AMDGPU::OpName::soffset);
625 if (!SOff.isImm() || SOff.getImm() != 0)
626 return;
627 }
628
629 // A frame index will resolve to a positive constant, so it should always be
630 // safe to fold the addressing mode, even pre-GFX9.
632
633 const unsigned Opc = UseMI->getOpcode();
634 if (TII->isFLATScratch(*UseMI) &&
635 AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::vaddr) &&
636 !AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::saddr)) {
637 unsigned NewOpc = AMDGPU::getFlatScratchInstSSfromSV(Opc);
638 UseMI->setDesc(TII->get(NewOpc));
639 }
640
641 return;
642 }
643
644 bool FoldingImmLike =
645 OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
646
647 if (FoldingImmLike && UseMI->isCopy()) {
648 Register DestReg = UseMI->getOperand(0).getReg();
649 Register SrcReg = UseMI->getOperand(1).getReg();
650 assert(SrcReg.isVirtual());
651
652 const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg);
653
654 // Don't fold into a copy to a physical register with the same class. Doing
655 // so would interfere with the register coalescer's logic which would avoid
656 // redundant initializations.
657 if (DestReg.isPhysical() && SrcRC->contains(DestReg))
658 return;
659
660 const TargetRegisterClass *DestRC = TRI->getRegClassForReg(*MRI, DestReg);
661 if (!DestReg.isPhysical()) {
662 if (TRI->isSGPRClass(SrcRC) && TRI->hasVectorRegisters(DestRC)) {
664 for (auto &Use : MRI->use_nodbg_operands(DestReg)) {
665 // There's no point trying to fold into an implicit operand.
666 if (Use.isImplicit())
667 continue;
668
669 CopyUses.emplace_back(Use.getParent(),
670 Use.getParent()->getOperandNo(&Use),
671 &UseMI->getOperand(1));
672 }
673
674 for (auto &F : CopyUses) {
675 foldOperand(*F.OpToFold, F.UseMI, F.UseOpNo, FoldList,
676 CopiesToReplace);
677 }
678 }
679
680 if (DestRC == &AMDGPU::AGPR_32RegClass &&
681 TII->isInlineConstant(OpToFold, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
682 UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64));
684 CopiesToReplace.push_back(UseMI);
685 return;
686 }
687 }
688
689 // In order to fold immediates into copies, we need to change the
690 // copy to a MOV.
691
692 unsigned MovOp = TII->getMovOpcode(DestRC);
693 if (MovOp == AMDGPU::COPY)
694 return;
695
696 UseMI->setDesc(TII->get(MovOp));
699 while (ImpOpI != ImpOpE) {
700 MachineInstr::mop_iterator Tmp = ImpOpI;
701 ImpOpI++;
703 }
704 CopiesToReplace.push_back(UseMI);
705 } else {
706 if (UseMI->isCopy() && OpToFold.isReg() &&
708 !UseMI->getOperand(1).getSubReg()) {
709 LLVM_DEBUG(dbgs() << "Folding " << OpToFold << "\n into " << *UseMI);
710 unsigned Size = TII->getOpSize(*UseMI, 1);
711 Register UseReg = OpToFold.getReg();
713 UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
714 UseMI->getOperand(1).setIsKill(false);
715 CopiesToReplace.push_back(UseMI);
716 OpToFold.setIsKill(false);
717
718 // Remove kill flags as kills may now be out of order with uses.
719 MRI->clearKillFlags(OpToFold.getReg());
720
721 // That is very tricky to store a value into an AGPR. v_accvgpr_write_b32
722 // can only accept VGPR or inline immediate. Recreate a reg_sequence with
723 // its initializers right here, so we will rematerialize immediates and
724 // avoid copies via different reg classes.
726 if (Size > 4 && TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
727 getRegSeqInit(Defs, UseReg, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
728 const DebugLoc &DL = UseMI->getDebugLoc();
730
731 UseMI->setDesc(TII->get(AMDGPU::REG_SEQUENCE));
732 for (unsigned I = UseMI->getNumOperands() - 1; I > 0; --I)
734
738 for (unsigned I = 0; I < Size / 4; ++I) {
739 MachineOperand *Def = Defs[I].first;
741 if (Def->isImm() &&
742 TII->isInlineConstant(*Def, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
743 int64_t Imm = Def->getImm();
744
745 auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
747 TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addImm(Imm);
748 B.addReg(Tmp);
749 } else if (Def->isReg() && TRI->isAGPR(*MRI, Def->getReg())) {
750 auto Src = getRegSubRegPair(*Def);
751 Def->setIsKill(false);
752 if (!SeenAGPRs.insert(Src)) {
753 // We cannot build a reg_sequence out of the same registers, they
754 // must be copied. Better do it here before copyPhysReg() created
755 // several reads to do the AGPR->VGPR->AGPR copy.
756 CopyToVGPR = Src;
757 } else {
758 B.addReg(Src.Reg, Def->isUndef() ? RegState::Undef : 0,
759 Src.SubReg);
760 }
761 } else {
762 assert(Def->isReg());
763 Def->setIsKill(false);
764 auto Src = getRegSubRegPair(*Def);
765
766 // Direct copy from SGPR to AGPR is not possible. To avoid creation
767 // of exploded copies SGPR->VGPR->AGPR in the copyPhysReg() later,
768 // create a copy here and track if we already have such a copy.
769 if (TRI->isSGPRReg(*MRI, Src.Reg)) {
770 CopyToVGPR = Src;
771 } else {
772 auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
773 BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Tmp).add(*Def);
774 B.addReg(Tmp);
775 }
776 }
777
778 if (CopyToVGPR.Reg) {
779 Register Vgpr;
780 if (VGPRCopies.count(CopyToVGPR)) {
781 Vgpr = VGPRCopies[CopyToVGPR];
782 } else {
783 Vgpr = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
784 BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Vgpr).add(*Def);
785 VGPRCopies[CopyToVGPR] = Vgpr;
786 }
787 auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
789 TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addReg(Vgpr);
790 B.addReg(Tmp);
791 }
792
793 B.addImm(Defs[I].second);
794 }
795 LLVM_DEBUG(dbgs() << "Folded " << *UseMI);
796 return;
797 }
798
799 if (Size != 4)
800 return;
801
802 Register Reg0 = UseMI->getOperand(0).getReg();
803 Register Reg1 = UseMI->getOperand(1).getReg();
804 if (TRI->isAGPR(*MRI, Reg0) && TRI->isVGPR(*MRI, Reg1))
805 UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64));
806 else if (TRI->isVGPR(*MRI, Reg0) && TRI->isAGPR(*MRI, Reg1))
807 UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_READ_B32_e64));
808 else if (ST->hasGFX90AInsts() && TRI->isAGPR(*MRI, Reg0) &&
809 TRI->isAGPR(*MRI, Reg1))
810 UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_MOV_B32));
811 return;
812 }
813
814 unsigned UseOpc = UseMI->getOpcode();
815 if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 ||
816 (UseOpc == AMDGPU::V_READLANE_B32 &&
817 (int)UseOpIdx ==
818 AMDGPU::getNamedOperandIdx(UseOpc, AMDGPU::OpName::src0))) {
819 // %vgpr = V_MOV_B32 imm
820 // %sgpr = V_READFIRSTLANE_B32 %vgpr
821 // =>
822 // %sgpr = S_MOV_B32 imm
823 if (FoldingImmLike) {
826 *OpToFold.getParent(),
827 *UseMI))
828 return;
829
830 UseMI->setDesc(TII->get(AMDGPU::S_MOV_B32));
831
832 if (OpToFold.isImm())
834 else
836 UseMI->removeOperand(2); // Remove exec read (or src1 for readlane)
837 return;
838 }
839
840 if (OpToFold.isReg() && TRI->isSGPRReg(*MRI, OpToFold.getReg())) {
843 *OpToFold.getParent(),
844 *UseMI))
845 return;
846
847 // %vgpr = COPY %sgpr0
848 // %sgpr1 = V_READFIRSTLANE_B32 %vgpr
849 // =>
850 // %sgpr1 = COPY %sgpr0
851 UseMI->setDesc(TII->get(AMDGPU::COPY));
852 UseMI->getOperand(1).setReg(OpToFold.getReg());
853 UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
854 UseMI->getOperand(1).setIsKill(false);
855 UseMI->removeOperand(2); // Remove exec read (or src1 for readlane)
856 return;
857 }
858 }
859
860 const MCInstrDesc &UseDesc = UseMI->getDesc();
861
862 // Don't fold into target independent nodes. Target independent opcodes
863 // don't have defined register classes.
864 if (UseDesc.isVariadic() || UseOp.isImplicit() ||
865 UseDesc.operands()[UseOpIdx].RegClass == -1)
866 return;
867 }
868
869 if (!FoldingImmLike) {
870 if (OpToFold.isReg() && ST->needsAlignedVGPRs()) {
871 // Don't fold if OpToFold doesn't hold an aligned register.
872 const TargetRegisterClass *RC =
873 TRI->getRegClassForReg(*MRI, OpToFold.getReg());
874 if (TRI->hasVectorRegisters(RC) && OpToFold.getSubReg()) {
875 unsigned SubReg = OpToFold.getSubReg();
876 if (const TargetRegisterClass *SubRC =
877 TRI->getSubRegisterClass(RC, SubReg))
878 RC = SubRC;
879 }
880
881 if (!RC || !TRI->isProperlyAlignedRC(*RC))
882 return;
883 }
884
885 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold);
886
887 // FIXME: We could try to change the instruction from 64-bit to 32-bit
888 // to enable more folding opportunities. The shrink operands pass
889 // already does this.
890 return;
891 }
892
893
894 const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
895 const TargetRegisterClass *FoldRC =
896 TRI->getRegClass(FoldDesc.operands()[0].RegClass);
897
898 // Split 64-bit constants into 32-bits for folding.
899 if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
900 Register UseReg = UseOp.getReg();
901 const TargetRegisterClass *UseRC = MRI->getRegClass(UseReg);
902
903 if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
904 return;
905
906 APInt Imm(64, OpToFold.getImm());
907 if (UseOp.getSubReg() == AMDGPU::sub0) {
908 Imm = Imm.getLoBits(32);
909 } else {
910 assert(UseOp.getSubReg() == AMDGPU::sub1);
911 Imm = Imm.getHiBits(32);
912 }
913
914 MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
915 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp);
916 return;
917 }
918
919 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold);
920}
921
922static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
923 uint32_t LHS, uint32_t RHS) {
924 switch (Opcode) {
925 case AMDGPU::V_AND_B32_e64:
926 case AMDGPU::V_AND_B32_e32:
927 case AMDGPU::S_AND_B32:
928 Result = LHS & RHS;
929 return true;
930 case AMDGPU::V_OR_B32_e64:
931 case AMDGPU::V_OR_B32_e32:
932 case AMDGPU::S_OR_B32:
933 Result = LHS | RHS;
934 return true;
935 case AMDGPU::V_XOR_B32_e64:
936 case AMDGPU::V_XOR_B32_e32:
937 case AMDGPU::S_XOR_B32:
938 Result = LHS ^ RHS;
939 return true;
940 case AMDGPU::S_XNOR_B32:
941 Result = ~(LHS ^ RHS);
942 return true;
943 case AMDGPU::S_NAND_B32:
944 Result = ~(LHS & RHS);
945 return true;
946 case AMDGPU::S_NOR_B32:
947 Result = ~(LHS | RHS);
948 return true;
949 case AMDGPU::S_ANDN2_B32:
950 Result = LHS & ~RHS;
951 return true;
952 case AMDGPU::S_ORN2_B32:
953 Result = LHS | ~RHS;
954 return true;
955 case AMDGPU::V_LSHL_B32_e64:
956 case AMDGPU::V_LSHL_B32_e32:
957 case AMDGPU::S_LSHL_B32:
958 // The instruction ignores the high bits for out of bounds shifts.
959 Result = LHS << (RHS & 31);
960 return true;
961 case AMDGPU::V_LSHLREV_B32_e64:
962 case AMDGPU::V_LSHLREV_B32_e32:
963 Result = RHS << (LHS & 31);
964 return true;
965 case AMDGPU::V_LSHR_B32_e64:
966 case AMDGPU::V_LSHR_B32_e32:
967 case AMDGPU::S_LSHR_B32:
968 Result = LHS >> (RHS & 31);
969 return true;
970 case AMDGPU::V_LSHRREV_B32_e64:
971 case AMDGPU::V_LSHRREV_B32_e32:
972 Result = RHS >> (LHS & 31);
973 return true;
974 case AMDGPU::V_ASHR_I32_e64:
975 case AMDGPU::V_ASHR_I32_e32:
976 case AMDGPU::S_ASHR_I32:
977 Result = static_cast<int32_t>(LHS) >> (RHS & 31);
978 return true;
979 case AMDGPU::V_ASHRREV_I32_e64:
980 case AMDGPU::V_ASHRREV_I32_e32:
981 Result = static_cast<int32_t>(RHS) >> (LHS & 31);
982 return true;
983 default:
984 return false;
985 }
986}
987
988static unsigned getMovOpc(bool IsScalar) {
989 return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
990}
991
992static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
993 MI.setDesc(NewDesc);
994
995 // Remove any leftover implicit operands from mutating the instruction. e.g.
996 // if we replace an s_and_b32 with a copy, we don't need the implicit scc def
997 // anymore.
998 const MCInstrDesc &Desc = MI.getDesc();
999 unsigned NumOps = Desc.getNumOperands() + Desc.implicit_uses().size() +
1000 Desc.implicit_defs().size();
1001
1002 for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
1003 MI.removeOperand(I);
1004}
1005
1007SIFoldOperands::getImmOrMaterializedImm(MachineOperand &Op) const {
1008 // If this has a subregister, it obviously is a register source.
1009 if (!Op.isReg() || Op.getSubReg() != AMDGPU::NoSubRegister ||
1010 !Op.getReg().isVirtual())
1011 return &Op;
1012
1013 MachineInstr *Def = MRI->getVRegDef(Op.getReg());
1014 if (Def && Def->isMoveImmediate()) {
1015 MachineOperand &ImmSrc = Def->getOperand(1);
1016 if (ImmSrc.isImm())
1017 return &ImmSrc;
1018 }
1019
1020 return &Op;
1021}
1022
1023// Try to simplify operations with a constant that may appear after instruction
1024// selection.
1025// TODO: See if a frame index with a fixed offset can fold.
1026bool SIFoldOperands::tryConstantFoldOp(MachineInstr *MI) const {
1027 unsigned Opc = MI->getOpcode();
1028
1029 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1030 if (Src0Idx == -1)
1031 return false;
1032 MachineOperand *Src0 = getImmOrMaterializedImm(MI->getOperand(Src0Idx));
1033
1034 if ((Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
1035 Opc == AMDGPU::S_NOT_B32) &&
1036 Src0->isImm()) {
1037 MI->getOperand(1).ChangeToImmediate(~Src0->getImm());
1038 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
1039 return true;
1040 }
1041
1042 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1043 if (Src1Idx == -1)
1044 return false;
1045 MachineOperand *Src1 = getImmOrMaterializedImm(MI->getOperand(Src1Idx));
1046
1047 if (!Src0->isImm() && !Src1->isImm())
1048 return false;
1049
1050 // and k0, k1 -> v_mov_b32 (k0 & k1)
1051 // or k0, k1 -> v_mov_b32 (k0 | k1)
1052 // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
1053 if (Src0->isImm() && Src1->isImm()) {
1054 int32_t NewImm;
1055 if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
1056 return false;
1057
1058 bool IsSGPR = TRI->isSGPRReg(*MRI, MI->getOperand(0).getReg());
1059
1060 // Be careful to change the right operand, src0 may belong to a different
1061 // instruction.
1062 MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
1063 MI->removeOperand(Src1Idx);
1064 mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
1065 return true;
1066 }
1067
1068 if (!MI->isCommutable())
1069 return false;
1070
1071 if (Src0->isImm() && !Src1->isImm()) {
1072 std::swap(Src0, Src1);
1073 std::swap(Src0Idx, Src1Idx);
1074 }
1075
1076 int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
1077 if (Opc == AMDGPU::V_OR_B32_e64 ||
1078 Opc == AMDGPU::V_OR_B32_e32 ||
1079 Opc == AMDGPU::S_OR_B32) {
1080 if (Src1Val == 0) {
1081 // y = or x, 0 => y = copy x
1082 MI->removeOperand(Src1Idx);
1083 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1084 } else if (Src1Val == -1) {
1085 // y = or x, -1 => y = v_mov_b32 -1
1086 MI->removeOperand(Src1Idx);
1087 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
1088 } else
1089 return false;
1090
1091 return true;
1092 }
1093
1094 if (Opc == AMDGPU::V_AND_B32_e64 || Opc == AMDGPU::V_AND_B32_e32 ||
1095 Opc == AMDGPU::S_AND_B32) {
1096 if (Src1Val == 0) {
1097 // y = and x, 0 => y = v_mov_b32 0
1098 MI->removeOperand(Src0Idx);
1099 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
1100 } else if (Src1Val == -1) {
1101 // y = and x, -1 => y = copy x
1102 MI->removeOperand(Src1Idx);
1103 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1104 } else
1105 return false;
1106
1107 return true;
1108 }
1109
1110 if (Opc == AMDGPU::V_XOR_B32_e64 || Opc == AMDGPU::V_XOR_B32_e32 ||
1111 Opc == AMDGPU::S_XOR_B32) {
1112 if (Src1Val == 0) {
1113 // y = xor x, 0 => y = copy x
1114 MI->removeOperand(Src1Idx);
1115 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1116 return true;
1117 }
1118 }
1119
1120 return false;
1121}
1122
1123// Try to fold an instruction into a simpler one
1124bool SIFoldOperands::tryFoldCndMask(MachineInstr &MI) const {
1125 unsigned Opc = MI.getOpcode();
1126 if (Opc != AMDGPU::V_CNDMASK_B32_e32 && Opc != AMDGPU::V_CNDMASK_B32_e64 &&
1127 Opc != AMDGPU::V_CNDMASK_B64_PSEUDO)
1128 return false;
1129
1130 MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1131 MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1132 if (!Src1->isIdenticalTo(*Src0)) {
1133 auto *Src0Imm = getImmOrMaterializedImm(*Src0);
1134 auto *Src1Imm = getImmOrMaterializedImm(*Src1);
1135 if (!Src1Imm->isIdenticalTo(*Src0Imm))
1136 return false;
1137 }
1138
1139 int Src1ModIdx =
1140 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers);
1141 int Src0ModIdx =
1142 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
1143 if ((Src1ModIdx != -1 && MI.getOperand(Src1ModIdx).getImm() != 0) ||
1144 (Src0ModIdx != -1 && MI.getOperand(Src0ModIdx).getImm() != 0))
1145 return false;
1146
1147 LLVM_DEBUG(dbgs() << "Folded " << MI << " into ");
1148 auto &NewDesc =
1149 TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(false));
1150 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
1151 if (Src2Idx != -1)
1152 MI.removeOperand(Src2Idx);
1153 MI.removeOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
1154 if (Src1ModIdx != -1)
1155 MI.removeOperand(Src1ModIdx);
1156 if (Src0ModIdx != -1)
1157 MI.removeOperand(Src0ModIdx);
1158 mutateCopyOp(MI, NewDesc);
1159 LLVM_DEBUG(dbgs() << MI);
1160 return true;
1161}
1162
1163bool SIFoldOperands::tryFoldZeroHighBits(MachineInstr &MI) const {
1164 if (MI.getOpcode() != AMDGPU::V_AND_B32_e64 &&
1165 MI.getOpcode() != AMDGPU::V_AND_B32_e32)
1166 return false;
1167
1168 MachineOperand *Src0 = getImmOrMaterializedImm(MI.getOperand(1));
1169 if (!Src0->isImm() || Src0->getImm() != 0xffff)
1170 return false;
1171
1172 Register Src1 = MI.getOperand(2).getReg();
1173 MachineInstr *SrcDef = MRI->getVRegDef(Src1);
1174 if (!ST->zeroesHigh16BitsOfDest(SrcDef->getOpcode()))
1175 return false;
1176
1177 Register Dst = MI.getOperand(0).getReg();
1178 MRI->replaceRegWith(Dst, SrcDef->getOperand(0).getReg());
1179 MI.eraseFromParent();
1180 return true;
1181}
1182
1183bool SIFoldOperands::foldInstOperand(MachineInstr &MI,
1184 MachineOperand &OpToFold) const {
1185 // We need mutate the operands of new mov instructions to add implicit
1186 // uses of EXEC, but adding them invalidates the use_iterator, so defer
1187 // this.
1188 SmallVector<MachineInstr *, 4> CopiesToReplace;
1190 MachineOperand &Dst = MI.getOperand(0);
1191 bool Changed = false;
1192
1193 if (OpToFold.isImm()) {
1194 for (auto &UseMI :
1195 make_early_inc_range(MRI->use_nodbg_instructions(Dst.getReg()))) {
1196 // Folding the immediate may reveal operations that can be constant
1197 // folded or replaced with a copy. This can happen for example after
1198 // frame indices are lowered to constants or from splitting 64-bit
1199 // constants.
1200 //
1201 // We may also encounter cases where one or both operands are
1202 // immediates materialized into a register, which would ordinarily not
1203 // be folded due to multiple uses or operand constraints.
1204 if (tryConstantFoldOp(&UseMI)) {
1205 LLVM_DEBUG(dbgs() << "Constant folded " << UseMI);
1206 Changed = true;
1207 }
1208 }
1209 }
1210
1212 for (auto &Use : MRI->use_nodbg_operands(Dst.getReg()))
1213 UsesToProcess.push_back(&Use);
1214 for (auto *U : UsesToProcess) {
1215 MachineInstr *UseMI = U->getParent();
1216 foldOperand(OpToFold, UseMI, UseMI->getOperandNo(U), FoldList,
1217 CopiesToReplace);
1218 }
1219
1220 if (CopiesToReplace.empty() && FoldList.empty())
1221 return Changed;
1222
1223 MachineFunction *MF = MI.getParent()->getParent();
1224 // Make sure we add EXEC uses to any new v_mov instructions created.
1225 for (MachineInstr *Copy : CopiesToReplace)
1226 Copy->addImplicitDefUseOperands(*MF);
1227
1228 for (FoldCandidate &Fold : FoldList) {
1229 assert(!Fold.isReg() || Fold.OpToFold);
1230 if (Fold.isReg() && Fold.OpToFold->getReg().isVirtual()) {
1231 Register Reg = Fold.OpToFold->getReg();
1232 MachineInstr *DefMI = Fold.OpToFold->getParent();
1233 if (DefMI->readsRegister(AMDGPU::EXEC, TRI) &&
1234 execMayBeModifiedBeforeUse(*MRI, Reg, *DefMI, *Fold.UseMI))
1235 continue;
1236 }
1237 if (updateOperand(Fold)) {
1238 // Clear kill flags.
1239 if (Fold.isReg()) {
1240 assert(Fold.OpToFold && Fold.OpToFold->isReg());
1241 // FIXME: Probably shouldn't bother trying to fold if not an
1242 // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
1243 // copies.
1244 MRI->clearKillFlags(Fold.OpToFold->getReg());
1245 }
1246 LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
1247 << static_cast<int>(Fold.UseOpNo) << " of "
1248 << *Fold.UseMI);
1249 } else if (Fold.Commuted) {
1250 // Restoring instruction's original operand order if fold has failed.
1251 TII->commuteInstruction(*Fold.UseMI, false);
1252 }
1253 }
1254 return true;
1255}
1256
1257bool SIFoldOperands::tryFoldFoldableCopy(
1258 MachineInstr &MI, MachineOperand *&CurrentKnownM0Val) const {
1259 // Specially track simple redefs of m0 to the same value in a block, so we
1260 // can erase the later ones.
1261 if (MI.getOperand(0).getReg() == AMDGPU::M0) {
1262 MachineOperand &NewM0Val = MI.getOperand(1);
1263 if (CurrentKnownM0Val && CurrentKnownM0Val->isIdenticalTo(NewM0Val)) {
1264 MI.eraseFromParent();
1265 return true;
1266 }
1267
1268 // We aren't tracking other physical registers
1269 CurrentKnownM0Val = (NewM0Val.isReg() && NewM0Val.getReg().isPhysical())
1270 ? nullptr
1271 : &NewM0Val;
1272 return false;
1273 }
1274
1275 MachineOperand &OpToFold = MI.getOperand(1);
1276 bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1277
1278 // FIXME: We could also be folding things like TargetIndexes.
1279 if (!FoldingImm && !OpToFold.isReg())
1280 return false;
1281
1282 if (OpToFold.isReg() && !OpToFold.getReg().isVirtual())
1283 return false;
1284
1285 // Prevent folding operands backwards in the function. For example,
1286 // the COPY opcode must not be replaced by 1 in this example:
1287 //
1288 // %3 = COPY %vgpr0; VGPR_32:%3
1289 // ...
1290 // %vgpr0 = V_MOV_B32_e32 1, implicit %exec
1291 if (!MI.getOperand(0).getReg().isVirtual())
1292 return false;
1293
1294 bool Changed = foldInstOperand(MI, OpToFold);
1295
1296 // If we managed to fold all uses of this copy then we might as well
1297 // delete it now.
1298 // The only reason we need to follow chains of copies here is that
1299 // tryFoldRegSequence looks forward through copies before folding a
1300 // REG_SEQUENCE into its eventual users.
1301 auto *InstToErase = &MI;
1302 while (MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
1303 auto &SrcOp = InstToErase->getOperand(1);
1304 auto SrcReg = SrcOp.isReg() ? SrcOp.getReg() : Register();
1305 InstToErase->eraseFromParent();
1306 Changed = true;
1307 InstToErase = nullptr;
1308 if (!SrcReg || SrcReg.isPhysical())
1309 break;
1310 InstToErase = MRI->getVRegDef(SrcReg);
1311 if (!InstToErase || !TII->isFoldableCopy(*InstToErase))
1312 break;
1313 }
1314
1315 if (InstToErase && InstToErase->isRegSequence() &&
1316 MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
1317 InstToErase->eraseFromParent();
1318 Changed = true;
1319 }
1320
1321 return Changed;
1322}
1323
1324// Clamp patterns are canonically selected to v_max_* instructions, so only
1325// handle them.
1326const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
1327 unsigned Op = MI.getOpcode();
1328 switch (Op) {
1329 case AMDGPU::V_MAX_F32_e64:
1330 case AMDGPU::V_MAX_F16_e64:
1331 case AMDGPU::V_MAX_F16_t16_e64:
1332 case AMDGPU::V_MAX_F64_e64:
1333 case AMDGPU::V_PK_MAX_F16: {
1334 if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
1335 return nullptr;
1336
1337 // Make sure sources are identical.
1338 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1339 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1340 if (!Src0->isReg() || !Src1->isReg() ||
1341 Src0->getReg() != Src1->getReg() ||
1342 Src0->getSubReg() != Src1->getSubReg() ||
1343 Src0->getSubReg() != AMDGPU::NoSubRegister)
1344 return nullptr;
1345
1346 // Can't fold up if we have modifiers.
1347 if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1348 return nullptr;
1349
1350 unsigned Src0Mods
1351 = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
1352 unsigned Src1Mods
1353 = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
1354
1355 // Having a 0 op_sel_hi would require swizzling the output in the source
1356 // instruction, which we can't do.
1357 unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1
1358 : 0u;
1359 if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
1360 return nullptr;
1361 return Src0;
1362 }
1363 default:
1364 return nullptr;
1365 }
1366}
1367
1368// FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
1369bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
1370 const MachineOperand *ClampSrc = isClamp(MI);
1371 if (!ClampSrc || !MRI->hasOneNonDBGUser(ClampSrc->getReg()))
1372 return false;
1373
1374 MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
1375
1376 // The type of clamp must be compatible.
1377 if (TII->getClampMask(*Def) != TII->getClampMask(MI))
1378 return false;
1379
1380 MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
1381 if (!DefClamp)
1382 return false;
1383
1384 LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def);
1385
1386 // Clamp is applied after omod, so it is OK if omod is set.
1387 DefClamp->setImm(1);
1388 MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1389 MI.eraseFromParent();
1390
1391 // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
1392 // instruction, so we might as well convert it to the more flexible VOP3-only
1393 // mad/fma form.
1394 if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
1395 Def->eraseFromParent();
1396
1397 return true;
1398}
1399
1400static int getOModValue(unsigned Opc, int64_t Val) {
1401 switch (Opc) {
1402 case AMDGPU::V_MUL_F64_e64: {
1403 switch (Val) {
1404 case 0x3fe0000000000000: // 0.5
1405 return SIOutMods::DIV2;
1406 case 0x4000000000000000: // 2.0
1407 return SIOutMods::MUL2;
1408 case 0x4010000000000000: // 4.0
1409 return SIOutMods::MUL4;
1410 default:
1411 return SIOutMods::NONE;
1412 }
1413 }
1414 case AMDGPU::V_MUL_F32_e64: {
1415 switch (static_cast<uint32_t>(Val)) {
1416 case 0x3f000000: // 0.5
1417 return SIOutMods::DIV2;
1418 case 0x40000000: // 2.0
1419 return SIOutMods::MUL2;
1420 case 0x40800000: // 4.0
1421 return SIOutMods::MUL4;
1422 default:
1423 return SIOutMods::NONE;
1424 }
1425 }
1426 case AMDGPU::V_MUL_F16_e64:
1427 case AMDGPU::V_MUL_F16_t16_e64: {
1428 switch (static_cast<uint16_t>(Val)) {
1429 case 0x3800: // 0.5
1430 return SIOutMods::DIV2;
1431 case 0x4000: // 2.0
1432 return SIOutMods::MUL2;
1433 case 0x4400: // 4.0
1434 return SIOutMods::MUL4;
1435 default:
1436 return SIOutMods::NONE;
1437 }
1438 }
1439 default:
1440 llvm_unreachable("invalid mul opcode");
1441 }
1442}
1443
1444// FIXME: Does this really not support denormals with f16?
1445// FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
1446// handled, so will anything other than that break?
1447std::pair<const MachineOperand *, int>
1448SIFoldOperands::isOMod(const MachineInstr &MI) const {
1449 unsigned Op = MI.getOpcode();
1450 switch (Op) {
1451 case AMDGPU::V_MUL_F64_e64:
1452 case AMDGPU::V_MUL_F32_e64:
1453 case AMDGPU::V_MUL_F16_t16_e64:
1454 case AMDGPU::V_MUL_F16_e64: {
1455 // If output denormals are enabled, omod is ignored.
1456 if ((Op == AMDGPU::V_MUL_F32_e64 &&
1457 MFI->getMode().FP32Denormals.Output != DenormalMode::PreserveSign) ||
1458 ((Op == AMDGPU::V_MUL_F64_e64 || Op == AMDGPU::V_MUL_F16_e64 ||
1459 Op == AMDGPU::V_MUL_F16_t16_e64) &&
1460 MFI->getMode().FP64FP16Denormals.Output != DenormalMode::PreserveSign))
1461 return std::pair(nullptr, SIOutMods::NONE);
1462
1463 const MachineOperand *RegOp = nullptr;
1464 const MachineOperand *ImmOp = nullptr;
1465 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1466 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1467 if (Src0->isImm()) {
1468 ImmOp = Src0;
1469 RegOp = Src1;
1470 } else if (Src1->isImm()) {
1471 ImmOp = Src1;
1472 RegOp = Src0;
1473 } else
1474 return std::pair(nullptr, SIOutMods::NONE);
1475
1476 int OMod = getOModValue(Op, ImmOp->getImm());
1477 if (OMod == SIOutMods::NONE ||
1478 TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1479 TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
1480 TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
1481 TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
1482 return std::pair(nullptr, SIOutMods::NONE);
1483
1484 return std::pair(RegOp, OMod);
1485 }
1486 case AMDGPU::V_ADD_F64_e64:
1487 case AMDGPU::V_ADD_F32_e64:
1488 case AMDGPU::V_ADD_F16_e64:
1489 case AMDGPU::V_ADD_F16_t16_e64: {
1490 // If output denormals are enabled, omod is ignored.
1491 if ((Op == AMDGPU::V_ADD_F32_e64 &&
1492 MFI->getMode().FP32Denormals.Output != DenormalMode::PreserveSign) ||
1493 ((Op == AMDGPU::V_ADD_F64_e64 || Op == AMDGPU::V_ADD_F16_e64 ||
1494 Op == AMDGPU::V_ADD_F16_t16_e64) &&
1495 MFI->getMode().FP64FP16Denormals.Output != DenormalMode::PreserveSign))
1496 return std::pair(nullptr, SIOutMods::NONE);
1497
1498 // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
1499 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1500 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1501
1502 if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
1503 Src0->getSubReg() == Src1->getSubReg() &&
1504 !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
1505 !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
1506 !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
1507 !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1508 return std::pair(Src0, SIOutMods::MUL2);
1509
1510 return std::pair(nullptr, SIOutMods::NONE);
1511 }
1512 default:
1513 return std::pair(nullptr, SIOutMods::NONE);
1514 }
1515}
1516
1517// FIXME: Does this need to check IEEE bit on function?
1518bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
1519 const MachineOperand *RegOp;
1520 int OMod;
1521 std::tie(RegOp, OMod) = isOMod(MI);
1522 if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
1523 RegOp->getSubReg() != AMDGPU::NoSubRegister ||
1524 !MRI->hasOneNonDBGUser(RegOp->getReg()))
1525 return false;
1526
1527 MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
1528 MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
1529 if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
1530 return false;
1531
1532 // Clamp is applied after omod. If the source already has clamp set, don't
1533 // fold it.
1534 if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
1535 return false;
1536
1537 LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def);
1538
1539 DefOMod->setImm(OMod);
1540 MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1541 MI.eraseFromParent();
1542
1543 // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
1544 // instruction, so we might as well convert it to the more flexible VOP3-only
1545 // mad/fma form.
1546 if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
1547 Def->eraseFromParent();
1548
1549 return true;
1550}
1551
1552// Try to fold a reg_sequence with vgpr output and agpr inputs into an
1553// instruction which can take an agpr. So far that means a store.
1554bool SIFoldOperands::tryFoldRegSequence(MachineInstr &MI) {
1555 assert(MI.isRegSequence());
1556 auto Reg = MI.getOperand(0).getReg();
1557
1558 if (!ST->hasGFX90AInsts() || !TRI->isVGPR(*MRI, Reg) ||
1559 !MRI->hasOneNonDBGUse(Reg))
1560 return false;
1561
1563 if (!getRegSeqInit(Defs, Reg, MCOI::OPERAND_REGISTER))
1564 return false;
1565
1566 for (auto &Def : Defs) {
1567 const auto *Op = Def.first;
1568 if (!Op->isReg())
1569 return false;
1570 if (TRI->isAGPR(*MRI, Op->getReg()))
1571 continue;
1572 // Maybe this is a COPY from AREG
1573 const MachineInstr *SubDef = MRI->getVRegDef(Op->getReg());
1574 if (!SubDef || !SubDef->isCopy() || SubDef->getOperand(1).getSubReg())
1575 return false;
1576 if (!TRI->isAGPR(*MRI, SubDef->getOperand(1).getReg()))
1577 return false;
1578 }
1579
1580 MachineOperand *Op = &*MRI->use_nodbg_begin(Reg);
1581 MachineInstr *UseMI = Op->getParent();
1582 while (UseMI->isCopy() && !Op->getSubReg()) {
1583 Reg = UseMI->getOperand(0).getReg();
1584 if (!TRI->isVGPR(*MRI, Reg) || !MRI->hasOneNonDBGUse(Reg))
1585 return false;
1586 Op = &*MRI->use_nodbg_begin(Reg);
1587 UseMI = Op->getParent();
1588 }
1589
1590 if (Op->getSubReg())
1591 return false;
1592
1593 unsigned OpIdx = Op - &UseMI->getOperand(0);
1594 const MCInstrDesc &InstDesc = UseMI->getDesc();
1595 const TargetRegisterClass *OpRC =
1596 TII->getRegClass(InstDesc, OpIdx, TRI, *MI.getMF());
1597 if (!OpRC || !TRI->isVectorSuperClass(OpRC))
1598 return false;
1599
1600 const auto *NewDstRC = TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg));
1601 auto Dst = MRI->createVirtualRegister(NewDstRC);
1602 auto RS = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1603 TII->get(AMDGPU::REG_SEQUENCE), Dst);
1604
1605 for (unsigned I = 0; I < Defs.size(); ++I) {
1606 MachineOperand *Def = Defs[I].first;
1607 Def->setIsKill(false);
1608 if (TRI->isAGPR(*MRI, Def->getReg())) {
1609 RS.add(*Def);
1610 } else { // This is a copy
1611 MachineInstr *SubDef = MRI->getVRegDef(Def->getReg());
1612 SubDef->getOperand(1).setIsKill(false);
1613 RS.addReg(SubDef->getOperand(1).getReg(), 0, Def->getSubReg());
1614 }
1615 RS.addImm(Defs[I].second);
1616 }
1617
1618 Op->setReg(Dst);
1619 if (!TII->isOperandLegal(*UseMI, OpIdx, Op)) {
1620 Op->setReg(Reg);
1621 RS->eraseFromParent();
1622 return false;
1623 }
1624
1625 LLVM_DEBUG(dbgs() << "Folded " << *RS << " into " << *UseMI);
1626
1627 // Erase the REG_SEQUENCE eagerly, unless we followed a chain of COPY users,
1628 // in which case we can erase them all later in runOnMachineFunction.
1629 if (MRI->use_nodbg_empty(MI.getOperand(0).getReg()))
1630 MI.eraseFromParent();
1631 return true;
1632}
1633
1634// Try to hoist an AGPR to VGPR copy out of the loop across a LCSSA PHI.
1635// This should allow folding of an AGPR into a consumer which may support it.
1636// I.e.:
1637//
1638// loop: // loop:
1639// %1:vreg = COPY %0:areg // exit:
1640// exit: => // %1:areg = PHI %0:areg, %loop
1641// %2:vreg = PHI %1:vreg, %loop // %2:vreg = COPY %1:areg
1642bool SIFoldOperands::tryFoldLCSSAPhi(MachineInstr &PHI) {
1643 assert(PHI.isPHI());
1644
1645 if (PHI.getNumExplicitOperands() != 3) // Single input LCSSA PHI
1646 return false;
1647
1648 Register PhiIn = PHI.getOperand(1).getReg();
1649 Register PhiOut = PHI.getOperand(0).getReg();
1650 if (PHI.getOperand(1).getSubReg() ||
1651 !TRI->isVGPR(*MRI, PhiIn) || !TRI->isVGPR(*MRI, PhiOut))
1652 return false;
1653
1654 // A single use should not matter for correctness, but if it has another use
1655 // inside the loop we may perform copy twice in a worst case.
1656 if (!MRI->hasOneNonDBGUse(PhiIn))
1657 return false;
1658
1659 MachineInstr *Copy = MRI->getVRegDef(PhiIn);
1660 if (!Copy || !Copy->isCopy())
1661 return false;
1662
1663 Register CopyIn = Copy->getOperand(1).getReg();
1664 if (!TRI->isAGPR(*MRI, CopyIn) || Copy->getOperand(1).getSubReg())
1665 return false;
1666
1667 const TargetRegisterClass *ARC = MRI->getRegClass(CopyIn);
1668 Register NewReg = MRI->createVirtualRegister(ARC);
1669 PHI.getOperand(1).setReg(CopyIn);
1670 PHI.getOperand(0).setReg(NewReg);
1671
1672 MachineBasicBlock *MBB = PHI.getParent();
1673 BuildMI(*MBB, MBB->getFirstNonPHI(), Copy->getDebugLoc(),
1674 TII->get(AMDGPU::COPY), PhiOut)
1675 .addReg(NewReg, RegState::Kill);
1676 Copy->eraseFromParent(); // We know this copy had a single use.
1677
1678 LLVM_DEBUG(dbgs() << "Folded " << PHI);
1679
1680 return true;
1681}
1682
1683// Attempt to convert VGPR load to an AGPR load.
1684bool SIFoldOperands::tryFoldLoad(MachineInstr &MI) {
1685 assert(MI.mayLoad());
1686 if (!ST->hasGFX90AInsts() || MI.getNumExplicitDefs() != 1)
1687 return false;
1688
1689 MachineOperand &Def = MI.getOperand(0);
1690 if (!Def.isDef())
1691 return false;
1692
1693 Register DefReg = Def.getReg();
1694
1695 if (DefReg.isPhysical() || !TRI->isVGPR(*MRI, DefReg))
1696 return false;
1697
1699 SmallVector<Register, 8> MoveRegs;
1700 for (const MachineInstr &I : MRI->use_nodbg_instructions(DefReg))
1701 Users.push_back(&I);
1702
1703 if (Users.empty())
1704 return false;
1705
1706 // Check that all uses a copy to an agpr or a reg_sequence producing an agpr.
1707 while (!Users.empty()) {
1708 const MachineInstr *I = Users.pop_back_val();
1709 if (!I->isCopy() && !I->isRegSequence())
1710 return false;
1711 Register DstReg = I->getOperand(0).getReg();
1712 // Physical registers may have more than one instruction definitions
1713 if (DstReg.isPhysical())
1714 return false;
1715 if (TRI->isAGPR(*MRI, DstReg))
1716 continue;
1717 MoveRegs.push_back(DstReg);
1718 for (const MachineInstr &U : MRI->use_nodbg_instructions(DstReg))
1719 Users.push_back(&U);
1720 }
1721
1722 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
1723 MRI->setRegClass(DefReg, TRI->getEquivalentAGPRClass(RC));
1724 if (!TII->isOperandLegal(MI, 0, &Def)) {
1725 MRI->setRegClass(DefReg, RC);
1726 return false;
1727 }
1728
1729 while (!MoveRegs.empty()) {
1730 Register Reg = MoveRegs.pop_back_val();
1731 MRI->setRegClass(Reg, TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg)));
1732 }
1733
1734 LLVM_DEBUG(dbgs() << "Folded " << MI);
1735
1736 return true;
1737}
1738
1739bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
1740 if (skipFunction(MF.getFunction()))
1741 return false;
1742
1743 MRI = &MF.getRegInfo();
1744 ST = &MF.getSubtarget<GCNSubtarget>();
1745 TII = ST->getInstrInfo();
1746 TRI = &TII->getRegisterInfo();
1747 MFI = MF.getInfo<SIMachineFunctionInfo>();
1748
1749 // omod is ignored by hardware if IEEE bit is enabled. omod also does not
1750 // correctly handle signed zeros.
1751 //
1752 // FIXME: Also need to check strictfp
1753 bool IsIEEEMode = MFI->getMode().IEEE;
1754 bool HasNSZ = MFI->hasNoSignedZerosFPMath();
1755
1756 bool Changed = false;
1757 for (MachineBasicBlock *MBB : depth_first(&MF)) {
1758 MachineOperand *CurrentKnownM0Val = nullptr;
1759 for (auto &MI : make_early_inc_range(*MBB)) {
1760 Changed |= tryFoldCndMask(MI);
1761
1762 if (tryFoldZeroHighBits(MI)) {
1763 Changed = true;
1764 continue;
1765 }
1766
1767 if (MI.isRegSequence() && tryFoldRegSequence(MI)) {
1768 Changed = true;
1769 continue;
1770 }
1771
1772 if (MI.isPHI() && tryFoldLCSSAPhi(MI)) {
1773 Changed = true;
1774 continue;
1775 }
1776
1777 if (MI.mayLoad() && tryFoldLoad(MI)) {
1778 Changed = true;
1779 continue;
1780 }
1781
1782 if (TII->isFoldableCopy(MI)) {
1783 Changed |= tryFoldFoldableCopy(MI, CurrentKnownM0Val);
1784 continue;
1785 }
1786
1787 // Saw an unknown clobber of m0, so we no longer know what it is.
1788 if (CurrentKnownM0Val && MI.modifiesRegister(AMDGPU::M0, TRI))
1789 CurrentKnownM0Val = nullptr;
1790
1791 // TODO: Omod might be OK if there is NSZ only on the source
1792 // instruction, and not the omod multiply.
1793 if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) ||
1794 !tryFoldOMod(MI))
1795 Changed |= tryFoldClamp(MI);
1796 }
1797 }
1798
1799 return Changed;
1800}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Provides AMDGPU specific target descriptions.
Rewrite undef for PHI
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat)
Updates the operand at Idx in instruction Inst with the result of instruction Mat.
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
uint64_t Size
AMD GCN specific subclass of TargetSubtarget.
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
iv Induction Variable Users
Definition: IVUsers.cpp:48
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
static bool isReg(const MCInst &MI, unsigned OpNo)
Module * Mod
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
unsigned UseOpIdx
uint64_t TSFlags
static unsigned macToMad(unsigned Opc)
static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result, uint32_t LHS, uint32_t RHS)
static int getOModValue(unsigned Opc, int64_t Val)
static bool isUseMIInFoldList(ArrayRef< FoldCandidate > FoldList, const MachineInstr *MI)
static unsigned getMovOpc(bool IsScalar)
static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc)
#define DEBUG_TYPE
static void appendFoldCandidate(SmallVectorImpl< FoldCandidate > &FoldList, MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp, bool Commuted=false, int ShrinkOp=-1)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isImm(const MachineOperand &MO, MachineRegisterInfo *MRI)
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:75
Represent the analysis usage information of a pass.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:265
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A debug info location.
Definition: DebugLoc.h:33
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:151
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:308
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:198
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:237
ArrayRef< MCOperandInfo > operands() const
Definition: MCInstrDesc.h:239
ArrayRef< MCPhysReg > implicit_defs() const
Return a list of registers that are potentially written by any instance of this machine instruction.
Definition: MCInstrDesc.h:577
bool isVariadic() const
Return true if this instruction can have a variable number of operands.
Definition: MCInstrDesc.h:260
ArrayRef< MCPhysReg > implicit_uses() const
Return a list of registers that are potentially read by any instance of this machine instruction.
Definition: MCInstrDesc.h:565
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition: MCInstrDesc.h:85
LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI, MCRegister Reg, const_iterator Before, unsigned Neighborhood=10) const
Return whether (physical) register Reg has been defined and not killed as of just before Before.
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
@ LQR_Dead
Register is known to be fully dead.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Definition: MachineInstr.h:68
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:516
bool isCopy() const
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:313
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:519
unsigned getOperandNo(const_mop_iterator I) const
Returns the number of the operand iterator I points to.
Definition: MachineInstr.h:706
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:513
bool isRegSequence() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:445
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr reads the specified register.
void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
iterator_range< mop_iterator > implicit_operands()
Definition: MachineInstr.h:655
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:526
void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
void substVirtReg(Register Reg, unsigned SubIdx, const TargetRegisterInfo &)
substVirtReg - Substitute the current register with the virtual subregister Reg:SubReg.
void ChangeToFrameIndex(int Idx, unsigned TargetFlags=0)
Replace this operand with a frame index.
void setImm(int64_t immVal)
int64_t getImm() const
bool isImplicit() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void ChangeToImmediate(int64_t ImmVal, unsigned TargetFlags=0)
ChangeToImmediate - Replace this operand with a new immediate operand of the specified value.
void ChangeToGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
ChangeToGA - Replace this operand with a new global address operand.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static MachineOperand CreateImm(int64_t Val)
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
@ MO_Immediate
Immediate operand.
@ MO_GlobalAddress
Address of a global value.
@ MO_FrameIndex
Abstract Stack Frame Index.
@ MO_Register
Register operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:97
bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
SIModeRegisterDefaults getMode() const
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:141
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:301
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:941
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
Register getReg() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
static const unsigned CommuteAnyOperandIndex
unsigned getID() const
Return the register class ID number.
bool contains(Register Reg) const
Return true if the specified register is included in this register class.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ OPERAND_REGISTER
Definition: MCInstrDesc.h:61
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
Reg
All possible values of the reg field in the ModR/M byte.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
TargetInstrInfo::RegSubRegPair getRegSubRegPair(const MachineOperand &O)
Create RegSubRegPair from a register MachineOperand.
Definition: SIInstrInfo.h:1217
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool execMayBeModifiedBeforeUse(const MachineRegisterInfo &MRI, Register VReg, const MachineInstr &DefMI, const MachineInstr &UseMI)
Return false if EXEC is not changed between the def of VReg at DefMI and the use at UseMI.
char & SIFoldOperandsID
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:732
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1789
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createSIFoldOperandsPass()
void initializeSIFoldOperandsPass(PassRegistry &)
iterator_range< df_iterator< T > > depth_first(const T &G)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:853
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
bool IEEE
Floating point opcodes that support exception flag gathering quiet and propagate signaling NaN inputs...
A pair composed of a register and a sub-register index.