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