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 "AMDGPUSubtarget.h" 13 #include "SIInstrInfo.h" 14 #include "SIMachineFunctionInfo.h" 15 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 16 #include "llvm/ADT/DepthFirstIterator.h" 17 #include "llvm/CodeGen/LiveIntervals.h" 18 #include "llvm/CodeGen/MachineFunctionPass.h" 19 #include "llvm/CodeGen/MachineInstrBuilder.h" 20 #include "llvm/CodeGen/MachineRegisterInfo.h" 21 #include "llvm/Support/Debug.h" 22 #include "llvm/Support/raw_ostream.h" 23 #include "llvm/Target/TargetMachine.h" 24 25 #define DEBUG_TYPE "si-fold-operands" 26 using namespace llvm; 27 28 namespace { 29 30 struct FoldCandidate { 31 MachineInstr *UseMI; 32 union { 33 MachineOperand *OpToFold; 34 uint64_t ImmToFold; 35 int FrameIndexToFold; 36 }; 37 int ShrinkOpcode; 38 unsigned char UseOpNo; 39 MachineOperand::MachineOperandType Kind; 40 bool Commuted; 41 42 FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp, 43 bool Commuted_ = false, 44 int ShrinkOp = -1) : 45 UseMI(MI), OpToFold(nullptr), ShrinkOpcode(ShrinkOp), UseOpNo(OpNo), 46 Kind(FoldOp->getType()), 47 Commuted(Commuted_) { 48 if (FoldOp->isImm()) { 49 ImmToFold = FoldOp->getImm(); 50 } else if (FoldOp->isFI()) { 51 FrameIndexToFold = FoldOp->getIndex(); 52 } else { 53 assert(FoldOp->isReg() || FoldOp->isGlobal()); 54 OpToFold = FoldOp; 55 } 56 } 57 58 bool isFI() const { 59 return Kind == MachineOperand::MO_FrameIndex; 60 } 61 62 bool isImm() const { 63 return Kind == MachineOperand::MO_Immediate; 64 } 65 66 bool isReg() const { 67 return Kind == MachineOperand::MO_Register; 68 } 69 70 bool isGlobal() const { return Kind == MachineOperand::MO_GlobalAddress; } 71 72 bool isCommuted() const { 73 return Commuted; 74 } 75 76 bool needsShrink() const { 77 return ShrinkOpcode != -1; 78 } 79 80 int getShrinkOpcode() const { 81 return ShrinkOpcode; 82 } 83 }; 84 85 class SIFoldOperands : public MachineFunctionPass { 86 public: 87 static char ID; 88 MachineRegisterInfo *MRI; 89 const SIInstrInfo *TII; 90 const SIRegisterInfo *TRI; 91 const GCNSubtarget *ST; 92 const SIMachineFunctionInfo *MFI; 93 94 void foldOperand(MachineOperand &OpToFold, 95 MachineInstr *UseMI, 96 int UseOpIdx, 97 SmallVectorImpl<FoldCandidate> &FoldList, 98 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const; 99 100 void foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const; 101 102 const MachineOperand *isClamp(const MachineInstr &MI) const; 103 bool tryFoldClamp(MachineInstr &MI); 104 105 std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const; 106 bool tryFoldOMod(MachineInstr &MI); 107 108 public: 109 SIFoldOperands() : MachineFunctionPass(ID) { 110 initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry()); 111 } 112 113 bool runOnMachineFunction(MachineFunction &MF) override; 114 115 StringRef getPassName() const override { return "SI Fold Operands"; } 116 117 void getAnalysisUsage(AnalysisUsage &AU) const override { 118 AU.setPreservesCFG(); 119 MachineFunctionPass::getAnalysisUsage(AU); 120 } 121 }; 122 123 } // End anonymous namespace. 124 125 INITIALIZE_PASS(SIFoldOperands, DEBUG_TYPE, 126 "SI Fold Operands", false, false) 127 128 char SIFoldOperands::ID = 0; 129 130 char &llvm::SIFoldOperandsID = SIFoldOperands::ID; 131 132 // Wrapper around isInlineConstant that understands special cases when 133 // instruction types are replaced during operand folding. 134 static bool isInlineConstantIfFolded(const SIInstrInfo *TII, 135 const MachineInstr &UseMI, 136 unsigned OpNo, 137 const MachineOperand &OpToFold) { 138 if (TII->isInlineConstant(UseMI, OpNo, OpToFold)) 139 return true; 140 141 unsigned Opc = UseMI.getOpcode(); 142 switch (Opc) { 143 case AMDGPU::V_MAC_F32_e64: 144 case AMDGPU::V_MAC_F16_e64: 145 case AMDGPU::V_FMAC_F32_e64: { 146 // Special case for mac. Since this is replaced with mad when folded into 147 // src2, we need to check the legality for the final instruction. 148 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2); 149 if (static_cast<int>(OpNo) == Src2Idx) { 150 bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e64; 151 bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64; 152 153 unsigned Opc = IsFMA ? 154 AMDGPU::V_FMA_F32 : (IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16); 155 const MCInstrDesc &MadDesc = TII->get(Opc); 156 return TII->isInlineConstant(OpToFold, MadDesc.OpInfo[OpNo].OperandType); 157 } 158 return false; 159 } 160 default: 161 return false; 162 } 163 } 164 165 // TODO: Add heuristic that the frame index might not fit in the addressing mode 166 // immediate offset to avoid materializing in loops. 167 static bool frameIndexMayFold(const SIInstrInfo *TII, 168 const MachineInstr &UseMI, 169 int OpNo, 170 const MachineOperand &OpToFold) { 171 return OpToFold.isFI() && 172 (TII->isMUBUF(UseMI) || TII->isFLATScratch(UseMI)) && 173 OpNo == AMDGPU::getNamedOperandIdx(UseMI.getOpcode(), AMDGPU::OpName::vaddr); 174 } 175 176 FunctionPass *llvm::createSIFoldOperandsPass() { 177 return new SIFoldOperands(); 178 } 179 180 static bool updateOperand(FoldCandidate &Fold, 181 const SIInstrInfo &TII, 182 const TargetRegisterInfo &TRI, 183 const GCNSubtarget &ST) { 184 MachineInstr *MI = Fold.UseMI; 185 MachineOperand &Old = MI->getOperand(Fold.UseOpNo); 186 assert(Old.isReg()); 187 188 if (Fold.isImm()) { 189 if (MI->getDesc().TSFlags & SIInstrFlags::IsPacked && 190 !(MI->getDesc().TSFlags & SIInstrFlags::IsMAI) && 191 AMDGPU::isInlinableLiteralV216(static_cast<uint16_t>(Fold.ImmToFold), 192 ST.hasInv2PiInlineImm())) { 193 // Set op_sel/op_sel_hi on this operand or bail out if op_sel is 194 // already set. 195 unsigned Opcode = MI->getOpcode(); 196 int OpNo = MI->getOperandNo(&Old); 197 int ModIdx = -1; 198 if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0)) 199 ModIdx = AMDGPU::OpName::src0_modifiers; 200 else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1)) 201 ModIdx = AMDGPU::OpName::src1_modifiers; 202 else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2)) 203 ModIdx = AMDGPU::OpName::src2_modifiers; 204 assert(ModIdx != -1); 205 ModIdx = AMDGPU::getNamedOperandIdx(Opcode, ModIdx); 206 MachineOperand &Mod = MI->getOperand(ModIdx); 207 unsigned Val = Mod.getImm(); 208 if ((Val & SISrcMods::OP_SEL_0) || !(Val & SISrcMods::OP_SEL_1)) 209 return false; 210 // Only apply the following transformation if that operand requries 211 // a packed immediate. 212 switch (TII.get(Opcode).OpInfo[OpNo].OperandType) { 213 case AMDGPU::OPERAND_REG_IMM_V2FP16: 214 case AMDGPU::OPERAND_REG_IMM_V2INT16: 215 case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: 216 case AMDGPU::OPERAND_REG_INLINE_C_V2INT16: 217 // If upper part is all zero we do not need op_sel_hi. 218 if (!isUInt<16>(Fold.ImmToFold)) { 219 if (!(Fold.ImmToFold & 0xffff)) { 220 Mod.setImm(Mod.getImm() | SISrcMods::OP_SEL_0); 221 Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1); 222 Old.ChangeToImmediate((Fold.ImmToFold >> 16) & 0xffff); 223 return true; 224 } 225 Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1); 226 Old.ChangeToImmediate(Fold.ImmToFold & 0xffff); 227 return true; 228 } 229 break; 230 default: 231 break; 232 } 233 } 234 } 235 236 if ((Fold.isImm() || Fold.isFI() || Fold.isGlobal()) && Fold.needsShrink()) { 237 MachineBasicBlock *MBB = MI->getParent(); 238 auto Liveness = MBB->computeRegisterLiveness(&TRI, AMDGPU::VCC, MI); 239 if (Liveness != MachineBasicBlock::LQR_Dead) 240 return false; 241 242 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 243 int Op32 = Fold.getShrinkOpcode(); 244 MachineOperand &Dst0 = MI->getOperand(0); 245 MachineOperand &Dst1 = MI->getOperand(1); 246 assert(Dst0.isDef() && Dst1.isDef()); 247 248 bool HaveNonDbgCarryUse = !MRI.use_nodbg_empty(Dst1.getReg()); 249 250 const TargetRegisterClass *Dst0RC = MRI.getRegClass(Dst0.getReg()); 251 Register NewReg0 = MRI.createVirtualRegister(Dst0RC); 252 253 MachineInstr *Inst32 = TII.buildShrunkInst(*MI, Op32); 254 255 if (HaveNonDbgCarryUse) { 256 BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::COPY), Dst1.getReg()) 257 .addReg(AMDGPU::VCC, RegState::Kill); 258 } 259 260 // Keep the old instruction around to avoid breaking iterators, but 261 // replace it with a dummy instruction to remove uses. 262 // 263 // FIXME: We should not invert how this pass looks at operands to avoid 264 // this. Should track set of foldable movs instead of looking for uses 265 // when looking at a use. 266 Dst0.setReg(NewReg0); 267 for (unsigned I = MI->getNumOperands() - 1; I > 0; --I) 268 MI->RemoveOperand(I); 269 MI->setDesc(TII.get(AMDGPU::IMPLICIT_DEF)); 270 271 if (Fold.isCommuted()) 272 TII.commuteInstruction(*Inst32, false); 273 return true; 274 } 275 276 assert(!Fold.needsShrink() && "not handled"); 277 278 if (Fold.isImm()) { 279 Old.ChangeToImmediate(Fold.ImmToFold); 280 return true; 281 } 282 283 if (Fold.isGlobal()) { 284 Old.ChangeToGA(Fold.OpToFold->getGlobal(), Fold.OpToFold->getOffset(), 285 Fold.OpToFold->getTargetFlags()); 286 return true; 287 } 288 289 if (Fold.isFI()) { 290 Old.ChangeToFrameIndex(Fold.FrameIndexToFold); 291 return true; 292 } 293 294 MachineOperand *New = Fold.OpToFold; 295 Old.substVirtReg(New->getReg(), New->getSubReg(), TRI); 296 Old.setIsUndef(New->isUndef()); 297 return true; 298 } 299 300 static bool isUseMIInFoldList(ArrayRef<FoldCandidate> FoldList, 301 const MachineInstr *MI) { 302 for (auto Candidate : FoldList) { 303 if (Candidate.UseMI == MI) 304 return true; 305 } 306 return false; 307 } 308 309 static bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList, 310 MachineInstr *MI, unsigned OpNo, 311 MachineOperand *OpToFold, 312 const SIInstrInfo *TII) { 313 if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) { 314 // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2 315 unsigned Opc = MI->getOpcode(); 316 if ((Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64 || 317 Opc == AMDGPU::V_FMAC_F32_e64) && 318 (int)OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)) { 319 bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e64; 320 bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64; 321 unsigned NewOpc = IsFMA ? 322 AMDGPU::V_FMA_F32 : (IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16); 323 324 // Check if changing this to a v_mad_{f16, f32} instruction will allow us 325 // to fold the operand. 326 MI->setDesc(TII->get(NewOpc)); 327 bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold, TII); 328 if (FoldAsMAD) { 329 MI->untieRegOperand(OpNo); 330 return true; 331 } 332 MI->setDesc(TII->get(Opc)); 333 } 334 335 // Special case for s_setreg_b32 336 if (Opc == AMDGPU::S_SETREG_B32 && OpToFold->isImm()) { 337 MI->setDesc(TII->get(AMDGPU::S_SETREG_IMM32_B32)); 338 FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold)); 339 return true; 340 } 341 342 // If we are already folding into another operand of MI, then 343 // we can't commute the instruction, otherwise we risk making the 344 // other fold illegal. 345 if (isUseMIInFoldList(FoldList, MI)) 346 return false; 347 348 unsigned CommuteOpNo = OpNo; 349 350 // Operand is not legal, so try to commute the instruction to 351 // see if this makes it possible to fold. 352 unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex; 353 unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex; 354 bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1); 355 356 if (CanCommute) { 357 if (CommuteIdx0 == OpNo) 358 CommuteOpNo = CommuteIdx1; 359 else if (CommuteIdx1 == OpNo) 360 CommuteOpNo = CommuteIdx0; 361 } 362 363 364 // One of operands might be an Imm operand, and OpNo may refer to it after 365 // the call of commuteInstruction() below. Such situations are avoided 366 // here explicitly as OpNo must be a register operand to be a candidate 367 // for memory folding. 368 if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() || 369 !MI->getOperand(CommuteIdx1).isReg())) 370 return false; 371 372 if (!CanCommute || 373 !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1)) 374 return false; 375 376 if (!TII->isOperandLegal(*MI, CommuteOpNo, OpToFold)) { 377 if ((Opc == AMDGPU::V_ADD_I32_e64 || 378 Opc == AMDGPU::V_SUB_I32_e64 || 379 Opc == AMDGPU::V_SUBREV_I32_e64) && // FIXME 380 (OpToFold->isImm() || OpToFold->isFI() || OpToFold->isGlobal())) { 381 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo(); 382 383 // Verify the other operand is a VGPR, otherwise we would violate the 384 // constant bus restriction. 385 unsigned OtherIdx = CommuteOpNo == CommuteIdx0 ? CommuteIdx1 : CommuteIdx0; 386 MachineOperand &OtherOp = MI->getOperand(OtherIdx); 387 if (!OtherOp.isReg() || 388 !TII->getRegisterInfo().isVGPR(MRI, OtherOp.getReg())) 389 return false; 390 391 assert(MI->getOperand(1).isDef()); 392 393 // Make sure to get the 32-bit version of the commuted opcode. 394 unsigned MaybeCommutedOpc = MI->getOpcode(); 395 int Op32 = AMDGPU::getVOPe32(MaybeCommutedOpc); 396 397 FoldList.push_back(FoldCandidate(MI, CommuteOpNo, OpToFold, true, 398 Op32)); 399 return true; 400 } 401 402 TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1); 403 return false; 404 } 405 406 FoldList.push_back(FoldCandidate(MI, CommuteOpNo, OpToFold, true)); 407 return true; 408 } 409 410 FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold)); 411 return true; 412 } 413 414 // If the use operand doesn't care about the value, this may be an operand only 415 // used for register indexing, in which case it is unsafe to fold. 416 static bool isUseSafeToFold(const SIInstrInfo *TII, 417 const MachineInstr &MI, 418 const MachineOperand &UseMO) { 419 return !UseMO.isUndef() && !TII->isSDWA(MI); 420 //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg()); 421 } 422 423 static bool tryToFoldACImm(const SIInstrInfo *TII, 424 const MachineOperand &OpToFold, 425 MachineInstr *UseMI, 426 unsigned UseOpIdx, 427 SmallVectorImpl<FoldCandidate> &FoldList) { 428 const MCInstrDesc &Desc = UseMI->getDesc(); 429 const MCOperandInfo *OpInfo = Desc.OpInfo; 430 if (!OpInfo || UseOpIdx >= Desc.getNumOperands()) 431 return false; 432 433 uint8_t OpTy = OpInfo[UseOpIdx].OperandType; 434 if (OpTy < AMDGPU::OPERAND_REG_INLINE_AC_FIRST || 435 OpTy > AMDGPU::OPERAND_REG_INLINE_AC_LAST) 436 return false; 437 438 if (OpToFold.isImm() && TII->isInlineConstant(OpToFold, OpTy)) { 439 UseMI->getOperand(UseOpIdx).ChangeToImmediate(OpToFold.getImm()); 440 return true; 441 } 442 443 if (!OpToFold.isReg()) 444 return false; 445 446 Register UseReg = OpToFold.getReg(); 447 if (!Register::isVirtualRegister(UseReg)) 448 return false; 449 450 if (llvm::find_if(FoldList, [UseMI](const FoldCandidate &FC) { 451 return FC.UseMI == UseMI; }) != FoldList.end()) 452 return false; 453 454 MachineRegisterInfo &MRI = UseMI->getParent()->getParent()->getRegInfo(); 455 const MachineInstr *Def = MRI.getUniqueVRegDef(UseReg); 456 if (!Def || !Def->isRegSequence()) 457 return false; 458 459 int64_t Imm; 460 MachineOperand *Op; 461 for (unsigned I = 1, E = Def->getNumExplicitOperands(); I < E; I += 2) { 462 const MachineOperand &Sub = Def->getOperand(I); 463 if (!Sub.isReg() || Sub.getSubReg()) 464 return false; 465 MachineInstr *SubDef = MRI.getUniqueVRegDef(Sub.getReg()); 466 while (SubDef && !SubDef->isMoveImmediate() && 467 !SubDef->getOperand(1).isImm() && TII->isFoldableCopy(*SubDef)) 468 SubDef = MRI.getUniqueVRegDef(SubDef->getOperand(1).getReg()); 469 if (!SubDef || !SubDef->isMoveImmediate() || !SubDef->getOperand(1).isImm()) 470 return false; 471 Op = &SubDef->getOperand(1); 472 auto SubImm = Op->getImm(); 473 if (I == 1) { 474 if (!TII->isInlineConstant(SubDef->getOperand(1), OpTy)) 475 return false; 476 477 Imm = SubImm; 478 continue; 479 } 480 if (Imm != SubImm) 481 return false; // Can only fold splat constants 482 } 483 484 FoldList.push_back(FoldCandidate(UseMI, UseOpIdx, Op)); 485 return true; 486 } 487 488 void SIFoldOperands::foldOperand( 489 MachineOperand &OpToFold, 490 MachineInstr *UseMI, 491 int UseOpIdx, 492 SmallVectorImpl<FoldCandidate> &FoldList, 493 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const { 494 const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx); 495 496 if (!isUseSafeToFold(TII, *UseMI, UseOp)) 497 return; 498 499 // FIXME: Fold operands with subregs. 500 if (UseOp.isReg() && OpToFold.isReg()) { 501 if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister) 502 return; 503 504 // Don't fold subregister extracts into tied operands, only if it is a full 505 // copy since a subregister use tied to a full register def doesn't really 506 // make sense. e.g. don't fold: 507 // 508 // %1 = COPY %0:sub1 509 // %2<tied3> = V_MAC_{F16, F32} %3, %4, %1<tied0> 510 // 511 // into 512 // %2<tied3> = V_MAC_{F16, F32} %3, %4, %0:sub1<tied0> 513 if (UseOp.isTied() && OpToFold.getSubReg() != AMDGPU::NoSubRegister) 514 return; 515 } 516 517 // Special case for REG_SEQUENCE: We can't fold literals into 518 // REG_SEQUENCE instructions, so we have to fold them into the 519 // uses of REG_SEQUENCE. 520 if (UseMI->isRegSequence()) { 521 Register RegSeqDstReg = UseMI->getOperand(0).getReg(); 522 unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm(); 523 524 MachineRegisterInfo::use_iterator Next; 525 for (MachineRegisterInfo::use_iterator 526 RSUse = MRI->use_begin(RegSeqDstReg), RSE = MRI->use_end(); 527 RSUse != RSE; RSUse = Next) { 528 Next = std::next(RSUse); 529 530 MachineInstr *RSUseMI = RSUse->getParent(); 531 532 if (tryToFoldACImm(TII, UseMI->getOperand(0), RSUseMI, 533 RSUse.getOperandNo(), FoldList)) 534 continue; 535 536 if (RSUse->getSubReg() != RegSeqDstSubReg) 537 continue; 538 539 foldOperand(OpToFold, RSUseMI, RSUse.getOperandNo(), FoldList, 540 CopiesToReplace); 541 } 542 543 return; 544 } 545 546 if (tryToFoldACImm(TII, OpToFold, UseMI, UseOpIdx, FoldList)) 547 return; 548 549 if (frameIndexMayFold(TII, *UseMI, UseOpIdx, OpToFold)) { 550 // Sanity check that this is a stack access. 551 // FIXME: Should probably use stack pseudos before frame lowering. 552 MachineOperand *SOff = TII->getNamedOperand(*UseMI, AMDGPU::OpName::soffset); 553 if (!SOff->isReg() || (SOff->getReg() != MFI->getScratchWaveOffsetReg() && 554 SOff->getReg() != MFI->getStackPtrOffsetReg())) 555 return; 556 557 if (TII->getNamedOperand(*UseMI, AMDGPU::OpName::srsrc)->getReg() != 558 MFI->getScratchRSrcReg()) 559 return; 560 561 // A frame index will resolve to a positive constant, so it should always be 562 // safe to fold the addressing mode, even pre-GFX9. 563 UseMI->getOperand(UseOpIdx).ChangeToFrameIndex(OpToFold.getIndex()); 564 SOff->setReg(MFI->getStackPtrOffsetReg()); 565 return; 566 } 567 568 bool FoldingImmLike = 569 OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal(); 570 571 if (FoldingImmLike && UseMI->isCopy()) { 572 Register DestReg = UseMI->getOperand(0).getReg(); 573 const TargetRegisterClass *DestRC = Register::isVirtualRegister(DestReg) 574 ? MRI->getRegClass(DestReg) 575 : TRI->getPhysRegClass(DestReg); 576 577 Register SrcReg = UseMI->getOperand(1).getReg(); 578 if (Register::isVirtualRegister(DestReg) && 579 Register::isVirtualRegister(SrcReg)) { 580 const TargetRegisterClass * SrcRC = MRI->getRegClass(SrcReg); 581 if (TRI->isSGPRClass(SrcRC) && TRI->hasVectorRegisters(DestRC)) { 582 MachineRegisterInfo::use_iterator NextUse; 583 SmallVector<FoldCandidate, 4> CopyUses; 584 for (MachineRegisterInfo::use_iterator 585 Use = MRI->use_begin(DestReg), E = MRI->use_end(); 586 Use != E; Use = NextUse) { 587 NextUse = std::next(Use); 588 FoldCandidate FC = FoldCandidate(Use->getParent(), 589 Use.getOperandNo(), &UseMI->getOperand(1)); 590 CopyUses.push_back(FC); 591 } 592 for (auto & F : CopyUses) { 593 foldOperand(*F.OpToFold, F.UseMI, F.UseOpNo, 594 FoldList, CopiesToReplace); 595 } 596 } 597 } 598 599 if (DestRC == &AMDGPU::AGPR_32RegClass && 600 TII->isInlineConstant(OpToFold, AMDGPU::OPERAND_REG_INLINE_C_INT32)) { 601 UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32)); 602 UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm()); 603 CopiesToReplace.push_back(UseMI); 604 return; 605 } 606 607 // In order to fold immediates into copies, we need to change the 608 // copy to a MOV. 609 610 unsigned MovOp = TII->getMovOpcode(DestRC); 611 if (MovOp == AMDGPU::COPY) 612 return; 613 614 UseMI->setDesc(TII->get(MovOp)); 615 MachineInstr::mop_iterator ImpOpI = UseMI->implicit_operands().begin(); 616 MachineInstr::mop_iterator ImpOpE = UseMI->implicit_operands().end(); 617 while (ImpOpI != ImpOpE) { 618 MachineInstr::mop_iterator Tmp = ImpOpI; 619 ImpOpI++; 620 UseMI->RemoveOperand(UseMI->getOperandNo(Tmp)); 621 } 622 CopiesToReplace.push_back(UseMI); 623 } else { 624 if (UseMI->isCopy() && OpToFold.isReg() && 625 Register::isVirtualRegister(UseMI->getOperand(0).getReg()) && 626 TRI->isVectorRegister(*MRI, UseMI->getOperand(0).getReg()) && 627 TRI->isVectorRegister(*MRI, UseMI->getOperand(1).getReg()) && 628 !UseMI->getOperand(1).getSubReg()) { 629 unsigned Size = TII->getOpSize(*UseMI, 1); 630 UseMI->getOperand(1).setReg(OpToFold.getReg()); 631 UseMI->getOperand(1).setSubReg(OpToFold.getSubReg()); 632 UseMI->getOperand(1).setIsKill(false); 633 CopiesToReplace.push_back(UseMI); 634 OpToFold.setIsKill(false); 635 if (Size != 4) 636 return; 637 if (TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) && 638 TRI->isVGPR(*MRI, UseMI->getOperand(1).getReg())) 639 UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32)); 640 else if (TRI->isVGPR(*MRI, UseMI->getOperand(0).getReg()) && 641 TRI->isAGPR(*MRI, UseMI->getOperand(1).getReg())) 642 UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_READ_B32)); 643 return; 644 } 645 646 unsigned UseOpc = UseMI->getOpcode(); 647 if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 || 648 (UseOpc == AMDGPU::V_READLANE_B32 && 649 (int)UseOpIdx == 650 AMDGPU::getNamedOperandIdx(UseOpc, AMDGPU::OpName::src0))) { 651 // %vgpr = V_MOV_B32 imm 652 // %sgpr = V_READFIRSTLANE_B32 %vgpr 653 // => 654 // %sgpr = S_MOV_B32 imm 655 if (FoldingImmLike) { 656 if (execMayBeModifiedBeforeUse(*MRI, 657 UseMI->getOperand(UseOpIdx).getReg(), 658 *OpToFold.getParent(), 659 *UseMI)) 660 return; 661 662 UseMI->setDesc(TII->get(AMDGPU::S_MOV_B32)); 663 664 // FIXME: ChangeToImmediate should clear subreg 665 UseMI->getOperand(1).setSubReg(0); 666 if (OpToFold.isImm()) 667 UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm()); 668 else 669 UseMI->getOperand(1).ChangeToFrameIndex(OpToFold.getIndex()); 670 UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane) 671 return; 672 } 673 674 if (OpToFold.isReg() && TRI->isSGPRReg(*MRI, OpToFold.getReg())) { 675 if (execMayBeModifiedBeforeUse(*MRI, 676 UseMI->getOperand(UseOpIdx).getReg(), 677 *OpToFold.getParent(), 678 *UseMI)) 679 return; 680 681 // %vgpr = COPY %sgpr0 682 // %sgpr1 = V_READFIRSTLANE_B32 %vgpr 683 // => 684 // %sgpr1 = COPY %sgpr0 685 UseMI->setDesc(TII->get(AMDGPU::COPY)); 686 UseMI->getOperand(1).setReg(OpToFold.getReg()); 687 UseMI->getOperand(1).setSubReg(OpToFold.getSubReg()); 688 UseMI->getOperand(1).setIsKill(false); 689 UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane) 690 return; 691 } 692 } 693 694 const MCInstrDesc &UseDesc = UseMI->getDesc(); 695 696 // Don't fold into target independent nodes. Target independent opcodes 697 // don't have defined register classes. 698 if (UseDesc.isVariadic() || 699 UseOp.isImplicit() || 700 UseDesc.OpInfo[UseOpIdx].RegClass == -1) 701 return; 702 } 703 704 if (!FoldingImmLike) { 705 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII); 706 707 // FIXME: We could try to change the instruction from 64-bit to 32-bit 708 // to enable more folding opportunites. The shrink operands pass 709 // already does this. 710 return; 711 } 712 713 714 const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc(); 715 const TargetRegisterClass *FoldRC = 716 TRI->getRegClass(FoldDesc.OpInfo[0].RegClass); 717 718 // Split 64-bit constants into 32-bits for folding. 719 if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) { 720 Register UseReg = UseOp.getReg(); 721 const TargetRegisterClass *UseRC = MRI->getRegClass(UseReg); 722 723 if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64) 724 return; 725 726 APInt Imm(64, OpToFold.getImm()); 727 if (UseOp.getSubReg() == AMDGPU::sub0) { 728 Imm = Imm.getLoBits(32); 729 } else { 730 assert(UseOp.getSubReg() == AMDGPU::sub1); 731 Imm = Imm.getHiBits(32); 732 } 733 734 MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue()); 735 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII); 736 return; 737 } 738 739 740 741 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII); 742 } 743 744 static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result, 745 uint32_t LHS, uint32_t RHS) { 746 switch (Opcode) { 747 case AMDGPU::V_AND_B32_e64: 748 case AMDGPU::V_AND_B32_e32: 749 case AMDGPU::S_AND_B32: 750 Result = LHS & RHS; 751 return true; 752 case AMDGPU::V_OR_B32_e64: 753 case AMDGPU::V_OR_B32_e32: 754 case AMDGPU::S_OR_B32: 755 Result = LHS | RHS; 756 return true; 757 case AMDGPU::V_XOR_B32_e64: 758 case AMDGPU::V_XOR_B32_e32: 759 case AMDGPU::S_XOR_B32: 760 Result = LHS ^ RHS; 761 return true; 762 case AMDGPU::V_LSHL_B32_e64: 763 case AMDGPU::V_LSHL_B32_e32: 764 case AMDGPU::S_LSHL_B32: 765 // The instruction ignores the high bits for out of bounds shifts. 766 Result = LHS << (RHS & 31); 767 return true; 768 case AMDGPU::V_LSHLREV_B32_e64: 769 case AMDGPU::V_LSHLREV_B32_e32: 770 Result = RHS << (LHS & 31); 771 return true; 772 case AMDGPU::V_LSHR_B32_e64: 773 case AMDGPU::V_LSHR_B32_e32: 774 case AMDGPU::S_LSHR_B32: 775 Result = LHS >> (RHS & 31); 776 return true; 777 case AMDGPU::V_LSHRREV_B32_e64: 778 case AMDGPU::V_LSHRREV_B32_e32: 779 Result = RHS >> (LHS & 31); 780 return true; 781 case AMDGPU::V_ASHR_I32_e64: 782 case AMDGPU::V_ASHR_I32_e32: 783 case AMDGPU::S_ASHR_I32: 784 Result = static_cast<int32_t>(LHS) >> (RHS & 31); 785 return true; 786 case AMDGPU::V_ASHRREV_I32_e64: 787 case AMDGPU::V_ASHRREV_I32_e32: 788 Result = static_cast<int32_t>(RHS) >> (LHS & 31); 789 return true; 790 default: 791 return false; 792 } 793 } 794 795 static unsigned getMovOpc(bool IsScalar) { 796 return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32; 797 } 798 799 /// Remove any leftover implicit operands from mutating the instruction. e.g. 800 /// if we replace an s_and_b32 with a copy, we don't need the implicit scc def 801 /// anymore. 802 static void stripExtraCopyOperands(MachineInstr &MI) { 803 const MCInstrDesc &Desc = MI.getDesc(); 804 unsigned NumOps = Desc.getNumOperands() + 805 Desc.getNumImplicitUses() + 806 Desc.getNumImplicitDefs(); 807 808 for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I) 809 MI.RemoveOperand(I); 810 } 811 812 static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) { 813 MI.setDesc(NewDesc); 814 stripExtraCopyOperands(MI); 815 } 816 817 static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI, 818 MachineOperand &Op) { 819 if (Op.isReg()) { 820 // If this has a subregister, it obviously is a register source. 821 if (Op.getSubReg() != AMDGPU::NoSubRegister || 822 !Register::isVirtualRegister(Op.getReg())) 823 return &Op; 824 825 MachineInstr *Def = MRI.getVRegDef(Op.getReg()); 826 if (Def && Def->isMoveImmediate()) { 827 MachineOperand &ImmSrc = Def->getOperand(1); 828 if (ImmSrc.isImm()) 829 return &ImmSrc; 830 } 831 } 832 833 return &Op; 834 } 835 836 // Try to simplify operations with a constant that may appear after instruction 837 // selection. 838 // TODO: See if a frame index with a fixed offset can fold. 839 static bool tryConstantFoldOp(MachineRegisterInfo &MRI, 840 const SIInstrInfo *TII, 841 MachineInstr *MI, 842 MachineOperand *ImmOp) { 843 unsigned Opc = MI->getOpcode(); 844 if (Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 || 845 Opc == AMDGPU::S_NOT_B32) { 846 MI->getOperand(1).ChangeToImmediate(~ImmOp->getImm()); 847 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32))); 848 return true; 849 } 850 851 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1); 852 if (Src1Idx == -1) 853 return false; 854 855 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0); 856 MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx)); 857 MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx)); 858 859 if (!Src0->isImm() && !Src1->isImm()) 860 return false; 861 862 if (MI->getOpcode() == AMDGPU::V_LSHL_OR_B32) { 863 if (Src0->isImm() && Src0->getImm() == 0) { 864 // v_lshl_or_b32 0, X, Y -> copy Y 865 // v_lshl_or_b32 0, X, K -> v_mov_b32 K 866 bool UseCopy = TII->getNamedOperand(*MI, AMDGPU::OpName::src2)->isReg(); 867 MI->RemoveOperand(Src1Idx); 868 MI->RemoveOperand(Src0Idx); 869 870 MI->setDesc(TII->get(UseCopy ? AMDGPU::COPY : AMDGPU::V_MOV_B32_e32)); 871 return true; 872 } 873 } 874 875 // and k0, k1 -> v_mov_b32 (k0 & k1) 876 // or k0, k1 -> v_mov_b32 (k0 | k1) 877 // xor k0, k1 -> v_mov_b32 (k0 ^ k1) 878 if (Src0->isImm() && Src1->isImm()) { 879 int32_t NewImm; 880 if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm())) 881 return false; 882 883 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 884 bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg()); 885 886 // Be careful to change the right operand, src0 may belong to a different 887 // instruction. 888 MI->getOperand(Src0Idx).ChangeToImmediate(NewImm); 889 MI->RemoveOperand(Src1Idx); 890 mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR))); 891 return true; 892 } 893 894 if (!MI->isCommutable()) 895 return false; 896 897 if (Src0->isImm() && !Src1->isImm()) { 898 std::swap(Src0, Src1); 899 std::swap(Src0Idx, Src1Idx); 900 } 901 902 int32_t Src1Val = static_cast<int32_t>(Src1->getImm()); 903 if (Opc == AMDGPU::V_OR_B32_e64 || 904 Opc == AMDGPU::V_OR_B32_e32 || 905 Opc == AMDGPU::S_OR_B32) { 906 if (Src1Val == 0) { 907 // y = or x, 0 => y = copy x 908 MI->RemoveOperand(Src1Idx); 909 mutateCopyOp(*MI, TII->get(AMDGPU::COPY)); 910 } else if (Src1Val == -1) { 911 // y = or x, -1 => y = v_mov_b32 -1 912 MI->RemoveOperand(Src1Idx); 913 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32))); 914 } else 915 return false; 916 917 return true; 918 } 919 920 if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 || 921 MI->getOpcode() == AMDGPU::V_AND_B32_e32 || 922 MI->getOpcode() == AMDGPU::S_AND_B32) { 923 if (Src1Val == 0) { 924 // y = and x, 0 => y = v_mov_b32 0 925 MI->RemoveOperand(Src0Idx); 926 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32))); 927 } else if (Src1Val == -1) { 928 // y = and x, -1 => y = copy x 929 MI->RemoveOperand(Src1Idx); 930 mutateCopyOp(*MI, TII->get(AMDGPU::COPY)); 931 stripExtraCopyOperands(*MI); 932 } else 933 return false; 934 935 return true; 936 } 937 938 if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 || 939 MI->getOpcode() == AMDGPU::V_XOR_B32_e32 || 940 MI->getOpcode() == AMDGPU::S_XOR_B32) { 941 if (Src1Val == 0) { 942 // y = xor x, 0 => y = copy x 943 MI->RemoveOperand(Src1Idx); 944 mutateCopyOp(*MI, TII->get(AMDGPU::COPY)); 945 return true; 946 } 947 } 948 949 return false; 950 } 951 952 // Try to fold an instruction into a simpler one 953 static bool tryFoldInst(const SIInstrInfo *TII, 954 MachineInstr *MI) { 955 unsigned Opc = MI->getOpcode(); 956 957 if (Opc == AMDGPU::V_CNDMASK_B32_e32 || 958 Opc == AMDGPU::V_CNDMASK_B32_e64 || 959 Opc == AMDGPU::V_CNDMASK_B64_PSEUDO) { 960 const MachineOperand *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0); 961 const MachineOperand *Src1 = TII->getNamedOperand(*MI, AMDGPU::OpName::src1); 962 int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers); 963 int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers); 964 if (Src1->isIdenticalTo(*Src0) && 965 (Src1ModIdx == -1 || !MI->getOperand(Src1ModIdx).getImm()) && 966 (Src0ModIdx == -1 || !MI->getOperand(Src0ModIdx).getImm())) { 967 LLVM_DEBUG(dbgs() << "Folded " << *MI << " into "); 968 auto &NewDesc = 969 TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(false)); 970 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2); 971 if (Src2Idx != -1) 972 MI->RemoveOperand(Src2Idx); 973 MI->RemoveOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1)); 974 if (Src1ModIdx != -1) 975 MI->RemoveOperand(Src1ModIdx); 976 if (Src0ModIdx != -1) 977 MI->RemoveOperand(Src0ModIdx); 978 mutateCopyOp(*MI, NewDesc); 979 LLVM_DEBUG(dbgs() << *MI << '\n'); 980 return true; 981 } 982 } 983 984 return false; 985 } 986 987 void SIFoldOperands::foldInstOperand(MachineInstr &MI, 988 MachineOperand &OpToFold) const { 989 // We need mutate the operands of new mov instructions to add implicit 990 // uses of EXEC, but adding them invalidates the use_iterator, so defer 991 // this. 992 SmallVector<MachineInstr *, 4> CopiesToReplace; 993 SmallVector<FoldCandidate, 4> FoldList; 994 MachineOperand &Dst = MI.getOperand(0); 995 996 bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal(); 997 if (FoldingImm) { 998 unsigned NumLiteralUses = 0; 999 MachineOperand *NonInlineUse = nullptr; 1000 int NonInlineUseOpNo = -1; 1001 1002 MachineRegisterInfo::use_iterator NextUse; 1003 for (MachineRegisterInfo::use_iterator 1004 Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end(); 1005 Use != E; Use = NextUse) { 1006 NextUse = std::next(Use); 1007 MachineInstr *UseMI = Use->getParent(); 1008 unsigned OpNo = Use.getOperandNo(); 1009 1010 // Folding the immediate may reveal operations that can be constant 1011 // folded or replaced with a copy. This can happen for example after 1012 // frame indices are lowered to constants or from splitting 64-bit 1013 // constants. 1014 // 1015 // We may also encounter cases where one or both operands are 1016 // immediates materialized into a register, which would ordinarily not 1017 // be folded due to multiple uses or operand constraints. 1018 1019 if (OpToFold.isImm() && tryConstantFoldOp(*MRI, TII, UseMI, &OpToFold)) { 1020 LLVM_DEBUG(dbgs() << "Constant folded " << *UseMI << '\n'); 1021 1022 // Some constant folding cases change the same immediate's use to a new 1023 // instruction, e.g. and x, 0 -> 0. Make sure we re-visit the user 1024 // again. The same constant folded instruction could also have a second 1025 // use operand. 1026 NextUse = MRI->use_begin(Dst.getReg()); 1027 FoldList.clear(); 1028 continue; 1029 } 1030 1031 // Try to fold any inline immediate uses, and then only fold other 1032 // constants if they have one use. 1033 // 1034 // The legality of the inline immediate must be checked based on the use 1035 // operand, not the defining instruction, because 32-bit instructions 1036 // with 32-bit inline immediate sources may be used to materialize 1037 // constants used in 16-bit operands. 1038 // 1039 // e.g. it is unsafe to fold: 1040 // s_mov_b32 s0, 1.0 // materializes 0x3f800000 1041 // v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00 1042 1043 // Folding immediates with more than one use will increase program size. 1044 // FIXME: This will also reduce register usage, which may be better 1045 // in some cases. A better heuristic is needed. 1046 if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) { 1047 foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace); 1048 } else if (frameIndexMayFold(TII, *UseMI, OpNo, OpToFold)) { 1049 foldOperand(OpToFold, UseMI, OpNo, FoldList, 1050 CopiesToReplace); 1051 } else { 1052 if (++NumLiteralUses == 1) { 1053 NonInlineUse = &*Use; 1054 NonInlineUseOpNo = OpNo; 1055 } 1056 } 1057 } 1058 1059 if (NumLiteralUses == 1) { 1060 MachineInstr *UseMI = NonInlineUse->getParent(); 1061 foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace); 1062 } 1063 } else { 1064 // Folding register. 1065 SmallVector <MachineRegisterInfo::use_iterator, 4> UsesToProcess; 1066 for (MachineRegisterInfo::use_iterator 1067 Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end(); 1068 Use != E; ++Use) { 1069 UsesToProcess.push_back(Use); 1070 } 1071 for (auto U : UsesToProcess) { 1072 MachineInstr *UseMI = U->getParent(); 1073 1074 foldOperand(OpToFold, UseMI, U.getOperandNo(), 1075 FoldList, CopiesToReplace); 1076 } 1077 } 1078 1079 MachineFunction *MF = MI.getParent()->getParent(); 1080 // Make sure we add EXEC uses to any new v_mov instructions created. 1081 for (MachineInstr *Copy : CopiesToReplace) 1082 Copy->addImplicitDefUseOperands(*MF); 1083 1084 for (FoldCandidate &Fold : FoldList) { 1085 if (updateOperand(Fold, *TII, *TRI, *ST)) { 1086 // Clear kill flags. 1087 if (Fold.isReg()) { 1088 assert(Fold.OpToFold && Fold.OpToFold->isReg()); 1089 // FIXME: Probably shouldn't bother trying to fold if not an 1090 // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR 1091 // copies. 1092 MRI->clearKillFlags(Fold.OpToFold->getReg()); 1093 } 1094 LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo " 1095 << static_cast<int>(Fold.UseOpNo) << " of " 1096 << *Fold.UseMI << '\n'); 1097 tryFoldInst(TII, Fold.UseMI); 1098 } else if (Fold.isCommuted()) { 1099 // Restoring instruction's original operand order if fold has failed. 1100 TII->commuteInstruction(*Fold.UseMI, false); 1101 } 1102 } 1103 } 1104 1105 // Clamp patterns are canonically selected to v_max_* instructions, so only 1106 // handle them. 1107 const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const { 1108 unsigned Op = MI.getOpcode(); 1109 switch (Op) { 1110 case AMDGPU::V_MAX_F32_e64: 1111 case AMDGPU::V_MAX_F16_e64: 1112 case AMDGPU::V_MAX_F64: 1113 case AMDGPU::V_PK_MAX_F16: { 1114 if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm()) 1115 return nullptr; 1116 1117 // Make sure sources are identical. 1118 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0); 1119 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); 1120 if (!Src0->isReg() || !Src1->isReg() || 1121 Src0->getReg() != Src1->getReg() || 1122 Src0->getSubReg() != Src1->getSubReg() || 1123 Src0->getSubReg() != AMDGPU::NoSubRegister) 1124 return nullptr; 1125 1126 // Can't fold up if we have modifiers. 1127 if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod)) 1128 return nullptr; 1129 1130 unsigned Src0Mods 1131 = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm(); 1132 unsigned Src1Mods 1133 = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm(); 1134 1135 // Having a 0 op_sel_hi would require swizzling the output in the source 1136 // instruction, which we can't do. 1137 unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1 1138 : 0u; 1139 if (Src0Mods != UnsetMods && Src1Mods != UnsetMods) 1140 return nullptr; 1141 return Src0; 1142 } 1143 default: 1144 return nullptr; 1145 } 1146 } 1147 1148 // We obviously have multiple uses in a clamp since the register is used twice 1149 // in the same instruction. 1150 static bool hasOneNonDBGUseInst(const MachineRegisterInfo &MRI, unsigned Reg) { 1151 int Count = 0; 1152 for (auto I = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end(); 1153 I != E; ++I) { 1154 if (++Count > 1) 1155 return false; 1156 } 1157 1158 return true; 1159 } 1160 1161 // FIXME: Clamp for v_mad_mixhi_f16 handled during isel. 1162 bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) { 1163 const MachineOperand *ClampSrc = isClamp(MI); 1164 if (!ClampSrc || !hasOneNonDBGUseInst(*MRI, ClampSrc->getReg())) 1165 return false; 1166 1167 MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg()); 1168 1169 // The type of clamp must be compatible. 1170 if (TII->getClampMask(*Def) != TII->getClampMask(MI)) 1171 return false; 1172 1173 MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp); 1174 if (!DefClamp) 1175 return false; 1176 1177 LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def 1178 << '\n'); 1179 1180 // Clamp is applied after omod, so it is OK if omod is set. 1181 DefClamp->setImm(1); 1182 MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg()); 1183 MI.eraseFromParent(); 1184 return true; 1185 } 1186 1187 static int getOModValue(unsigned Opc, int64_t Val) { 1188 switch (Opc) { 1189 case AMDGPU::V_MUL_F32_e64: { 1190 switch (static_cast<uint32_t>(Val)) { 1191 case 0x3f000000: // 0.5 1192 return SIOutMods::DIV2; 1193 case 0x40000000: // 2.0 1194 return SIOutMods::MUL2; 1195 case 0x40800000: // 4.0 1196 return SIOutMods::MUL4; 1197 default: 1198 return SIOutMods::NONE; 1199 } 1200 } 1201 case AMDGPU::V_MUL_F16_e64: { 1202 switch (static_cast<uint16_t>(Val)) { 1203 case 0x3800: // 0.5 1204 return SIOutMods::DIV2; 1205 case 0x4000: // 2.0 1206 return SIOutMods::MUL2; 1207 case 0x4400: // 4.0 1208 return SIOutMods::MUL4; 1209 default: 1210 return SIOutMods::NONE; 1211 } 1212 } 1213 default: 1214 llvm_unreachable("invalid mul opcode"); 1215 } 1216 } 1217 1218 // FIXME: Does this really not support denormals with f16? 1219 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not 1220 // handled, so will anything other than that break? 1221 std::pair<const MachineOperand *, int> 1222 SIFoldOperands::isOMod(const MachineInstr &MI) const { 1223 unsigned Op = MI.getOpcode(); 1224 switch (Op) { 1225 case AMDGPU::V_MUL_F32_e64: 1226 case AMDGPU::V_MUL_F16_e64: { 1227 // If output denormals are enabled, omod is ignored. 1228 if ((Op == AMDGPU::V_MUL_F32_e64 && ST->hasFP32Denormals()) || 1229 (Op == AMDGPU::V_MUL_F16_e64 && ST->hasFP16Denormals())) 1230 return std::make_pair(nullptr, SIOutMods::NONE); 1231 1232 const MachineOperand *RegOp = nullptr; 1233 const MachineOperand *ImmOp = nullptr; 1234 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0); 1235 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); 1236 if (Src0->isImm()) { 1237 ImmOp = Src0; 1238 RegOp = Src1; 1239 } else if (Src1->isImm()) { 1240 ImmOp = Src1; 1241 RegOp = Src0; 1242 } else 1243 return std::make_pair(nullptr, SIOutMods::NONE); 1244 1245 int OMod = getOModValue(Op, ImmOp->getImm()); 1246 if (OMod == SIOutMods::NONE || 1247 TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) || 1248 TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) || 1249 TII->hasModifiersSet(MI, AMDGPU::OpName::omod) || 1250 TII->hasModifiersSet(MI, AMDGPU::OpName::clamp)) 1251 return std::make_pair(nullptr, SIOutMods::NONE); 1252 1253 return std::make_pair(RegOp, OMod); 1254 } 1255 case AMDGPU::V_ADD_F32_e64: 1256 case AMDGPU::V_ADD_F16_e64: { 1257 // If output denormals are enabled, omod is ignored. 1258 if ((Op == AMDGPU::V_ADD_F32_e64 && ST->hasFP32Denormals()) || 1259 (Op == AMDGPU::V_ADD_F16_e64 && ST->hasFP16Denormals())) 1260 return std::make_pair(nullptr, SIOutMods::NONE); 1261 1262 // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x 1263 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0); 1264 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); 1265 1266 if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() && 1267 Src0->getSubReg() == Src1->getSubReg() && 1268 !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) && 1269 !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) && 1270 !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) && 1271 !TII->hasModifiersSet(MI, AMDGPU::OpName::omod)) 1272 return std::make_pair(Src0, SIOutMods::MUL2); 1273 1274 return std::make_pair(nullptr, SIOutMods::NONE); 1275 } 1276 default: 1277 return std::make_pair(nullptr, SIOutMods::NONE); 1278 } 1279 } 1280 1281 // FIXME: Does this need to check IEEE bit on function? 1282 bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) { 1283 const MachineOperand *RegOp; 1284 int OMod; 1285 std::tie(RegOp, OMod) = isOMod(MI); 1286 if (OMod == SIOutMods::NONE || !RegOp->isReg() || 1287 RegOp->getSubReg() != AMDGPU::NoSubRegister || 1288 !hasOneNonDBGUseInst(*MRI, RegOp->getReg())) 1289 return false; 1290 1291 MachineInstr *Def = MRI->getVRegDef(RegOp->getReg()); 1292 MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod); 1293 if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE) 1294 return false; 1295 1296 // Clamp is applied after omod. If the source already has clamp set, don't 1297 // fold it. 1298 if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp)) 1299 return false; 1300 1301 LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def << '\n'); 1302 1303 DefOMod->setImm(OMod); 1304 MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg()); 1305 MI.eraseFromParent(); 1306 return true; 1307 } 1308 1309 bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) { 1310 if (skipFunction(MF.getFunction())) 1311 return false; 1312 1313 MRI = &MF.getRegInfo(); 1314 ST = &MF.getSubtarget<GCNSubtarget>(); 1315 TII = ST->getInstrInfo(); 1316 TRI = &TII->getRegisterInfo(); 1317 MFI = MF.getInfo<SIMachineFunctionInfo>(); 1318 1319 // omod is ignored by hardware if IEEE bit is enabled. omod also does not 1320 // correctly handle signed zeros. 1321 // 1322 // FIXME: Also need to check strictfp 1323 bool IsIEEEMode = MFI->getMode().IEEE; 1324 bool HasNSZ = MFI->hasNoSignedZerosFPMath(); 1325 1326 for (MachineBasicBlock *MBB : depth_first(&MF)) { 1327 MachineBasicBlock::iterator I, Next; 1328 for (I = MBB->begin(); I != MBB->end(); I = Next) { 1329 Next = std::next(I); 1330 MachineInstr &MI = *I; 1331 1332 tryFoldInst(TII, &MI); 1333 1334 if (!TII->isFoldableCopy(MI)) { 1335 // TODO: Omod might be OK if there is NSZ only on the source 1336 // instruction, and not the omod multiply. 1337 if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) || 1338 !tryFoldOMod(MI)) 1339 tryFoldClamp(MI); 1340 continue; 1341 } 1342 1343 MachineOperand &OpToFold = MI.getOperand(1); 1344 bool FoldingImm = 1345 OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal(); 1346 1347 // FIXME: We could also be folding things like TargetIndexes. 1348 if (!FoldingImm && !OpToFold.isReg()) 1349 continue; 1350 1351 if (OpToFold.isReg() && !Register::isVirtualRegister(OpToFold.getReg())) 1352 continue; 1353 1354 // Prevent folding operands backwards in the function. For example, 1355 // the COPY opcode must not be replaced by 1 in this example: 1356 // 1357 // %3 = COPY %vgpr0; VGPR_32:%3 1358 // ... 1359 // %vgpr0 = V_MOV_B32_e32 1, implicit %exec 1360 MachineOperand &Dst = MI.getOperand(0); 1361 if (Dst.isReg() && !Register::isVirtualRegister(Dst.getReg())) 1362 continue; 1363 1364 foldInstOperand(MI, OpToFold); 1365 } 1366 } 1367 return false; 1368 } 1369