10b57cec5SDimitry Andric //===- AMDGPUUnifyDivergentExitNodes.cpp ----------------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 9fe6060f1SDimitry Andric // This is a variant of the UnifyFunctionExitNodes pass. Rather than ensuring 100b57cec5SDimitry Andric // there is at most one ret and one unreachable instruction, it ensures there is 110b57cec5SDimitry Andric // at most one divergent exiting block. 120b57cec5SDimitry Andric // 130b57cec5SDimitry Andric // StructurizeCFG can't deal with multi-exit regions formed by branches to 140b57cec5SDimitry Andric // multiple return nodes. It is not desirable to structurize regions with 150b57cec5SDimitry Andric // uniform branches, so unifying those to the same return block as divergent 160b57cec5SDimitry Andric // branches inhibits use of scalar branching. It still can't deal with the case 170b57cec5SDimitry Andric // where one branch goes to return, and one unreachable. Replace unreachable in 180b57cec5SDimitry Andric // this case with a return. 190b57cec5SDimitry Andric // 200b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 210b57cec5SDimitry Andric 220b57cec5SDimitry Andric #include "AMDGPU.h" 23e8d8bef9SDimitry Andric #include "SIDefines.h" 240b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h" 250b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 260b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 270b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h" 28e8d8bef9SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h" 290b57cec5SDimitry Andric #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 300b57cec5SDimitry Andric #include "llvm/Analysis/PostDominators.h" 310b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h" 320b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h" 330b57cec5SDimitry Andric #include "llvm/IR/CFG.h" 340b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 35e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h" 360b57cec5SDimitry Andric #include "llvm/IR/Function.h" 37e8d8bef9SDimitry Andric #include "llvm/IR/IRBuilder.h" 380b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h" 390b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 400b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 41e8d8bef9SDimitry Andric #include "llvm/IR/IntrinsicsAMDGPU.h" 420b57cec5SDimitry Andric #include "llvm/IR/Type.h" 43480093f4SDimitry Andric #include "llvm/InitializePasses.h" 440b57cec5SDimitry Andric #include "llvm/Pass.h" 450b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 460b57cec5SDimitry Andric #include "llvm/Transforms/Scalar.h" 470b57cec5SDimitry Andric #include "llvm/Transforms/Utils.h" 48480093f4SDimitry Andric #include "llvm/Transforms/Utils/Local.h" 490b57cec5SDimitry Andric 500b57cec5SDimitry Andric using namespace llvm; 510b57cec5SDimitry Andric 520b57cec5SDimitry Andric #define DEBUG_TYPE "amdgpu-unify-divergent-exit-nodes" 530b57cec5SDimitry Andric 540b57cec5SDimitry Andric namespace { 550b57cec5SDimitry Andric 560b57cec5SDimitry Andric class AMDGPUUnifyDivergentExitNodes : public FunctionPass { 57fe6060f1SDimitry Andric private: 58fe6060f1SDimitry Andric const TargetTransformInfo *TTI = nullptr; 59fe6060f1SDimitry Andric 600b57cec5SDimitry Andric public: 610b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid 620b57cec5SDimitry Andric 630b57cec5SDimitry Andric AMDGPUUnifyDivergentExitNodes() : FunctionPass(ID) { 640b57cec5SDimitry Andric initializeAMDGPUUnifyDivergentExitNodesPass(*PassRegistry::getPassRegistry()); 650b57cec5SDimitry Andric } 660b57cec5SDimitry Andric 670b57cec5SDimitry Andric // We can preserve non-critical-edgeness when we unify function exit nodes 680b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override; 69fe6060f1SDimitry Andric BasicBlock *unifyReturnBlockSet(Function &F, DomTreeUpdater &DTU, 70fe6060f1SDimitry Andric ArrayRef<BasicBlock *> ReturningBlocks, 71fe6060f1SDimitry Andric StringRef Name); 720b57cec5SDimitry Andric bool runOnFunction(Function &F) override; 730b57cec5SDimitry Andric }; 740b57cec5SDimitry Andric 750b57cec5SDimitry Andric } // end anonymous namespace 760b57cec5SDimitry Andric 770b57cec5SDimitry Andric char AMDGPUUnifyDivergentExitNodes::ID = 0; 780b57cec5SDimitry Andric 790b57cec5SDimitry Andric char &llvm::AMDGPUUnifyDivergentExitNodesID = AMDGPUUnifyDivergentExitNodes::ID; 800b57cec5SDimitry Andric 810b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE, 820b57cec5SDimitry Andric "Unify divergent function exit nodes", false, false) 83e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 840b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 850b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis) 860b57cec5SDimitry Andric INITIALIZE_PASS_END(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE, 870b57cec5SDimitry Andric "Unify divergent function exit nodes", false, false) 880b57cec5SDimitry Andric 890b57cec5SDimitry Andric void AMDGPUUnifyDivergentExitNodes::getAnalysisUsage(AnalysisUsage &AU) const{ 90e8d8bef9SDimitry Andric if (RequireAndPreserveDomTree) 91e8d8bef9SDimitry Andric AU.addRequired<DominatorTreeWrapperPass>(); 92e8d8bef9SDimitry Andric 930b57cec5SDimitry Andric AU.addRequired<PostDominatorTreeWrapperPass>(); 940b57cec5SDimitry Andric 950b57cec5SDimitry Andric AU.addRequired<LegacyDivergenceAnalysis>(); 960b57cec5SDimitry Andric 97e8d8bef9SDimitry Andric if (RequireAndPreserveDomTree) { 98e8d8bef9SDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>(); 99e8d8bef9SDimitry Andric // FIXME: preserve PostDominatorTreeWrapperPass 100e8d8bef9SDimitry Andric } 101e8d8bef9SDimitry Andric 1020b57cec5SDimitry Andric // No divergent values are changed, only blocks and branch edges. 1030b57cec5SDimitry Andric AU.addPreserved<LegacyDivergenceAnalysis>(); 1040b57cec5SDimitry Andric 1050b57cec5SDimitry Andric // We preserve the non-critical-edgeness property 1060b57cec5SDimitry Andric AU.addPreservedID(BreakCriticalEdgesID); 1070b57cec5SDimitry Andric 1080b57cec5SDimitry Andric // This is a cluster of orthogonal Transforms 1090b57cec5SDimitry Andric AU.addPreservedID(LowerSwitchID); 1100b57cec5SDimitry Andric FunctionPass::getAnalysisUsage(AU); 1110b57cec5SDimitry Andric 1120b57cec5SDimitry Andric AU.addRequired<TargetTransformInfoWrapperPass>(); 1130b57cec5SDimitry Andric } 1140b57cec5SDimitry Andric 1150b57cec5SDimitry Andric /// \returns true if \p BB is reachable through only uniform branches. 1160b57cec5SDimitry Andric /// XXX - Is there a more efficient way to find this? 1170b57cec5SDimitry Andric static bool isUniformlyReached(const LegacyDivergenceAnalysis &DA, 1180b57cec5SDimitry Andric BasicBlock &BB) { 119fe6060f1SDimitry Andric SmallVector<BasicBlock *, 8> Stack(predecessors(&BB)); 1200b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 8> Visited; 1210b57cec5SDimitry Andric 1220b57cec5SDimitry Andric while (!Stack.empty()) { 1230b57cec5SDimitry Andric BasicBlock *Top = Stack.pop_back_val(); 1240b57cec5SDimitry Andric if (!DA.isUniform(Top->getTerminator())) 1250b57cec5SDimitry Andric return false; 1260b57cec5SDimitry Andric 1270b57cec5SDimitry Andric for (BasicBlock *Pred : predecessors(Top)) { 1280b57cec5SDimitry Andric if (Visited.insert(Pred).second) 1290b57cec5SDimitry Andric Stack.push_back(Pred); 1300b57cec5SDimitry Andric } 1310b57cec5SDimitry Andric } 1320b57cec5SDimitry Andric 1330b57cec5SDimitry Andric return true; 1340b57cec5SDimitry Andric } 1350b57cec5SDimitry Andric 136fe6060f1SDimitry Andric BasicBlock *AMDGPUUnifyDivergentExitNodes::unifyReturnBlockSet( 137fe6060f1SDimitry Andric Function &F, DomTreeUpdater &DTU, ArrayRef<BasicBlock *> ReturningBlocks, 1380b57cec5SDimitry Andric StringRef Name) { 1390b57cec5SDimitry Andric // Otherwise, we need to insert a new basic block into the function, add a PHI 1400b57cec5SDimitry Andric // nodes (if the function returns values), and convert all of the return 1410b57cec5SDimitry Andric // instructions into unconditional branches. 1420b57cec5SDimitry Andric BasicBlock *NewRetBlock = BasicBlock::Create(F.getContext(), Name, &F); 14313138422SDimitry Andric IRBuilder<> B(NewRetBlock); 14413138422SDimitry Andric 1450b57cec5SDimitry Andric PHINode *PN = nullptr; 1460b57cec5SDimitry Andric if (F.getReturnType()->isVoidTy()) { 14713138422SDimitry Andric B.CreateRetVoid(); 1480b57cec5SDimitry Andric } else { 1490b57cec5SDimitry Andric // If the function doesn't return void... add a PHI node to the block... 15013138422SDimitry Andric PN = B.CreatePHI(F.getReturnType(), ReturningBlocks.size(), 1510b57cec5SDimitry Andric "UnifiedRetVal"); 15213138422SDimitry Andric B.CreateRet(PN); 1530b57cec5SDimitry Andric } 1540b57cec5SDimitry Andric 1550b57cec5SDimitry Andric // Loop over all of the blocks, replacing the return instruction with an 1560b57cec5SDimitry Andric // unconditional branch. 157e8d8bef9SDimitry Andric std::vector<DominatorTree::UpdateType> Updates; 158e8d8bef9SDimitry Andric Updates.reserve(ReturningBlocks.size()); 1590b57cec5SDimitry Andric for (BasicBlock *BB : ReturningBlocks) { 1600b57cec5SDimitry Andric // Add an incoming element to the PHI node for every return instruction that 1610b57cec5SDimitry Andric // is merging into this new block... 1620b57cec5SDimitry Andric if (PN) 1630b57cec5SDimitry Andric PN->addIncoming(BB->getTerminator()->getOperand(0), BB); 1640b57cec5SDimitry Andric 1650b57cec5SDimitry Andric // Remove and delete the return inst. 1660b57cec5SDimitry Andric BB->getTerminator()->eraseFromParent(); 1670b57cec5SDimitry Andric BranchInst::Create(NewRetBlock, BB); 168e8d8bef9SDimitry Andric Updates.push_back({DominatorTree::Insert, BB, NewRetBlock}); 1690b57cec5SDimitry Andric } 1700b57cec5SDimitry Andric 171e8d8bef9SDimitry Andric if (RequireAndPreserveDomTree) 172e8d8bef9SDimitry Andric DTU.applyUpdates(Updates); 173e8d8bef9SDimitry Andric Updates.clear(); 174e8d8bef9SDimitry Andric 1750b57cec5SDimitry Andric for (BasicBlock *BB : ReturningBlocks) { 1760b57cec5SDimitry Andric // Cleanup possible branch to unconditional branch to the return. 177fe6060f1SDimitry Andric simplifyCFG(BB, *TTI, RequireAndPreserveDomTree ? &DTU : nullptr, 178e8d8bef9SDimitry Andric SimplifyCFGOptions().bonusInstThreshold(2)); 1790b57cec5SDimitry Andric } 1800b57cec5SDimitry Andric 1810b57cec5SDimitry Andric return NewRetBlock; 1820b57cec5SDimitry Andric } 1830b57cec5SDimitry Andric 1840b57cec5SDimitry Andric bool AMDGPUUnifyDivergentExitNodes::runOnFunction(Function &F) { 185e8d8bef9SDimitry Andric DominatorTree *DT = nullptr; 186e8d8bef9SDimitry Andric if (RequireAndPreserveDomTree) 187e8d8bef9SDimitry Andric DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 188e8d8bef9SDimitry Andric 1890b57cec5SDimitry Andric auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 1905ffd83dbSDimitry Andric 191fe6060f1SDimitry Andric // If there's only one exit, we don't need to do anything. 192fe6060f1SDimitry Andric if (PDT.root_size() <= 1) 1930b57cec5SDimitry Andric return false; 1940b57cec5SDimitry Andric 1950b57cec5SDimitry Andric LegacyDivergenceAnalysis &DA = getAnalysis<LegacyDivergenceAnalysis>(); 196fe6060f1SDimitry Andric TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 1970b57cec5SDimitry Andric 1980b57cec5SDimitry Andric // Loop over all of the blocks in a function, tracking all of the blocks that 1990b57cec5SDimitry Andric // return. 2000b57cec5SDimitry Andric SmallVector<BasicBlock *, 4> ReturningBlocks; 2010b57cec5SDimitry Andric SmallVector<BasicBlock *, 4> UnreachableBlocks; 2020b57cec5SDimitry Andric 2030b57cec5SDimitry Andric // Dummy return block for infinite loop. 2040b57cec5SDimitry Andric BasicBlock *DummyReturnBB = nullptr; 2050b57cec5SDimitry Andric 2065ffd83dbSDimitry Andric bool Changed = false; 207e8d8bef9SDimitry Andric std::vector<DominatorTree::UpdateType> Updates; 208e8d8bef9SDimitry Andric 2095ffd83dbSDimitry Andric for (BasicBlock *BB : PDT.roots()) { 2100b57cec5SDimitry Andric if (isa<ReturnInst>(BB->getTerminator())) { 2110b57cec5SDimitry Andric if (!isUniformlyReached(DA, *BB)) 2120b57cec5SDimitry Andric ReturningBlocks.push_back(BB); 2130b57cec5SDimitry Andric } else if (isa<UnreachableInst>(BB->getTerminator())) { 2140b57cec5SDimitry Andric if (!isUniformlyReached(DA, *BB)) 2150b57cec5SDimitry Andric UnreachableBlocks.push_back(BB); 2160b57cec5SDimitry Andric } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 2170b57cec5SDimitry Andric 2180b57cec5SDimitry Andric ConstantInt *BoolTrue = ConstantInt::getTrue(F.getContext()); 2190b57cec5SDimitry Andric if (DummyReturnBB == nullptr) { 2200b57cec5SDimitry Andric DummyReturnBB = BasicBlock::Create(F.getContext(), 2210b57cec5SDimitry Andric "DummyReturnBlock", &F); 2220b57cec5SDimitry Andric Type *RetTy = F.getReturnType(); 2230b57cec5SDimitry Andric Value *RetVal = RetTy->isVoidTy() ? nullptr : UndefValue::get(RetTy); 2240b57cec5SDimitry Andric ReturnInst::Create(F.getContext(), RetVal, DummyReturnBB); 2250b57cec5SDimitry Andric ReturningBlocks.push_back(DummyReturnBB); 2260b57cec5SDimitry Andric } 2270b57cec5SDimitry Andric 2280b57cec5SDimitry Andric if (BI->isUnconditional()) { 2290b57cec5SDimitry Andric BasicBlock *LoopHeaderBB = BI->getSuccessor(0); 2300b57cec5SDimitry Andric BI->eraseFromParent(); // Delete the unconditional branch. 2310b57cec5SDimitry Andric // Add a new conditional branch with a dummy edge to the return block. 2320b57cec5SDimitry Andric BranchInst::Create(LoopHeaderBB, DummyReturnBB, BoolTrue, BB); 233e8d8bef9SDimitry Andric Updates.push_back({DominatorTree::Insert, BB, DummyReturnBB}); 2340b57cec5SDimitry Andric } else { // Conditional branch. 235*349cc55cSDimitry Andric SmallVector<BasicBlock *, 2> Successors(successors(BB)); 236e8d8bef9SDimitry Andric 2370b57cec5SDimitry Andric // Create a new transition block to hold the conditional branch. 2380b57cec5SDimitry Andric BasicBlock *TransitionBB = BB->splitBasicBlock(BI, "TransitionBlock"); 2390b57cec5SDimitry Andric 240e8d8bef9SDimitry Andric Updates.reserve(Updates.size() + 2 * Successors.size() + 2); 241e8d8bef9SDimitry Andric 242e8d8bef9SDimitry Andric // 'Successors' become successors of TransitionBB instead of BB, 243e8d8bef9SDimitry Andric // and TransitionBB becomes a single successor of BB. 244e8d8bef9SDimitry Andric Updates.push_back({DominatorTree::Insert, BB, TransitionBB}); 245e8d8bef9SDimitry Andric for (BasicBlock *Successor : Successors) { 246e8d8bef9SDimitry Andric Updates.push_back({DominatorTree::Insert, TransitionBB, Successor}); 247e8d8bef9SDimitry Andric Updates.push_back({DominatorTree::Delete, BB, Successor}); 248e8d8bef9SDimitry Andric } 249e8d8bef9SDimitry Andric 2500b57cec5SDimitry Andric // Create a branch that will always branch to the transition block and 2510b57cec5SDimitry Andric // references DummyReturnBB. 2520b57cec5SDimitry Andric BB->getTerminator()->eraseFromParent(); 2530b57cec5SDimitry Andric BranchInst::Create(TransitionBB, DummyReturnBB, BoolTrue, BB); 254e8d8bef9SDimitry Andric Updates.push_back({DominatorTree::Insert, BB, DummyReturnBB}); 2550b57cec5SDimitry Andric } 2565ffd83dbSDimitry Andric Changed = true; 2570b57cec5SDimitry Andric } 2580b57cec5SDimitry Andric } 2590b57cec5SDimitry Andric 2600b57cec5SDimitry Andric if (!UnreachableBlocks.empty()) { 2610b57cec5SDimitry Andric BasicBlock *UnreachableBlock = nullptr; 2620b57cec5SDimitry Andric 2630b57cec5SDimitry Andric if (UnreachableBlocks.size() == 1) { 2640b57cec5SDimitry Andric UnreachableBlock = UnreachableBlocks.front(); 2650b57cec5SDimitry Andric } else { 2660b57cec5SDimitry Andric UnreachableBlock = BasicBlock::Create(F.getContext(), 2670b57cec5SDimitry Andric "UnifiedUnreachableBlock", &F); 2680b57cec5SDimitry Andric new UnreachableInst(F.getContext(), UnreachableBlock); 2690b57cec5SDimitry Andric 270e8d8bef9SDimitry Andric Updates.reserve(Updates.size() + UnreachableBlocks.size()); 2710b57cec5SDimitry Andric for (BasicBlock *BB : UnreachableBlocks) { 2720b57cec5SDimitry Andric // Remove and delete the unreachable inst. 2730b57cec5SDimitry Andric BB->getTerminator()->eraseFromParent(); 2740b57cec5SDimitry Andric BranchInst::Create(UnreachableBlock, BB); 275e8d8bef9SDimitry Andric Updates.push_back({DominatorTree::Insert, BB, UnreachableBlock}); 2760b57cec5SDimitry Andric } 2775ffd83dbSDimitry Andric Changed = true; 2780b57cec5SDimitry Andric } 2790b57cec5SDimitry Andric 2800b57cec5SDimitry Andric if (!ReturningBlocks.empty()) { 2810b57cec5SDimitry Andric // Don't create a new unreachable inst if we have a return. The 2820b57cec5SDimitry Andric // structurizer/annotator can't handle the multiple exits 2830b57cec5SDimitry Andric 2840b57cec5SDimitry Andric Type *RetTy = F.getReturnType(); 2850b57cec5SDimitry Andric Value *RetVal = RetTy->isVoidTy() ? nullptr : UndefValue::get(RetTy); 2860b57cec5SDimitry Andric // Remove and delete the unreachable inst. 2870b57cec5SDimitry Andric UnreachableBlock->getTerminator()->eraseFromParent(); 2880b57cec5SDimitry Andric 2890b57cec5SDimitry Andric Function *UnreachableIntrin = 2900b57cec5SDimitry Andric Intrinsic::getDeclaration(F.getParent(), Intrinsic::amdgcn_unreachable); 2910b57cec5SDimitry Andric 2920b57cec5SDimitry Andric // Insert a call to an intrinsic tracking that this is an unreachable 2930b57cec5SDimitry Andric // point, in case we want to kill the active lanes or something later. 2940b57cec5SDimitry Andric CallInst::Create(UnreachableIntrin, {}, "", UnreachableBlock); 2950b57cec5SDimitry Andric 2960b57cec5SDimitry Andric // Don't create a scalar trap. We would only want to trap if this code was 2970b57cec5SDimitry Andric // really reached, but a scalar trap would happen even if no lanes 2980b57cec5SDimitry Andric // actually reached here. 2990b57cec5SDimitry Andric ReturnInst::Create(F.getContext(), RetVal, UnreachableBlock); 3000b57cec5SDimitry Andric ReturningBlocks.push_back(UnreachableBlock); 3015ffd83dbSDimitry Andric Changed = true; 3020b57cec5SDimitry Andric } 3030b57cec5SDimitry Andric } 3040b57cec5SDimitry Andric 305e8d8bef9SDimitry Andric // FIXME: add PDT here once simplifycfg is ready. 306e8d8bef9SDimitry Andric DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 307e8d8bef9SDimitry Andric if (RequireAndPreserveDomTree) 308e8d8bef9SDimitry Andric DTU.applyUpdates(Updates); 309e8d8bef9SDimitry Andric Updates.clear(); 310e8d8bef9SDimitry Andric 3110b57cec5SDimitry Andric // Now handle return blocks. 3120b57cec5SDimitry Andric if (ReturningBlocks.empty()) 3135ffd83dbSDimitry Andric return Changed; // No blocks return 3140b57cec5SDimitry Andric 315fe6060f1SDimitry Andric if (ReturningBlocks.size() == 1) 3165ffd83dbSDimitry Andric return Changed; // Already has a single return block 3170b57cec5SDimitry Andric 318fe6060f1SDimitry Andric unifyReturnBlockSet(F, DTU, ReturningBlocks, "UnifiedReturnBlock"); 3190b57cec5SDimitry Andric return true; 3200b57cec5SDimitry Andric } 321