1 //===-- SIFormMemoryClauses.cpp -------------------------------------------===// 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 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// This pass creates bundles of SMEM and VMEM instructions forming memory 11 /// clauses if XNACK is enabled. Def operands of clauses are marked as early 12 /// clobber to make sure we will not override any source within a clause. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #include "AMDGPU.h" 17 #include "GCNRegPressure.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "llvm/InitializePasses.h" 20 21 using namespace llvm; 22 23 #define DEBUG_TYPE "si-form-memory-clauses" 24 25 // Clauses longer then 15 instructions would overflow one of the counters 26 // and stall. They can stall even earlier if there are outstanding counters. 27 static cl::opt<unsigned> 28 MaxClause("amdgpu-max-memory-clause", cl::Hidden, cl::init(15), 29 cl::desc("Maximum length of a memory clause, instructions")); 30 31 namespace { 32 33 class SIFormMemoryClauses : public MachineFunctionPass { 34 typedef DenseMap<unsigned, std::pair<unsigned, LaneBitmask>> RegUse; 35 36 public: 37 static char ID; 38 39 public: 40 SIFormMemoryClauses() : MachineFunctionPass(ID) { 41 initializeSIFormMemoryClausesPass(*PassRegistry::getPassRegistry()); 42 } 43 44 bool runOnMachineFunction(MachineFunction &MF) override; 45 46 StringRef getPassName() const override { 47 return "SI Form memory clauses"; 48 } 49 50 void getAnalysisUsage(AnalysisUsage &AU) const override { 51 AU.addRequired<LiveIntervals>(); 52 AU.setPreservesAll(); 53 MachineFunctionPass::getAnalysisUsage(AU); 54 } 55 56 MachineFunctionProperties getClearedProperties() const override { 57 return MachineFunctionProperties().set( 58 MachineFunctionProperties::Property::IsSSA); 59 } 60 61 private: 62 template <typename Callable> 63 void forAllLanes(Register Reg, LaneBitmask LaneMask, Callable Func) const; 64 65 bool canBundle(const MachineInstr &MI, const RegUse &Defs, 66 const RegUse &Uses) const; 67 bool checkPressure(const MachineInstr &MI, GCNDownwardRPTracker &RPT); 68 void collectRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses) const; 69 bool processRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses, 70 GCNDownwardRPTracker &RPT); 71 72 const GCNSubtarget *ST; 73 const SIRegisterInfo *TRI; 74 const MachineRegisterInfo *MRI; 75 SIMachineFunctionInfo *MFI; 76 77 unsigned LastRecordedOccupancy; 78 unsigned MaxVGPRs; 79 unsigned MaxSGPRs; 80 }; 81 82 } // End anonymous namespace. 83 84 INITIALIZE_PASS_BEGIN(SIFormMemoryClauses, DEBUG_TYPE, 85 "SI Form memory clauses", false, false) 86 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 87 INITIALIZE_PASS_END(SIFormMemoryClauses, DEBUG_TYPE, 88 "SI Form memory clauses", false, false) 89 90 91 char SIFormMemoryClauses::ID = 0; 92 93 char &llvm::SIFormMemoryClausesID = SIFormMemoryClauses::ID; 94 95 FunctionPass *llvm::createSIFormMemoryClausesPass() { 96 return new SIFormMemoryClauses(); 97 } 98 99 static bool isVMEMClauseInst(const MachineInstr &MI) { 100 return SIInstrInfo::isFLAT(MI) || SIInstrInfo::isVMEM(MI); 101 } 102 103 static bool isSMEMClauseInst(const MachineInstr &MI) { 104 return SIInstrInfo::isSMRD(MI); 105 } 106 107 // There no sense to create store clauses, they do not define anything, 108 // thus there is nothing to set early-clobber. 109 static bool isValidClauseInst(const MachineInstr &MI, bool IsVMEMClause) { 110 assert(!MI.isDebugInstr() && "debug instructions should not reach here"); 111 if (MI.isBundled()) 112 return false; 113 if (!MI.mayLoad() || MI.mayStore()) 114 return false; 115 if (SIInstrInfo::isAtomic(MI)) 116 return false; 117 if (IsVMEMClause && !isVMEMClauseInst(MI)) 118 return false; 119 if (!IsVMEMClause && !isSMEMClauseInst(MI)) 120 return false; 121 // If this is a load instruction where the result has been coalesced with an operand, then we cannot clause it. 122 for (const MachineOperand &ResMO : MI.defs()) { 123 Register ResReg = ResMO.getReg(); 124 for (const MachineOperand &MO : MI.uses()) { 125 if (!MO.isReg() || MO.isDef()) 126 continue; 127 if (MO.getReg() == ResReg) 128 return false; 129 } 130 break; // Only check the first def. 131 } 132 return true; 133 } 134 135 static unsigned getMopState(const MachineOperand &MO) { 136 unsigned S = 0; 137 if (MO.isImplicit()) 138 S |= RegState::Implicit; 139 if (MO.isDead()) 140 S |= RegState::Dead; 141 if (MO.isUndef()) 142 S |= RegState::Undef; 143 if (MO.isKill()) 144 S |= RegState::Kill; 145 if (MO.isEarlyClobber()) 146 S |= RegState::EarlyClobber; 147 if (MO.getReg().isPhysical() && MO.isRenamable()) 148 S |= RegState::Renamable; 149 return S; 150 } 151 152 template <typename Callable> 153 void SIFormMemoryClauses::forAllLanes(Register Reg, LaneBitmask LaneMask, 154 Callable Func) const { 155 if (LaneMask.all() || Reg.isPhysical() || 156 LaneMask == MRI->getMaxLaneMaskForVReg(Reg)) { 157 Func(0); 158 return; 159 } 160 161 const TargetRegisterClass *RC = MRI->getRegClass(Reg); 162 unsigned E = TRI->getNumSubRegIndices(); 163 SmallVector<unsigned, AMDGPU::NUM_TARGET_SUBREGS> CoveringSubregs; 164 for (unsigned Idx = 1; Idx < E; ++Idx) { 165 // Is this index even compatible with the given class? 166 if (TRI->getSubClassWithSubReg(RC, Idx) != RC) 167 continue; 168 LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(Idx); 169 // Early exit if we found a perfect match. 170 if (SubRegMask == LaneMask) { 171 Func(Idx); 172 return; 173 } 174 175 if ((SubRegMask & ~LaneMask).any() || (SubRegMask & LaneMask).none()) 176 continue; 177 178 CoveringSubregs.push_back(Idx); 179 } 180 181 llvm::sort(CoveringSubregs, [this](unsigned A, unsigned B) { 182 LaneBitmask MaskA = TRI->getSubRegIndexLaneMask(A); 183 LaneBitmask MaskB = TRI->getSubRegIndexLaneMask(B); 184 unsigned NA = MaskA.getNumLanes(); 185 unsigned NB = MaskB.getNumLanes(); 186 if (NA != NB) 187 return NA > NB; 188 return MaskA.getHighestLane() > MaskB.getHighestLane(); 189 }); 190 191 for (unsigned Idx : CoveringSubregs) { 192 LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(Idx); 193 if ((SubRegMask & ~LaneMask).any() || (SubRegMask & LaneMask).none()) 194 continue; 195 196 Func(Idx); 197 LaneMask &= ~SubRegMask; 198 if (LaneMask.none()) 199 return; 200 } 201 202 llvm_unreachable("Failed to find all subregs to cover lane mask"); 203 } 204 205 // Returns false if there is a use of a def already in the map. 206 // In this case we must break the clause. 207 bool SIFormMemoryClauses::canBundle(const MachineInstr &MI, const RegUse &Defs, 208 const RegUse &Uses) const { 209 // Check interference with defs. 210 for (const MachineOperand &MO : MI.operands()) { 211 // TODO: Prologue/Epilogue Insertion pass does not process bundled 212 // instructions. 213 if (MO.isFI()) 214 return false; 215 216 if (!MO.isReg()) 217 continue; 218 219 Register Reg = MO.getReg(); 220 221 // If it is tied we will need to write same register as we read. 222 if (MO.isTied()) 223 return false; 224 225 const RegUse &Map = MO.isDef() ? Uses : Defs; 226 auto Conflict = Map.find(Reg); 227 if (Conflict == Map.end()) 228 continue; 229 230 if (Reg.isPhysical()) 231 return false; 232 233 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(MO.getSubReg()); 234 if ((Conflict->second.second & Mask).any()) 235 return false; 236 } 237 238 return true; 239 } 240 241 // Since all defs in the clause are early clobber we can run out of registers. 242 // Function returns false if pressure would hit the limit if instruction is 243 // bundled into a memory clause. 244 bool SIFormMemoryClauses::checkPressure(const MachineInstr &MI, 245 GCNDownwardRPTracker &RPT) { 246 // NB: skip advanceBeforeNext() call. Since all defs will be marked 247 // early-clobber they will all stay alive at least to the end of the 248 // clause. Therefor we should not decrease pressure even if load 249 // pointer becomes dead and could otherwise be reused for destination. 250 RPT.advanceToNext(); 251 GCNRegPressure MaxPressure = RPT.moveMaxPressure(); 252 unsigned Occupancy = MaxPressure.getOccupancy(*ST); 253 254 // Don't push over half the register budget. We don't want to introduce 255 // spilling just to form a soft clause. 256 // 257 // FIXME: This pressure check is fundamentally broken. First, this is checking 258 // the global pressure, not the pressure at this specific point in the 259 // program. Second, it's not accounting for the increased liveness of the use 260 // operands due to the early clobber we will introduce. Third, the pressure 261 // tracking does not account for the alignment requirements for SGPRs, or the 262 // fragmentation of registers the allocator will need to satisfy. 263 if (Occupancy >= MFI->getMinAllowedOccupancy() && 264 MaxPressure.getVGPRNum() <= MaxVGPRs / 2 && 265 MaxPressure.getSGPRNum() <= MaxSGPRs / 2) { 266 LastRecordedOccupancy = Occupancy; 267 return true; 268 } 269 return false; 270 } 271 272 // Collect register defs and uses along with their lane masks and states. 273 void SIFormMemoryClauses::collectRegUses(const MachineInstr &MI, 274 RegUse &Defs, RegUse &Uses) const { 275 for (const MachineOperand &MO : MI.operands()) { 276 if (!MO.isReg()) 277 continue; 278 Register Reg = MO.getReg(); 279 if (!Reg) 280 continue; 281 282 LaneBitmask Mask = Reg.isVirtual() 283 ? TRI->getSubRegIndexLaneMask(MO.getSubReg()) 284 : LaneBitmask::getAll(); 285 RegUse &Map = MO.isDef() ? Defs : Uses; 286 287 auto Loc = Map.find(Reg); 288 unsigned State = getMopState(MO); 289 if (Loc == Map.end()) { 290 Map[Reg] = std::make_pair(State, Mask); 291 } else { 292 Loc->second.first |= State; 293 Loc->second.second |= Mask; 294 } 295 } 296 } 297 298 // Check register def/use conflicts, occupancy limits and collect def/use maps. 299 // Return true if instruction can be bundled with previous. It it cannot 300 // def/use maps are not updated. 301 bool SIFormMemoryClauses::processRegUses(const MachineInstr &MI, 302 RegUse &Defs, RegUse &Uses, 303 GCNDownwardRPTracker &RPT) { 304 if (!canBundle(MI, Defs, Uses)) 305 return false; 306 307 if (!checkPressure(MI, RPT)) 308 return false; 309 310 collectRegUses(MI, Defs, Uses); 311 return true; 312 } 313 314 bool SIFormMemoryClauses::runOnMachineFunction(MachineFunction &MF) { 315 if (skipFunction(MF.getFunction())) 316 return false; 317 318 ST = &MF.getSubtarget<GCNSubtarget>(); 319 if (!ST->isXNACKEnabled()) 320 return false; 321 322 const SIInstrInfo *TII = ST->getInstrInfo(); 323 TRI = ST->getRegisterInfo(); 324 MRI = &MF.getRegInfo(); 325 MFI = MF.getInfo<SIMachineFunctionInfo>(); 326 LiveIntervals *LIS = &getAnalysis<LiveIntervals>(); 327 SlotIndexes *Ind = LIS->getSlotIndexes(); 328 bool Changed = false; 329 330 MaxVGPRs = TRI->getAllocatableSet(MF, &AMDGPU::VGPR_32RegClass).count(); 331 MaxSGPRs = TRI->getAllocatableSet(MF, &AMDGPU::SGPR_32RegClass).count(); 332 unsigned FuncMaxClause = AMDGPU::getIntegerAttribute( 333 MF.getFunction(), "amdgpu-max-memory-clause", MaxClause); 334 335 SmallVector<MachineInstr *> DbgInstrs; 336 337 for (MachineBasicBlock &MBB : MF) { 338 GCNDownwardRPTracker RPT(*LIS); 339 MachineBasicBlock::instr_iterator Next; 340 for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; I = Next) { 341 MachineInstr &MI = *I; 342 Next = std::next(I); 343 344 if (MI.isDebugInstr()) 345 continue; 346 347 bool IsVMEM = isVMEMClauseInst(MI); 348 349 if (!isValidClauseInst(MI, IsVMEM)) 350 continue; 351 352 if (!RPT.getNext().isValid()) 353 RPT.reset(MI); 354 else { // Advance the state to the current MI. 355 RPT.advance(MachineBasicBlock::const_iterator(MI)); 356 RPT.advanceBeforeNext(); 357 } 358 359 const GCNRPTracker::LiveRegSet LiveRegsCopy(RPT.getLiveRegs()); 360 RegUse Defs, Uses; 361 if (!processRegUses(MI, Defs, Uses, RPT)) { 362 RPT.reset(MI, &LiveRegsCopy); 363 continue; 364 } 365 366 unsigned Length = 1; 367 for ( ; Next != E && Length < FuncMaxClause; ++Next) { 368 // Debug instructions should not change the bundling. We need to move 369 // these after the bundle 370 if (Next->isDebugInstr()) 371 continue; 372 373 if (!isValidClauseInst(*Next, IsVMEM)) 374 break; 375 376 // A load from pointer which was loaded inside the same bundle is an 377 // impossible clause because we will need to write and read the same 378 // register inside. In this case processRegUses will return false. 379 if (!processRegUses(*Next, Defs, Uses, RPT)) 380 break; 381 382 ++Length; 383 } 384 if (Length < 2) { 385 RPT.reset(MI, &LiveRegsCopy); 386 continue; 387 } 388 389 Changed = true; 390 MFI->limitOccupancy(LastRecordedOccupancy); 391 392 auto B = BuildMI(MBB, I, DebugLoc(), TII->get(TargetOpcode::BUNDLE)); 393 Ind->insertMachineInstrInMaps(*B); 394 395 // Restore the state after processing the bundle. 396 RPT.reset(*B, &LiveRegsCopy); 397 DbgInstrs.clear(); 398 399 auto BundleNext = I; 400 for (auto BI = I; BI != Next; BI = BundleNext) { 401 BundleNext = std::next(BI); 402 403 if (BI->isDebugValue()) { 404 DbgInstrs.push_back(BI->removeFromParent()); 405 continue; 406 } 407 408 BI->bundleWithPred(); 409 Ind->removeSingleMachineInstrFromMaps(*BI); 410 411 for (MachineOperand &MO : BI->defs()) 412 if (MO.readsReg()) 413 MO.setIsInternalRead(true); 414 } 415 416 // Replace any debug instructions after the new bundle. 417 for (MachineInstr *DbgInst : DbgInstrs) 418 MBB.insert(Next, DbgInst); 419 420 for (auto &&R : Defs) { 421 forAllLanes(R.first, R.second.second, [&R, &B](unsigned SubReg) { 422 unsigned S = R.second.first | RegState::EarlyClobber; 423 if (!SubReg) 424 S &= ~(RegState::Undef | RegState::Dead); 425 B.addDef(R.first, S, SubReg); 426 }); 427 } 428 429 for (auto &&R : Uses) { 430 forAllLanes(R.first, R.second.second, [&R, &B](unsigned SubReg) { 431 B.addUse(R.first, R.second.first & ~RegState::Kill, SubReg); 432 }); 433 } 434 435 for (auto &&R : Defs) { 436 Register Reg = R.first; 437 Uses.erase(Reg); 438 if (Reg.isPhysical()) 439 continue; 440 LIS->removeInterval(Reg); 441 LIS->createAndComputeVirtRegInterval(Reg); 442 } 443 444 for (auto &&R : Uses) { 445 Register Reg = R.first; 446 if (Reg.isPhysical()) 447 continue; 448 LIS->removeInterval(Reg); 449 LIS->createAndComputeVirtRegInterval(Reg); 450 } 451 } 452 } 453 454 return Changed; 455 } 456