1 //===-- SIModeRegister.cpp - Mode Register --------------------------------===// 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 /// \file 9 /// This pass inserts changes to the Mode register settings as required. 10 /// Note that currently it only deals with the Double Precision Floating Point 11 /// rounding mode setting, but is intended to be generic enough to be easily 12 /// expanded. 13 /// 14 //===----------------------------------------------------------------------===// 15 // 16 #include "AMDGPU.h" 17 #include "GCNSubtarget.h" 18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 19 #include "llvm/ADT/Statistic.h" 20 #include <queue> 21 22 #define DEBUG_TYPE "si-mode-register" 23 24 STATISTIC(NumSetregInserted, "Number of setreg of mode register inserted."); 25 26 using namespace llvm; 27 28 struct Status { 29 // Mask is a bitmask where a '1' indicates the corresponding Mode bit has a 30 // known value 31 unsigned Mask; 32 unsigned Mode; 33 34 Status() : Mask(0), Mode(0){}; 35 36 Status(unsigned NewMask, unsigned NewMode) : Mask(NewMask), Mode(NewMode) { 37 Mode &= Mask; 38 }; 39 40 // merge two status values such that only values that don't conflict are 41 // preserved 42 Status merge(const Status &S) const { 43 return Status((Mask | S.Mask), ((Mode & ~S.Mask) | (S.Mode & S.Mask))); 44 } 45 46 // merge an unknown value by using the unknown value's mask to remove bits 47 // from the result 48 Status mergeUnknown(unsigned newMask) { 49 return Status(Mask & ~newMask, Mode & ~newMask); 50 } 51 52 // intersect two Status values to produce a mode and mask that is a subset 53 // of both values 54 Status intersect(const Status &S) const { 55 unsigned NewMask = (Mask & S.Mask) & (Mode ^ ~S.Mode); 56 unsigned NewMode = (Mode & NewMask); 57 return Status(NewMask, NewMode); 58 } 59 60 // produce the delta required to change the Mode to the required Mode 61 Status delta(const Status &S) const { 62 return Status((S.Mask & (Mode ^ S.Mode)) | (~Mask & S.Mask), S.Mode); 63 } 64 65 bool operator==(const Status &S) const { 66 return (Mask == S.Mask) && (Mode == S.Mode); 67 } 68 69 bool operator!=(const Status &S) const { return !(*this == S); } 70 71 bool isCompatible(Status &S) { 72 return ((Mask & S.Mask) == S.Mask) && ((Mode & S.Mask) == S.Mode); 73 } 74 75 bool isCombinable(Status &S) { return !(Mask & S.Mask) || isCompatible(S); } 76 }; 77 78 class BlockData { 79 public: 80 // The Status that represents the mode register settings required by the 81 // FirstInsertionPoint (if any) in this block. Calculated in Phase 1. 82 Status Require; 83 84 // The Status that represents the net changes to the Mode register made by 85 // this block, Calculated in Phase 1. 86 Status Change; 87 88 // The Status that represents the mode register settings on exit from this 89 // block. Calculated in Phase 2. 90 Status Exit; 91 92 // The Status that represents the intersection of exit Mode register settings 93 // from all predecessor blocks. Calculated in Phase 2, and used by Phase 3. 94 Status Pred; 95 96 // In Phase 1 we record the first instruction that has a mode requirement, 97 // which is used in Phase 3 if we need to insert a mode change. 98 MachineInstr *FirstInsertionPoint; 99 100 // A flag to indicate whether an Exit value has been set (we can't tell by 101 // examining the Exit value itself as all values may be valid results). 102 bool ExitSet; 103 104 BlockData() : FirstInsertionPoint(nullptr), ExitSet(false){}; 105 }; 106 107 namespace { 108 109 class SIModeRegister : public MachineFunctionPass { 110 public: 111 static char ID; 112 113 std::vector<std::unique_ptr<BlockData>> BlockInfo; 114 std::queue<MachineBasicBlock *> Phase2List; 115 116 // The default mode register setting currently only caters for the floating 117 // point double precision rounding mode. 118 // We currently assume the default rounding mode is Round to Nearest 119 // NOTE: this should come from a per function rounding mode setting once such 120 // a setting exists. 121 unsigned DefaultMode = FP_ROUND_ROUND_TO_NEAREST; 122 Status DefaultStatus = 123 Status(FP_ROUND_MODE_DP(0x3), FP_ROUND_MODE_DP(DefaultMode)); 124 125 bool Changed = false; 126 127 public: 128 SIModeRegister() : MachineFunctionPass(ID) {} 129 130 bool runOnMachineFunction(MachineFunction &MF) override; 131 132 void getAnalysisUsage(AnalysisUsage &AU) const override { 133 AU.setPreservesCFG(); 134 MachineFunctionPass::getAnalysisUsage(AU); 135 } 136 137 void processBlockPhase1(MachineBasicBlock &MBB, const SIInstrInfo *TII); 138 139 void processBlockPhase2(MachineBasicBlock &MBB, const SIInstrInfo *TII); 140 141 void processBlockPhase3(MachineBasicBlock &MBB, const SIInstrInfo *TII); 142 143 Status getInstructionMode(MachineInstr &MI, const SIInstrInfo *TII); 144 145 void insertSetreg(MachineBasicBlock &MBB, MachineInstr *I, 146 const SIInstrInfo *TII, Status InstrMode); 147 }; 148 } // End anonymous namespace. 149 150 INITIALIZE_PASS(SIModeRegister, DEBUG_TYPE, 151 "Insert required mode register values", false, false) 152 153 char SIModeRegister::ID = 0; 154 155 char &llvm::SIModeRegisterID = SIModeRegister::ID; 156 157 FunctionPass *llvm::createSIModeRegisterPass() { return new SIModeRegister(); } 158 159 // Determine the Mode register setting required for this instruction. 160 // Instructions which don't use the Mode register return a null Status. 161 // Note this currently only deals with instructions that use the floating point 162 // double precision setting. 163 Status SIModeRegister::getInstructionMode(MachineInstr &MI, 164 const SIInstrInfo *TII) { 165 if (TII->usesFPDPRounding(MI) || 166 MI.getOpcode() == AMDGPU::FPTRUNC_UPWARD_PSEUDO || 167 MI.getOpcode() == AMDGPU::FPTRUNC_DOWNWARD_PSEUDO) { 168 switch (MI.getOpcode()) { 169 case AMDGPU::V_INTERP_P1LL_F16: 170 case AMDGPU::V_INTERP_P1LV_F16: 171 case AMDGPU::V_INTERP_P2_F16: 172 // f16 interpolation instructions need double precision round to zero 173 return Status(FP_ROUND_MODE_DP(3), 174 FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_ZERO)); 175 case AMDGPU::FPTRUNC_UPWARD_PSEUDO: { 176 // Replacing the pseudo by a real instruction 177 MI.setDesc(TII->get(AMDGPU::V_CVT_F16_F32_e32)); 178 return Status(FP_ROUND_MODE_DP(3), 179 FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_INF)); 180 } 181 case AMDGPU::FPTRUNC_DOWNWARD_PSEUDO: { 182 // Replacing the pseudo by a real instruction 183 MI.setDesc(TII->get(AMDGPU::V_CVT_F16_F32_e32)); 184 return Status(FP_ROUND_MODE_DP(3), 185 FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEGINF)); 186 } 187 default: 188 return DefaultStatus; 189 } 190 } 191 return Status(); 192 } 193 194 // Insert a setreg instruction to update the Mode register. 195 // It is possible (though unlikely) for an instruction to require a change to 196 // the value of disjoint parts of the Mode register when we don't know the 197 // value of the intervening bits. In that case we need to use more than one 198 // setreg instruction. 199 void SIModeRegister::insertSetreg(MachineBasicBlock &MBB, MachineInstr *MI, 200 const SIInstrInfo *TII, Status InstrMode) { 201 while (InstrMode.Mask) { 202 unsigned Offset = countTrailingZeros<unsigned>(InstrMode.Mask); 203 unsigned Width = countTrailingOnes<unsigned>(InstrMode.Mask >> Offset); 204 unsigned Value = (InstrMode.Mode >> Offset) & ((1 << Width) - 1); 205 BuildMI(MBB, MI, nullptr, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 206 .addImm(Value) 207 .addImm(((Width - 1) << AMDGPU::Hwreg::WIDTH_M1_SHIFT_) | 208 (Offset << AMDGPU::Hwreg::OFFSET_SHIFT_) | 209 (AMDGPU::Hwreg::ID_MODE << AMDGPU::Hwreg::ID_SHIFT_)); 210 ++NumSetregInserted; 211 Changed = true; 212 InstrMode.Mask &= ~(((1 << Width) - 1) << Offset); 213 } 214 } 215 216 // In Phase 1 we iterate through the instructions of the block and for each 217 // instruction we get its mode usage. If the instruction uses the Mode register 218 // we: 219 // - update the Change status, which tracks the changes to the Mode register 220 // made by this block 221 // - if this instruction's requirements are compatible with the current setting 222 // of the Mode register we merge the modes 223 // - if it isn't compatible and an InsertionPoint isn't set, then we set the 224 // InsertionPoint to the current instruction, and we remember the current 225 // mode 226 // - if it isn't compatible and InsertionPoint is set we insert a seteg before 227 // that instruction (unless this instruction forms part of the block's 228 // entry requirements in which case the insertion is deferred until Phase 3 229 // when predecessor exit values are known), and move the insertion point to 230 // this instruction 231 // - if this is a setreg instruction we treat it as an incompatible instruction. 232 // This is sub-optimal but avoids some nasty corner cases, and is expected to 233 // occur very rarely. 234 // - on exit we have set the Require, Change, and initial Exit modes. 235 void SIModeRegister::processBlockPhase1(MachineBasicBlock &MBB, 236 const SIInstrInfo *TII) { 237 auto NewInfo = std::make_unique<BlockData>(); 238 MachineInstr *InsertionPoint = nullptr; 239 // RequirePending is used to indicate whether we are collecting the initial 240 // requirements for the block, and need to defer the first InsertionPoint to 241 // Phase 3. It is set to false once we have set FirstInsertionPoint, or when 242 // we discover an explicit setreg that means this block doesn't have any 243 // initial requirements. 244 bool RequirePending = true; 245 Status IPChange; 246 for (MachineInstr &MI : MBB) { 247 Status InstrMode = getInstructionMode(MI, TII); 248 if (MI.getOpcode() == AMDGPU::S_SETREG_B32 || 249 MI.getOpcode() == AMDGPU::S_SETREG_B32_mode || 250 MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 || 251 MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32_mode) { 252 // We preserve any explicit mode register setreg instruction we encounter, 253 // as we assume it has been inserted by a higher authority (this is 254 // likely to be a very rare occurrence). 255 unsigned Dst = TII->getNamedOperand(MI, AMDGPU::OpName::simm16)->getImm(); 256 if (((Dst & AMDGPU::Hwreg::ID_MASK_) >> AMDGPU::Hwreg::ID_SHIFT_) != 257 AMDGPU::Hwreg::ID_MODE) 258 continue; 259 260 unsigned Width = ((Dst & AMDGPU::Hwreg::WIDTH_M1_MASK_) >> 261 AMDGPU::Hwreg::WIDTH_M1_SHIFT_) + 262 1; 263 unsigned Offset = 264 (Dst & AMDGPU::Hwreg::OFFSET_MASK_) >> AMDGPU::Hwreg::OFFSET_SHIFT_; 265 unsigned Mask = ((1 << Width) - 1) << Offset; 266 267 // If an InsertionPoint is set we will insert a setreg there. 268 if (InsertionPoint) { 269 insertSetreg(MBB, InsertionPoint, TII, IPChange.delta(NewInfo->Change)); 270 InsertionPoint = nullptr; 271 } 272 // If this is an immediate then we know the value being set, but if it is 273 // not an immediate then we treat the modified bits of the mode register 274 // as unknown. 275 if (MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 || 276 MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32_mode) { 277 unsigned Val = TII->getNamedOperand(MI, AMDGPU::OpName::imm)->getImm(); 278 unsigned Mode = (Val << Offset) & Mask; 279 Status Setreg = Status(Mask, Mode); 280 // If we haven't already set the initial requirements for the block we 281 // don't need to as the requirements start from this explicit setreg. 282 RequirePending = false; 283 NewInfo->Change = NewInfo->Change.merge(Setreg); 284 } else { 285 NewInfo->Change = NewInfo->Change.mergeUnknown(Mask); 286 } 287 } else if (!NewInfo->Change.isCompatible(InstrMode)) { 288 // This instruction uses the Mode register and its requirements aren't 289 // compatible with the current mode. 290 if (InsertionPoint) { 291 // If the required mode change cannot be included in the current 292 // InsertionPoint changes, we need a setreg and start a new 293 // InsertionPoint. 294 if (!IPChange.delta(NewInfo->Change).isCombinable(InstrMode)) { 295 if (RequirePending) { 296 // This is the first insertionPoint in the block so we will defer 297 // the insertion of the setreg to Phase 3 where we know whether or 298 // not it is actually needed. 299 NewInfo->FirstInsertionPoint = InsertionPoint; 300 NewInfo->Require = NewInfo->Change; 301 RequirePending = false; 302 } else { 303 insertSetreg(MBB, InsertionPoint, TII, 304 IPChange.delta(NewInfo->Change)); 305 IPChange = NewInfo->Change; 306 } 307 // Set the new InsertionPoint 308 InsertionPoint = &MI; 309 } 310 NewInfo->Change = NewInfo->Change.merge(InstrMode); 311 } else { 312 // No InsertionPoint is currently set - this is either the first in 313 // the block or we have previously seen an explicit setreg. 314 InsertionPoint = &MI; 315 IPChange = NewInfo->Change; 316 NewInfo->Change = NewInfo->Change.merge(InstrMode); 317 } 318 } 319 } 320 if (RequirePending) { 321 // If we haven't yet set the initial requirements for the block we set them 322 // now. 323 NewInfo->FirstInsertionPoint = InsertionPoint; 324 NewInfo->Require = NewInfo->Change; 325 } else if (InsertionPoint) { 326 // We need to insert a setreg at the InsertionPoint 327 insertSetreg(MBB, InsertionPoint, TII, IPChange.delta(NewInfo->Change)); 328 } 329 NewInfo->Exit = NewInfo->Change; 330 BlockInfo[MBB.getNumber()] = std::move(NewInfo); 331 } 332 333 // In Phase 2 we revisit each block and calculate the common Mode register 334 // value provided by all predecessor blocks. If the Exit value for the block 335 // is changed, then we add the successor blocks to the worklist so that the 336 // exit value is propagated. 337 void SIModeRegister::processBlockPhase2(MachineBasicBlock &MBB, 338 const SIInstrInfo *TII) { 339 bool RevisitRequired = false; 340 bool ExitSet = false; 341 unsigned ThisBlock = MBB.getNumber(); 342 if (MBB.pred_empty()) { 343 // There are no predecessors, so use the default starting status. 344 BlockInfo[ThisBlock]->Pred = DefaultStatus; 345 ExitSet = true; 346 } else { 347 // Build a status that is common to all the predecessors by intersecting 348 // all the predecessor exit status values. 349 // Mask bits (which represent the Mode bits with a known value) can only be 350 // added by explicit SETREG instructions or the initial default value - 351 // the intersection process may remove Mask bits. 352 // If we find a predecessor that has not yet had an exit value determined 353 // (this can happen for example if a block is its own predecessor) we defer 354 // use of that value as the Mask will be all zero, and we will revisit this 355 // block again later (unless the only predecessor without an exit value is 356 // this block). 357 MachineBasicBlock::pred_iterator P = MBB.pred_begin(), E = MBB.pred_end(); 358 MachineBasicBlock &PB = *(*P); 359 unsigned PredBlock = PB.getNumber(); 360 if ((ThisBlock == PredBlock) && (std::next(P) == E)) { 361 BlockInfo[ThisBlock]->Pred = DefaultStatus; 362 ExitSet = true; 363 } else if (BlockInfo[PredBlock]->ExitSet) { 364 BlockInfo[ThisBlock]->Pred = BlockInfo[PredBlock]->Exit; 365 ExitSet = true; 366 } else if (PredBlock != ThisBlock) 367 RevisitRequired = true; 368 369 for (P = std::next(P); P != E; P = std::next(P)) { 370 MachineBasicBlock *Pred = *P; 371 unsigned PredBlock = Pred->getNumber(); 372 if (BlockInfo[PredBlock]->ExitSet) { 373 if (BlockInfo[ThisBlock]->ExitSet) { 374 BlockInfo[ThisBlock]->Pred = 375 BlockInfo[ThisBlock]->Pred.intersect(BlockInfo[PredBlock]->Exit); 376 } else { 377 BlockInfo[ThisBlock]->Pred = BlockInfo[PredBlock]->Exit; 378 } 379 ExitSet = true; 380 } else if (PredBlock != ThisBlock) 381 RevisitRequired = true; 382 } 383 } 384 Status TmpStatus = 385 BlockInfo[ThisBlock]->Pred.merge(BlockInfo[ThisBlock]->Change); 386 if (BlockInfo[ThisBlock]->Exit != TmpStatus) { 387 BlockInfo[ThisBlock]->Exit = TmpStatus; 388 // Add the successors to the work list so we can propagate the changed exit 389 // status. 390 for (MachineBasicBlock *Succ : MBB.successors()) 391 Phase2List.push(Succ); 392 } 393 BlockInfo[ThisBlock]->ExitSet = ExitSet; 394 if (RevisitRequired) 395 Phase2List.push(&MBB); 396 } 397 398 // In Phase 3 we revisit each block and if it has an insertion point defined we 399 // check whether the predecessor mode meets the block's entry requirements. If 400 // not we insert an appropriate setreg instruction to modify the Mode register. 401 void SIModeRegister::processBlockPhase3(MachineBasicBlock &MBB, 402 const SIInstrInfo *TII) { 403 unsigned ThisBlock = MBB.getNumber(); 404 if (!BlockInfo[ThisBlock]->Pred.isCompatible(BlockInfo[ThisBlock]->Require)) { 405 Status Delta = 406 BlockInfo[ThisBlock]->Pred.delta(BlockInfo[ThisBlock]->Require); 407 if (BlockInfo[ThisBlock]->FirstInsertionPoint) 408 insertSetreg(MBB, BlockInfo[ThisBlock]->FirstInsertionPoint, TII, Delta); 409 else 410 insertSetreg(MBB, &MBB.instr_front(), TII, Delta); 411 } 412 } 413 414 bool SIModeRegister::runOnMachineFunction(MachineFunction &MF) { 415 BlockInfo.resize(MF.getNumBlockIDs()); 416 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 417 const SIInstrInfo *TII = ST.getInstrInfo(); 418 419 // Processing is performed in a number of phases 420 421 // Phase 1 - determine the initial mode required by each block, and add setreg 422 // instructions for intra block requirements. 423 for (MachineBasicBlock &BB : MF) 424 processBlockPhase1(BB, TII); 425 426 // Phase 2 - determine the exit mode from each block. We add all blocks to the 427 // list here, but will also add any that need to be revisited during Phase 2 428 // processing. 429 for (MachineBasicBlock &BB : MF) 430 Phase2List.push(&BB); 431 while (!Phase2List.empty()) { 432 processBlockPhase2(*Phase2List.front(), TII); 433 Phase2List.pop(); 434 } 435 436 // Phase 3 - add an initial setreg to each block where the required entry mode 437 // is not satisfied by the exit mode of all its predecessors. 438 for (MachineBasicBlock &BB : MF) 439 processBlockPhase3(BB, TII); 440 441 BlockInfo.clear(); 442 443 return Changed; 444 } 445