1 //===--------------------- SIOptimizeVGPRLiveRange.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 tries to remove unnecessary VGPR live range in divergent if-else 11 /// structure. 12 /// 13 /// When we do structurization, we usually transform a if-else into two 14 /// sucessive if-then (with a flow block to do predicate inversion). Consider a 15 /// simple case after structurization: A divergent value %a was defined before 16 /// if-else and used in both THEN (use in THEN is optional) and ELSE part: 17 /// bb.if: 18 /// %a = ... 19 /// ... 20 /// bb.then: 21 /// ... = op %a 22 /// ... // %a can be dead here 23 /// bb.flow: 24 /// ... 25 /// bb.else: 26 /// ... = %a 27 /// ... 28 /// bb.endif 29 /// 30 /// As register allocator has no idea of the thread-control-flow, it will just 31 /// assume %a would be alive in the whole range of bb.then because of a later 32 /// use in bb.else. On AMDGPU architecture, the VGPR was accessed with respect 33 /// to exec mask. For this if-else case, the lanes active in bb.then will be 34 /// inactive in bb.else, and vice-verse. So we are safe to say that %a was dead 35 /// after the last use in bb.then untill the end of the block. The reason is 36 /// the instructions in bb.then will only overwrite lanes that will never be 37 /// accessed in bb.else. 38 /// 39 /// This pass aims to to tell register allocator that %a is in-fact dead, 40 /// through inserting a phi-node in bb.flow saying that %a is undef when coming 41 /// from bb.then, and then replace the uses in the bb.else with the result of 42 /// newly inserted phi. 43 /// 44 /// Two key conditions must be met to ensure correctness: 45 /// 1.) The def-point should be in the same loop-level as if-else-endif to make 46 /// sure the second loop iteration still get correct data. 47 /// 2.) There should be no further uses after the IF-ELSE region. 48 /// 49 // 50 //===----------------------------------------------------------------------===// 51 52 #include "AMDGPU.h" 53 #include "GCNSubtarget.h" 54 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 55 #include "SIMachineFunctionInfo.h" 56 #include "llvm/CodeGen/LiveVariables.h" 57 #include "llvm/CodeGen/MachineDominators.h" 58 #include "llvm/CodeGen/MachineLoopInfo.h" 59 #include "llvm/CodeGen/TargetRegisterInfo.h" 60 #include "llvm/InitializePasses.h" 61 62 using namespace llvm; 63 64 #define DEBUG_TYPE "si-opt-vgpr-liverange" 65 66 namespace { 67 68 class SIOptimizeVGPRLiveRange : public MachineFunctionPass { 69 private: 70 const SIRegisterInfo *TRI = nullptr; 71 const SIInstrInfo *TII = nullptr; 72 LiveVariables *LV = nullptr; 73 MachineDominatorTree *MDT = nullptr; 74 const MachineLoopInfo *Loops = nullptr; 75 MachineRegisterInfo *MRI = nullptr; 76 77 public: 78 static char ID; 79 80 MachineBasicBlock *getElseTarget(MachineBasicBlock *MBB) const; 81 82 void collectElseRegionBlocks(MachineBasicBlock *Flow, 83 MachineBasicBlock *Endif, 84 SmallSetVector<MachineBasicBlock *, 16> &) const; 85 86 void 87 collectCandidateRegisters(MachineBasicBlock *If, MachineBasicBlock *Flow, 88 MachineBasicBlock *Endif, 89 SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks, 90 SmallVectorImpl<Register> &CandidateRegs) const; 91 92 void findNonPHIUsesInBlock(Register Reg, MachineBasicBlock *MBB, 93 SmallVectorImpl<MachineInstr *> &Uses) const; 94 95 void updateLiveRangeInThenRegion(Register Reg, MachineBasicBlock *If, 96 MachineBasicBlock *Flow) const; 97 98 void updateLiveRangeInElseRegion( 99 Register Reg, Register NewReg, MachineBasicBlock *Flow, 100 MachineBasicBlock *Endif, 101 SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks) const; 102 103 void 104 optimizeLiveRange(Register Reg, MachineBasicBlock *If, 105 MachineBasicBlock *Flow, MachineBasicBlock *Endif, 106 SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks) const; 107 108 SIOptimizeVGPRLiveRange() : MachineFunctionPass(ID) {} 109 110 bool runOnMachineFunction(MachineFunction &MF) override; 111 112 StringRef getPassName() const override { 113 return "SI Optimize VGPR LiveRange"; 114 } 115 116 void getAnalysisUsage(AnalysisUsage &AU) const override { 117 AU.addRequired<LiveVariables>(); 118 AU.addRequired<MachineDominatorTree>(); 119 AU.addRequired<MachineLoopInfo>(); 120 AU.addPreserved<LiveVariables>(); 121 AU.addPreserved<MachineDominatorTree>(); 122 AU.addPreserved<MachineLoopInfo>(); 123 MachineFunctionPass::getAnalysisUsage(AU); 124 } 125 126 MachineFunctionProperties getRequiredProperties() const override { 127 return MachineFunctionProperties().set( 128 MachineFunctionProperties::Property::IsSSA); 129 } 130 }; 131 132 } // end anonymous namespace 133 134 // Check whether the MBB is a else flow block and get the branching target which 135 // is the Endif block 136 MachineBasicBlock * 137 SIOptimizeVGPRLiveRange::getElseTarget(MachineBasicBlock *MBB) const { 138 for (auto &BR : MBB->terminators()) { 139 if (BR.getOpcode() == AMDGPU::SI_ELSE) 140 return BR.getOperand(2).getMBB(); 141 } 142 return nullptr; 143 } 144 145 void SIOptimizeVGPRLiveRange::collectElseRegionBlocks( 146 MachineBasicBlock *Flow, MachineBasicBlock *Endif, 147 SmallSetVector<MachineBasicBlock *, 16> &Blocks) const { 148 assert(Flow != Endif); 149 150 MachineBasicBlock *MBB = Endif; 151 unsigned Cur = 0; 152 while (MBB) { 153 for (auto *Pred : MBB->predecessors()) { 154 if (Pred != Flow && !Blocks.contains(Pred)) 155 Blocks.insert(Pred); 156 } 157 158 if (Cur < Blocks.size()) 159 MBB = Blocks[Cur++]; 160 else 161 MBB = nullptr; 162 } 163 164 LLVM_DEBUG({ 165 dbgs() << "Found Else blocks: "; 166 for (auto *MBB : Blocks) 167 dbgs() << printMBBReference(*MBB) << ' '; 168 dbgs() << '\n'; 169 }); 170 } 171 172 /// Find the instructions(excluding phi) in \p MBB that uses the \p Reg. 173 void SIOptimizeVGPRLiveRange::findNonPHIUsesInBlock( 174 Register Reg, MachineBasicBlock *MBB, 175 SmallVectorImpl<MachineInstr *> &Uses) const { 176 for (auto &UseMI : MRI->use_nodbg_instructions(Reg)) { 177 if (UseMI.getParent() == MBB && !UseMI.isPHI()) 178 Uses.push_back(&UseMI); 179 } 180 } 181 182 /// Collect the killed registers in the ELSE region which are not alive through 183 /// the whole THEN region. 184 void SIOptimizeVGPRLiveRange::collectCandidateRegisters( 185 MachineBasicBlock *If, MachineBasicBlock *Flow, MachineBasicBlock *Endif, 186 SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks, 187 SmallVectorImpl<Register> &CandidateRegs) const { 188 189 SmallSet<Register, 8> KillsInElse; 190 191 for (auto *Else : ElseBlocks) { 192 for (auto &MI : Else->instrs()) { 193 if (MI.isDebugInstr()) 194 continue; 195 196 for (auto &MO : MI.operands()) { 197 if (!MO.isReg() || !MO.getReg() || MO.isDef()) 198 continue; 199 200 Register MOReg = MO.getReg(); 201 // We can only optimize AGPR/VGPR virtual register 202 if (MOReg.isPhysical() || !TRI->isVectorRegister(*MRI, MOReg)) 203 continue; 204 205 if (MO.isKill() && MO.readsReg()) { 206 LiveVariables::VarInfo &VI = LV->getVarInfo(MOReg); 207 const MachineBasicBlock *DefMBB = MRI->getVRegDef(MOReg)->getParent(); 208 // Make sure two conditions are met: 209 // a.) the value is defined before/in the IF block 210 // b.) should be defined in the same loop-level. 211 if ((VI.AliveBlocks.test(If->getNumber()) || DefMBB == If) && 212 Loops->getLoopFor(DefMBB) == Loops->getLoopFor(If)) 213 KillsInElse.insert(MOReg); 214 } 215 } 216 } 217 } 218 219 // Check the phis in the Endif, looking for value coming from the ELSE 220 // region. Make sure the phi-use is the last use. 221 for (auto &MI : Endif->phis()) { 222 for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) { 223 auto &MO = MI.getOperand(Idx); 224 auto *Pred = MI.getOperand(Idx + 1).getMBB(); 225 if (Pred == Flow) 226 continue; 227 assert(ElseBlocks.contains(Pred) && "Should be from Else region\n"); 228 229 if (!MO.isReg() || !MO.getReg() || MO.isUndef()) 230 continue; 231 232 Register Reg = MO.getReg(); 233 if (Reg.isPhysical() || !TRI->isVectorRegister(*MRI, Reg)) 234 continue; 235 236 LiveVariables::VarInfo &VI = LV->getVarInfo(Reg); 237 238 if (VI.isLiveIn(*Endif, Reg, *MRI)) { 239 LLVM_DEBUG(dbgs() << "Excluding " << printReg(Reg, TRI) 240 << " as Live in Endif\n"); 241 continue; 242 } 243 // Make sure two conditions are met: 244 // a.) the value is defined before/in the IF block 245 // b.) should be defined in the same loop-level. 246 const MachineBasicBlock *DefMBB = MRI->getVRegDef(Reg)->getParent(); 247 if ((VI.AliveBlocks.test(If->getNumber()) || DefMBB == If) && 248 Loops->getLoopFor(DefMBB) == Loops->getLoopFor(If)) 249 KillsInElse.insert(Reg); 250 } 251 } 252 253 auto IsLiveThroughThen = [&](Register Reg) { 254 for (auto I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end(); I != E; 255 ++I) { 256 if (!I->readsReg()) 257 continue; 258 auto *UseMI = I->getParent(); 259 auto *UseMBB = UseMI->getParent(); 260 if (UseMBB == Flow || UseMBB == Endif) { 261 if (!UseMI->isPHI()) 262 return true; 263 264 auto *IncomingMBB = UseMI->getOperand(I.getOperandNo() + 1).getMBB(); 265 // The register is live through the path If->Flow or Flow->Endif. 266 // we should not optimize for such cases. 267 if ((UseMBB == Flow && IncomingMBB != If) || 268 (UseMBB == Endif && IncomingMBB == Flow)) 269 return true; 270 } 271 } 272 return false; 273 }; 274 275 for (auto Reg : KillsInElse) { 276 if (!IsLiveThroughThen(Reg)) 277 CandidateRegs.push_back(Reg); 278 } 279 } 280 281 // Re-calculate the liveness of \p Reg in the THEN-region 282 void SIOptimizeVGPRLiveRange::updateLiveRangeInThenRegion( 283 Register Reg, MachineBasicBlock *If, MachineBasicBlock *Flow) const { 284 285 SmallPtrSet<MachineBasicBlock *, 16> PHIIncoming; 286 287 MachineBasicBlock *ThenEntry = nullptr; 288 for (auto *Succ : If->successors()) { 289 if (Succ != Flow) { 290 ThenEntry = Succ; 291 break; 292 } 293 } 294 assert(ThenEntry && "No successor in Then region?"); 295 296 LiveVariables::VarInfo &OldVarInfo = LV->getVarInfo(Reg); 297 df_iterator_default_set<MachineBasicBlock *, 16> Visited; 298 299 for (MachineBasicBlock *MBB : depth_first_ext(ThenEntry, Visited)) { 300 if (MBB == Flow) 301 break; 302 303 // Clear Live bit, as we will recalculate afterwards 304 LLVM_DEBUG(dbgs() << "Clear AliveBlock " << printMBBReference(*MBB) 305 << '\n'); 306 OldVarInfo.AliveBlocks.reset(MBB->getNumber()); 307 } 308 309 // Get the blocks the Reg should be alive through 310 for (auto I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end(); I != E; 311 ++I) { 312 auto *UseMI = I->getParent(); 313 if (UseMI->isPHI() && I->readsReg()) { 314 if (Visited.contains(UseMI->getParent())) 315 PHIIncoming.insert(UseMI->getOperand(I.getOperandNo() + 1).getMBB()); 316 } 317 } 318 319 Visited.clear(); 320 321 for (MachineBasicBlock *MBB : depth_first_ext(ThenEntry, Visited)) { 322 if (MBB == Flow) 323 break; 324 325 SmallVector<MachineInstr *> Uses; 326 // PHI instructions has been processed before. 327 findNonPHIUsesInBlock(Reg, MBB, Uses); 328 329 if (Uses.size() == 1) { 330 LLVM_DEBUG(dbgs() << "Found one Non-PHI use in " 331 << printMBBReference(*MBB) << '\n'); 332 LV->HandleVirtRegUse(Reg, MBB, *(*Uses.begin())); 333 } else if (Uses.size() > 1) { 334 // Process the instructions in-order 335 LLVM_DEBUG(dbgs() << "Found " << Uses.size() << " Non-PHI uses in " 336 << printMBBReference(*MBB) << '\n'); 337 for (MachineInstr &MI : *MBB) { 338 if (llvm::is_contained(Uses, &MI)) 339 LV->HandleVirtRegUse(Reg, MBB, MI); 340 } 341 } 342 343 // Mark Reg alive through the block if this is a PHI incoming block 344 if (PHIIncoming.contains(MBB)) 345 LV->MarkVirtRegAliveInBlock(OldVarInfo, MRI->getVRegDef(Reg)->getParent(), 346 MBB); 347 } 348 349 // Set the isKilled flag if we get new Kills in the THEN region. 350 for (auto *MI : OldVarInfo.Kills) { 351 if (Visited.contains(MI->getParent())) 352 MI->addRegisterKilled(Reg, TRI); 353 } 354 } 355 356 void SIOptimizeVGPRLiveRange::updateLiveRangeInElseRegion( 357 Register Reg, Register NewReg, MachineBasicBlock *Flow, 358 MachineBasicBlock *Endif, 359 SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks) const { 360 LiveVariables::VarInfo &NewVarInfo = LV->getVarInfo(NewReg); 361 LiveVariables::VarInfo &OldVarInfo = LV->getVarInfo(Reg); 362 363 // Transfer aliveBlocks from Reg to NewReg 364 for (auto *MBB : ElseBlocks) { 365 unsigned BBNum = MBB->getNumber(); 366 if (OldVarInfo.AliveBlocks.test(BBNum)) { 367 NewVarInfo.AliveBlocks.set(BBNum); 368 LLVM_DEBUG(dbgs() << "Removing ALiveBlock " << printMBBReference(*MBB) 369 << '\n'); 370 OldVarInfo.AliveBlocks.reset(BBNum); 371 } 372 } 373 374 // Transfer the possible Kills in ElseBlocks from Reg to NewReg 375 auto I = OldVarInfo.Kills.begin(); 376 while (I != OldVarInfo.Kills.end()) { 377 if (ElseBlocks.contains((*I)->getParent())) { 378 NewVarInfo.Kills.push_back(*I); 379 I = OldVarInfo.Kills.erase(I); 380 } else { 381 ++I; 382 } 383 } 384 } 385 386 void SIOptimizeVGPRLiveRange::optimizeLiveRange( 387 Register Reg, MachineBasicBlock *If, MachineBasicBlock *Flow, 388 MachineBasicBlock *Endif, 389 SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks) const { 390 // Insert a new PHI, marking the value from the THEN region being 391 // undef. 392 LLVM_DEBUG(dbgs() << "Optimizing " << printReg(Reg, TRI) << '\n'); 393 const auto *RC = MRI->getRegClass(Reg); 394 Register NewReg = MRI->createVirtualRegister(RC); 395 Register UndefReg = MRI->createVirtualRegister(RC); 396 MachineInstrBuilder PHI = BuildMI(*Flow, Flow->getFirstNonPHI(), DebugLoc(), 397 TII->get(TargetOpcode::PHI), NewReg); 398 for (auto *Pred : Flow->predecessors()) { 399 if (Pred == If) 400 PHI.addReg(Reg).addMBB(Pred); 401 else 402 PHI.addReg(UndefReg, RegState::Undef).addMBB(Pred); 403 } 404 405 // Replace all uses in the ELSE region or the PHIs in ENDIF block 406 for (auto I = MRI->use_begin(Reg), E = MRI->use_end(); I != E;) { 407 MachineOperand &O = *I; 408 // This is a little bit tricky, the setReg() will update the linked list, 409 // so we have to increment the iterator before setReg() to avoid skipping 410 // some uses. 411 ++I; 412 auto *UseMI = O.getParent(); 413 auto *UseBlock = UseMI->getParent(); 414 // Replace uses in Endif block 415 if (UseBlock == Endif) { 416 assert(UseMI->isPHI() && "Uses should be PHI in Endif block"); 417 O.setReg(NewReg); 418 continue; 419 } 420 421 // Replace uses in Else region 422 if (ElseBlocks.contains(UseBlock)) 423 O.setReg(NewReg); 424 } 425 426 // The optimized Reg is not alive through Flow blocks anymore. 427 LiveVariables::VarInfo &OldVarInfo = LV->getVarInfo(Reg); 428 OldVarInfo.AliveBlocks.reset(Flow->getNumber()); 429 430 updateLiveRangeInElseRegion(Reg, NewReg, Flow, Endif, ElseBlocks); 431 updateLiveRangeInThenRegion(Reg, If, Flow); 432 } 433 434 char SIOptimizeVGPRLiveRange::ID = 0; 435 436 INITIALIZE_PASS_BEGIN(SIOptimizeVGPRLiveRange, DEBUG_TYPE, 437 "SI Optimize VGPR LiveRange", false, false) 438 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 439 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 440 INITIALIZE_PASS_DEPENDENCY(LiveVariables) 441 INITIALIZE_PASS_END(SIOptimizeVGPRLiveRange, DEBUG_TYPE, 442 "SI Optimize VGPR LiveRange", false, false) 443 444 char &llvm::SIOptimizeVGPRLiveRangeID = SIOptimizeVGPRLiveRange::ID; 445 446 FunctionPass *llvm::createSIOptimizeVGPRLiveRangePass() { 447 return new SIOptimizeVGPRLiveRange(); 448 } 449 450 bool SIOptimizeVGPRLiveRange::runOnMachineFunction(MachineFunction &MF) { 451 452 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 453 TII = ST.getInstrInfo(); 454 TRI = &TII->getRegisterInfo(); 455 MDT = &getAnalysis<MachineDominatorTree>(); 456 Loops = &getAnalysis<MachineLoopInfo>(); 457 LV = &getAnalysis<LiveVariables>(); 458 MRI = &MF.getRegInfo(); 459 460 if (skipFunction(MF.getFunction())) 461 return false; 462 463 bool MadeChange = false; 464 465 // TODO: we need to think about the order of visiting the blocks to get 466 // optimal result for nesting if-else cases. 467 for (MachineBasicBlock &MBB : MF) { 468 for (auto &MI : MBB.terminators()) { 469 // Detect the if-else blocks 470 if (MI.getOpcode() == AMDGPU::SI_IF) { 471 MachineBasicBlock *IfTarget = MI.getOperand(2).getMBB(); 472 auto *Endif = getElseTarget(IfTarget); 473 if (!Endif) 474 continue; 475 476 SmallSetVector<MachineBasicBlock *, 16> ElseBlocks; 477 SmallVector<Register> CandidateRegs; 478 479 LLVM_DEBUG(dbgs() << "Checking IF-ELSE-ENDIF: " 480 << printMBBReference(MBB) << ' ' 481 << printMBBReference(*IfTarget) << ' ' 482 << printMBBReference(*Endif) << '\n'); 483 484 // Collect all the blocks in the ELSE region 485 collectElseRegionBlocks(IfTarget, Endif, ElseBlocks); 486 487 // Collect the registers can be optimized 488 collectCandidateRegisters(&MBB, IfTarget, Endif, ElseBlocks, 489 CandidateRegs); 490 MadeChange |= !CandidateRegs.empty(); 491 // Now we are safe to optimize. 492 for (auto Reg : CandidateRegs) 493 optimizeLiveRange(Reg, &MBB, IfTarget, Endif, ElseBlocks); 494 } 495 } 496 } 497 498 return MadeChange; 499 } 500