LLVM 20.0.0git
AMDGPUUnifyDivergentExitNodes.cpp
Go to the documentation of this file.
1//===- AMDGPUUnifyDivergentExitNodes.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// This is a variant of the UnifyFunctionExitNodes pass. Rather than ensuring
10// there is at most one ret and one unreachable instruction, it ensures there is
11// at most one divergent exiting block.
12//
13// StructurizeCFG can't deal with multi-exit regions formed by branches to
14// multiple return nodes. It is not desirable to structurize regions with
15// uniform branches, so unifying those to the same return block as divergent
16// branches inhibits use of scalar branching. It still can't deal with the case
17// where one branch goes to return, and one unreachable. Replace unreachable in
18// this case with a return.
19//
20//===----------------------------------------------------------------------===//
21
23#include "AMDGPU.h"
24#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/StringRef.h"
32#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/CFG.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/InstrTypes.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/IntrinsicsAMDGPU.h"
42#include "llvm/IR/Type.h"
44#include "llvm/Pass.h"
50
51using namespace llvm;
52
53#define DEBUG_TYPE "amdgpu-unify-divergent-exit-nodes"
54
55namespace {
56
57class AMDGPUUnifyDivergentExitNodesImpl {
58private:
59 const TargetTransformInfo *TTI = nullptr;
60
61public:
62 AMDGPUUnifyDivergentExitNodesImpl() = delete;
63 AMDGPUUnifyDivergentExitNodesImpl(const TargetTransformInfo *TTI)
64 : TTI(TTI) {}
65
66 // We can preserve non-critical-edgeness when we unify function exit nodes
67 BasicBlock *unifyReturnBlockSet(Function &F, DomTreeUpdater &DTU,
68 ArrayRef<BasicBlock *> ReturningBlocks,
70 bool run(Function &F, DominatorTree *DT, const PostDominatorTree &PDT,
71 const UniformityInfo &UA);
72};
73
74class AMDGPUUnifyDivergentExitNodes : public FunctionPass {
75public:
76 static char ID;
77 AMDGPUUnifyDivergentExitNodes() : FunctionPass(ID) {
80 }
81 void getAnalysisUsage(AnalysisUsage &AU) const override;
82 bool runOnFunction(Function &F) override;
83};
84} // end anonymous namespace
85
86char AMDGPUUnifyDivergentExitNodes::ID = 0;
87
88char &llvm::AMDGPUUnifyDivergentExitNodesID = AMDGPUUnifyDivergentExitNodes::ID;
89
90INITIALIZE_PASS_BEGIN(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE,
91 "Unify divergent function exit nodes", false, false)
95INITIALIZE_PASS_END(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE,
96 "Unify divergent function exit nodes", false, false)
97
98void AMDGPUUnifyDivergentExitNodes::getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.addRequired<DominatorTreeWrapperPass>();
101
102 AU.addRequired<PostDominatorTreeWrapperPass>();
103
104 AU.addRequired<UniformityInfoWrapperPass>();
105
107 AU.addPreserved<DominatorTreeWrapperPass>();
108 // FIXME: preserve PostDominatorTreeWrapperPass
109 }
110
111 // We preserve the non-critical-edgeness property
112 AU.addPreservedID(BreakCriticalEdgesID);
113
114 FunctionPass::getAnalysisUsage(AU);
115
116 AU.addRequired<TargetTransformInfoWrapperPass>();
117}
118
119/// \returns true if \p BB is reachable through only uniform branches.
120/// XXX - Is there a more efficient way to find this?
121static bool isUniformlyReached(const UniformityInfo &UA, BasicBlock &BB) {
124
125 while (!Stack.empty()) {
126 BasicBlock *Top = Stack.pop_back_val();
127 if (!UA.isUniform(Top->getTerminator()))
128 return false;
129
130 for (BasicBlock *Pred : predecessors(Top)) {
131 if (Visited.insert(Pred).second)
132 Stack.push_back(Pred);
133 }
134 }
135
136 return true;
137}
138
139BasicBlock *AMDGPUUnifyDivergentExitNodesImpl::unifyReturnBlockSet(
140 Function &F, DomTreeUpdater &DTU, ArrayRef<BasicBlock *> ReturningBlocks,
141 StringRef Name) {
142 // Otherwise, we need to insert a new basic block into the function, add a PHI
143 // nodes (if the function returns values), and convert all of the return
144 // instructions into unconditional branches.
145 BasicBlock *NewRetBlock = BasicBlock::Create(F.getContext(), Name, &F);
146 IRBuilder<> B(NewRetBlock);
147
148 PHINode *PN = nullptr;
149 if (F.getReturnType()->isVoidTy()) {
150 B.CreateRetVoid();
151 } else {
152 // If the function doesn't return void... add a PHI node to the block...
153 PN = B.CreatePHI(F.getReturnType(), ReturningBlocks.size(),
154 "UnifiedRetVal");
155 B.CreateRet(PN);
156 }
157
158 // Loop over all of the blocks, replacing the return instruction with an
159 // unconditional branch.
160 std::vector<DominatorTree::UpdateType> Updates;
161 Updates.reserve(ReturningBlocks.size());
162 for (BasicBlock *BB : ReturningBlocks) {
163 // Add an incoming element to the PHI node for every return instruction that
164 // is merging into this new block...
165 if (PN)
166 PN->addIncoming(BB->getTerminator()->getOperand(0), BB);
167
168 // Remove and delete the return inst.
169 BB->getTerminator()->eraseFromParent();
170 BranchInst::Create(NewRetBlock, BB);
171 Updates.emplace_back(DominatorTree::Insert, BB, NewRetBlock);
172 }
173
175 DTU.applyUpdates(Updates);
176 Updates.clear();
177
178 for (BasicBlock *BB : ReturningBlocks) {
179 // Cleanup possible branch to unconditional branch to the return.
180 simplifyCFG(BB, *TTI, RequireAndPreserveDomTree ? &DTU : nullptr,
181 SimplifyCFGOptions().bonusInstThreshold(2));
182 }
183
184 return NewRetBlock;
185}
186
187bool AMDGPUUnifyDivergentExitNodesImpl::run(Function &F, DominatorTree *DT,
188 const PostDominatorTree &PDT,
189 const UniformityInfo &UA) {
190 assert(hasOnlySimpleTerminator(F) && "Unsupported block terminator.");
191
192 if (PDT.root_size() == 0 ||
193 (PDT.root_size() == 1 &&
194 !isa<BranchInst>(PDT.getRoot()->getTerminator())))
195 return false;
196
197 // Loop over all of the blocks in a function, tracking all of the blocks that
198 // return.
199 SmallVector<BasicBlock *, 4> ReturningBlocks;
200 SmallVector<BasicBlock *, 4> UnreachableBlocks;
201
202 // Dummy return block for infinite loop.
203 BasicBlock *DummyReturnBB = nullptr;
204
205 bool Changed = false;
206 std::vector<DominatorTree::UpdateType> Updates;
207
208 // TODO: For now we unify all exit blocks, even though they are uniformly
209 // reachable, if there are any exits not uniformly reached. This is to
210 // workaround the limitation of structurizer, which can not handle multiple
211 // function exits. After structurizer is able to handle multiple function
212 // exits, we should only unify UnreachableBlocks that are not uniformly
213 // reachable.
214 bool HasDivergentExitBlock = llvm::any_of(
215 PDT.roots(), [&](auto BB) { return !isUniformlyReached(UA, *BB); });
216
217 for (BasicBlock *BB : PDT.roots()) {
218 if (isa<ReturnInst>(BB->getTerminator())) {
219 if (HasDivergentExitBlock)
220 ReturningBlocks.push_back(BB);
221 } else if (isa<UnreachableInst>(BB->getTerminator())) {
222 if (HasDivergentExitBlock)
223 UnreachableBlocks.push_back(BB);
224 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
225
226 ConstantInt *BoolTrue = ConstantInt::getTrue(F.getContext());
227 if (DummyReturnBB == nullptr) {
228 DummyReturnBB = BasicBlock::Create(F.getContext(),
229 "DummyReturnBlock", &F);
230 Type *RetTy = F.getReturnType();
231 Value *RetVal = RetTy->isVoidTy() ? nullptr : PoisonValue::get(RetTy);
232 ReturnInst::Create(F.getContext(), RetVal, DummyReturnBB);
233 ReturningBlocks.push_back(DummyReturnBB);
234 }
235
236 if (BI->isUnconditional()) {
237 BasicBlock *LoopHeaderBB = BI->getSuccessor(0);
238 BI->eraseFromParent(); // Delete the unconditional branch.
239 // Add a new conditional branch with a dummy edge to the return block.
240 BranchInst::Create(LoopHeaderBB, DummyReturnBB, BoolTrue, BB);
241 Updates.emplace_back(DominatorTree::Insert, BB, DummyReturnBB);
242 } else { // Conditional branch.
244
245 // Create a new transition block to hold the conditional branch.
246 BasicBlock *TransitionBB = BB->splitBasicBlock(BI, "TransitionBlock");
247
248 Updates.reserve(Updates.size() + 2 * Successors.size() + 2);
249
250 // 'Successors' become successors of TransitionBB instead of BB,
251 // and TransitionBB becomes a single successor of BB.
252 Updates.emplace_back(DominatorTree::Insert, BB, TransitionBB);
253 for (BasicBlock *Successor : Successors) {
254 Updates.emplace_back(DominatorTree::Insert, TransitionBB, Successor);
255 Updates.emplace_back(DominatorTree::Delete, BB, Successor);
256 }
257
258 // Create a branch that will always branch to the transition block and
259 // references DummyReturnBB.
261 BranchInst::Create(TransitionBB, DummyReturnBB, BoolTrue, BB);
262 Updates.emplace_back(DominatorTree::Insert, BB, DummyReturnBB);
263 }
264 Changed = true;
265 }
266 }
267
268 if (!UnreachableBlocks.empty()) {
269 BasicBlock *UnreachableBlock = nullptr;
270
271 if (UnreachableBlocks.size() == 1) {
272 UnreachableBlock = UnreachableBlocks.front();
273 } else {
274 UnreachableBlock = BasicBlock::Create(F.getContext(),
275 "UnifiedUnreachableBlock", &F);
276 new UnreachableInst(F.getContext(), UnreachableBlock);
277
278 Updates.reserve(Updates.size() + UnreachableBlocks.size());
279 for (BasicBlock *BB : UnreachableBlocks) {
280 // Remove and delete the unreachable inst.
281 BB->getTerminator()->eraseFromParent();
282 BranchInst::Create(UnreachableBlock, BB);
283 Updates.emplace_back(DominatorTree::Insert, BB, UnreachableBlock);
284 }
285 Changed = true;
286 }
287
288 if (!ReturningBlocks.empty()) {
289 // Don't create a new unreachable inst if we have a return. The
290 // structurizer/annotator can't handle the multiple exits
291
292 Type *RetTy = F.getReturnType();
293 Value *RetVal = RetTy->isVoidTy() ? nullptr : PoisonValue::get(RetTy);
294 // Remove and delete the unreachable inst.
295 UnreachableBlock->getTerminator()->eraseFromParent();
296
297 Function *UnreachableIntrin = Intrinsic::getOrInsertDeclaration(
298 F.getParent(), Intrinsic::amdgcn_unreachable);
299
300 // Insert a call to an intrinsic tracking that this is an unreachable
301 // point, in case we want to kill the active lanes or something later.
302 CallInst::Create(UnreachableIntrin, {}, "", UnreachableBlock);
303
304 // Don't create a scalar trap. We would only want to trap if this code was
305 // really reached, but a scalar trap would happen even if no lanes
306 // actually reached here.
307 ReturnInst::Create(F.getContext(), RetVal, UnreachableBlock);
308 ReturningBlocks.push_back(UnreachableBlock);
309 Changed = true;
310 }
311 }
312
313 // FIXME: add PDT here once simplifycfg is ready.
314 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
316 DTU.applyUpdates(Updates);
317 Updates.clear();
318
319 // Now handle return blocks.
320 if (ReturningBlocks.empty())
321 return Changed; // No blocks return
322
323 if (ReturningBlocks.size() == 1)
324 return Changed; // Already has a single return block
325
326 unifyReturnBlockSet(F, DTU, ReturningBlocks, "UnifiedReturnBlock");
327 return true;
328}
329
330bool AMDGPUUnifyDivergentExitNodes::runOnFunction(Function &F) {
331 DominatorTree *DT = nullptr;
333 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
334 const auto &PDT =
335 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
336 const auto &UA = getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
337 const auto *TranformInfo =
338 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
339 return AMDGPUUnifyDivergentExitNodesImpl(TranformInfo).run(F, DT, PDT, UA);
340}
341
345 DominatorTree *DT = nullptr;
348
349 const auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
350 const auto &UA = AM.getResult<UniformityInfoAnalysis>(F);
351 const auto *TransformInfo = &AM.getResult<TargetIRAnalysis>(F);
352 return AMDGPUUnifyDivergentExitNodesImpl(TransformInfo).run(F, DT, PDT, UA)
355}
static bool isUniformlyReached(const UniformityInfo &UA, BasicBlock &BB)
Unify divergent function exit nodes
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
return RetTy
Performs the initial survey of the specified function
std::string Name
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
#define F(x, y, z)
Definition: MD5.cpp:55
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This pass exposes codegen information to IR-level passes.
LLVM IR instance of the generic uniformity analysis.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
Represent the analysis usage information of a pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:212
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="", bool Before=false)
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:577
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
Definition: BasicBlock.cpp:279
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:239
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:866
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
iterator_range< root_iterator > roots()
size_t root_size() const
NodeT * getRoot() const
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:317
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
bool isUniform(ConstValueRefT V) const
Whether V is uniform/non-divergent.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2697
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:94
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1878
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:384
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Analysis pass providing the TargetTransformInfo.
Result run(const Function &F, FunctionAnalysisManager &)
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
This function has undefined behavior.
LLVM Value Representation.
Definition: Value.h:74
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
Definition: Intrinsics.cpp:731
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool hasOnlySimpleTerminator(const Function &F)
auto successors(const MachineBasicBlock *BB)
char & AMDGPUUnifyDivergentExitNodesID
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1746
cl::opt< bool > RequireAndPreserveDomTree
This function is used to do simplification of a CFG.
bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, DomTreeUpdater *DTU=nullptr, const SimplifyCFGOptions &Options={}, ArrayRef< WeakVH > LoopHeaders={})
char & BreakCriticalEdgesID
auto predecessors(const MachineBasicBlock *BB)
void initializeAMDGPUUnifyDivergentExitNodesPass(PassRegistry &)