LLVM 23.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,
69 StringRef Name);
70 bool run(Function &F, DominatorTree *DT, const PostDominatorTree &PDT,
71 const UniformityInfo &UA);
72};
73
74class AMDGPUUnifyDivergentExitNodesLegacy : public FunctionPass {
75public:
76 static char ID;
77 AMDGPUUnifyDivergentExitNodesLegacy() : FunctionPass(ID) {}
78 void getAnalysisUsage(AnalysisUsage &AU) const override;
79 bool runOnFunction(Function &F) override;
80};
81} // end anonymous namespace
82
83char AMDGPUUnifyDivergentExitNodesLegacy::ID = 0;
84
86 AMDGPUUnifyDivergentExitNodesLegacy::ID;
87
88INITIALIZE_PASS_BEGIN(AMDGPUUnifyDivergentExitNodesLegacy, DEBUG_TYPE,
89 "Unify divergent function exit nodes", false, false)
93INITIALIZE_PASS_END(AMDGPUUnifyDivergentExitNodesLegacy, DEBUG_TYPE,
94 "Unify divergent function exit nodes", false, false)
95
96void AMDGPUUnifyDivergentExitNodesLegacy::getAnalysisUsage(
97 AnalysisUsage &AU) const {
99 AU.addRequired<DominatorTreeWrapperPass>();
100
101 AU.addRequired<PostDominatorTreeWrapperPass>();
102
103 AU.addRequired<UniformityInfoWrapperPass>();
104
106 AU.addPreserved<DominatorTreeWrapperPass>();
107 // FIXME: preserve PostDominatorTreeWrapperPass
108 }
109
110 // We preserve the non-critical-edgeness property
111 AU.addPreservedID(BreakCriticalEdgesID);
112
114
115 AU.addRequired<TargetTransformInfoWrapperPass>();
116}
117
118/// \returns true if \p BB is reachable through only uniform branches.
119/// XXX - Is there a more efficient way to find this?
120static bool isUniformlyReached(const UniformityInfo &UA, BasicBlock &BB) {
123
124 while (!Stack.empty()) {
125 BasicBlock *Top = Stack.pop_back_val();
126 if (!UA.isUniform(Top->getTerminator()))
127 return false;
128
129 for (BasicBlock *Pred : predecessors(Top)) {
130 if (Visited.insert(Pred).second)
131 Stack.push_back(Pred);
132 }
133 }
134
135 return true;
136}
137
138BasicBlock *AMDGPUUnifyDivergentExitNodesImpl::unifyReturnBlockSet(
139 Function &F, DomTreeUpdater &DTU, ArrayRef<BasicBlock *> ReturningBlocks,
140 StringRef Name) {
141 // Otherwise, we need to insert a new basic block into the function, add a PHI
142 // nodes (if the function returns values), and convert all of the return
143 // instructions into unconditional branches.
144 BasicBlock *NewRetBlock = BasicBlock::Create(F.getContext(), Name, &F);
145 IRBuilder<> B(NewRetBlock);
146
147 PHINode *PN = nullptr;
148 if (F.getReturnType()->isVoidTy()) {
149 B.CreateRetVoid();
150 } else {
151 // If the function doesn't return void... add a PHI node to the block...
152 PN = B.CreatePHI(F.getReturnType(), ReturningBlocks.size(),
153 "UnifiedRetVal");
154 B.CreateRet(PN);
155 }
156
157 // Loop over all of the blocks, replacing the return instruction with an
158 // unconditional branch.
159 std::vector<DominatorTree::UpdateType> Updates;
160 Updates.reserve(ReturningBlocks.size());
161 for (BasicBlock *BB : ReturningBlocks) {
162 // Add an incoming element to the PHI node for every return instruction that
163 // is merging into this new block...
164 if (PN)
165 PN->addIncoming(BB->getTerminator()->getOperand(0), BB);
166
167 // Remove and delete the return inst.
168 BB->getTerminator()->eraseFromParent();
169 UncondBrInst::Create(NewRetBlock, BB);
170 Updates.emplace_back(DominatorTree::Insert, BB, NewRetBlock);
171 }
172
174 DTU.applyUpdates(Updates);
175 Updates.clear();
176
177 for (BasicBlock *BB : ReturningBlocks) {
178 // Cleanup possible branch to unconditional branch to the return.
179 simplifyCFG(BB, *TTI, RequireAndPreserveDomTree ? &DTU : nullptr,
180 SimplifyCFGOptions().bonusInstThreshold(2));
181 }
182
183 return NewRetBlock;
184}
185
186static BasicBlock *
188 SmallVector<BasicBlock *, 4> &ReturningBlocks) {
189 BasicBlock *DummyReturnBB =
190 BasicBlock::Create(F.getContext(), "DummyReturnBlock", &F);
191 Type *RetTy = F.getReturnType();
192 Value *RetVal = RetTy->isVoidTy() ? nullptr : PoisonValue::get(RetTy);
193 ReturnInst::Create(F.getContext(), RetVal, DummyReturnBB);
194 ReturningBlocks.push_back(DummyReturnBB);
195 return DummyReturnBB;
196}
197
198/// Handle conditional branch instructions (-> 2 targets) and callbr
199/// instructions with N targets.
201 BasicBlock *DummyReturnBB,
202 std::vector<DominatorTree::UpdateType> &Updates) {
204
205 // Create a new transition block to hold the conditional branch.
206 BasicBlock *TransitionBB = BB->splitBasicBlock(BI, "TransitionBlock");
207
208 Updates.reserve(Updates.size() + 2 * Successors.size() + 2);
209
210 // 'Successors' become successors of TransitionBB instead of BB,
211 // and TransitionBB becomes a single successor of BB.
212 Updates.emplace_back(DominatorTree::Insert, BB, TransitionBB);
213 for (BasicBlock *Successor : Successors) {
214 Updates.emplace_back(DominatorTree::Insert, TransitionBB, Successor);
215 Updates.emplace_back(DominatorTree::Delete, BB, Successor);
216 }
217
218 // Create a branch that will always branch to the transition block and
219 // references DummyReturnBB.
221 CondBrInst::Create(ConstantInt::getTrue(F.getContext()), TransitionBB,
222 DummyReturnBB, BB);
223 Updates.emplace_back(DominatorTree::Insert, BB, DummyReturnBB);
224}
225
226bool AMDGPUUnifyDivergentExitNodesImpl::run(Function &F, DominatorTree *DT,
227 const PostDominatorTree &PDT,
228 const UniformityInfo &UA) {
229 if (PDT.root_size() == 0 ||
231 PDT.getRoot()->getTerminator())))
232 return false;
233
234 // Loop over all of the blocks in a function, tracking all of the blocks that
235 // return.
236 SmallVector<BasicBlock *, 4> ReturningBlocks;
237 SmallVector<BasicBlock *, 4> UnreachableBlocks;
238
239 // Dummy return block for infinite loop.
240 BasicBlock *DummyReturnBB = nullptr;
241
242 bool Changed = false;
243 std::vector<DominatorTree::UpdateType> Updates;
244
245 // TODO: For now we unify all exit blocks, even though they are uniformly
246 // reachable, if there are any exits not uniformly reached. This is to
247 // workaround the limitation of structurizer, which can not handle multiple
248 // function exits. After structurizer is able to handle multiple function
249 // exits, we should only unify UnreachableBlocks that are not uniformly
250 // reachable.
251 bool HasDivergentExitBlock = llvm::any_of(
252 PDT.roots(), [&](auto BB) { return !isUniformlyReached(UA, *BB); });
253
254 for (BasicBlock *BB : PDT.roots()) {
255 Instruction *Term = BB->getTerminator();
256 if (auto *RI = dyn_cast<ReturnInst>(Term)) {
257 auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode());
258 if (CI && CI->isMustTailCall())
259 continue;
260 if (HasDivergentExitBlock)
261 ReturningBlocks.push_back(BB);
262 } else if (isa<UnreachableInst>(Term)) {
263 if (HasDivergentExitBlock)
264 UnreachableBlocks.push_back(BB);
265 } else if (UncondBrInst *BI = dyn_cast<UncondBrInst>(Term)) {
266 if (!DummyReturnBB)
267 DummyReturnBB = createDummyReturnBlock(F, ReturningBlocks);
268
269 BasicBlock *LoopHeaderBB = BI->getSuccessor();
270 BI->eraseFromParent(); // Delete the unconditional branch.
271 // Add a new conditional branch with a dummy edge to the return block.
272 CondBrInst::Create(ConstantInt::getTrue(F.getContext()), LoopHeaderBB,
273 DummyReturnBB, BB);
274 Updates.emplace_back(DominatorTree::Insert, BB, DummyReturnBB);
275 Changed = true;
276 } else if (isa<CondBrInst, CallBrInst>(Term)) {
277 if (!DummyReturnBB)
278 DummyReturnBB = createDummyReturnBlock(F, ReturningBlocks);
279
280 handleNBranch(F, BB, Term, DummyReturnBB, Updates);
281 Changed = true;
282 } else {
283 llvm_unreachable("unsupported block terminator");
284 }
285 }
286
287 if (!UnreachableBlocks.empty()) {
288 BasicBlock *UnreachableBlock = nullptr;
289
290 if (UnreachableBlocks.size() == 1) {
291 UnreachableBlock = UnreachableBlocks.front();
292 } else {
293 UnreachableBlock = BasicBlock::Create(F.getContext(),
294 "UnifiedUnreachableBlock", &F);
295 new UnreachableInst(F.getContext(), UnreachableBlock);
296
297 Updates.reserve(Updates.size() + UnreachableBlocks.size());
298 for (BasicBlock *BB : UnreachableBlocks) {
299 // Remove and delete the unreachable inst.
300 BB->getTerminator()->eraseFromParent();
301 UncondBrInst::Create(UnreachableBlock, BB);
302 Updates.emplace_back(DominatorTree::Insert, BB, UnreachableBlock);
303 }
304 Changed = true;
305 }
306
307 if (!ReturningBlocks.empty()) {
308 // Don't create a new unreachable inst if we have a return. The
309 // structurizer/annotator can't handle the multiple exits
310
311 Type *RetTy = F.getReturnType();
312 Value *RetVal = RetTy->isVoidTy() ? nullptr : PoisonValue::get(RetTy);
313 // Remove and delete the unreachable inst.
314 UnreachableBlock->getTerminator()->eraseFromParent();
315
316 Function *UnreachableIntrin = Intrinsic::getOrInsertDeclaration(
317 F.getParent(), Intrinsic::amdgcn_unreachable);
318
319 // Insert a call to an intrinsic tracking that this is an unreachable
320 // point, in case we want to kill the active lanes or something later.
321 CallInst::Create(UnreachableIntrin, {}, "", UnreachableBlock);
322
323 // Don't create a scalar trap. We would only want to trap if this code was
324 // really reached, but a scalar trap would happen even if no lanes
325 // actually reached here.
326 ReturnInst::Create(F.getContext(), RetVal, UnreachableBlock);
327 ReturningBlocks.push_back(UnreachableBlock);
328 Changed = true;
329 }
330 }
331
332 // FIXME: add PDT here once simplifycfg is ready.
333 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
335 DTU.applyUpdates(Updates);
336 Updates.clear();
337
338 // Now handle return blocks.
339 if (ReturningBlocks.empty())
340 return Changed; // No blocks return
341
342 if (ReturningBlocks.size() == 1)
343 return Changed; // Already has a single return block
344
345 unifyReturnBlockSet(F, DTU, ReturningBlocks, "UnifiedReturnBlock");
346 return true;
347}
348
349bool AMDGPUUnifyDivergentExitNodesLegacy::runOnFunction(Function &F) {
350 DominatorTree *DT = nullptr;
352 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
353 const auto &PDT =
354 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
355 const auto &UA = getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
356 const auto *TranformInfo =
357 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
358 return AMDGPUUnifyDivergentExitNodesImpl(TranformInfo).run(F, DT, PDT, UA);
359}
360
361PreservedAnalyses
364 DominatorTree *DT = nullptr;
367
368 const auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
369 const auto &UA = AM.getResult<UniformityInfoAnalysis>(F);
370 const auto *TransformInfo = &AM.getResult<TargetIRAnalysis>(F);
371 return AMDGPUUnifyDivergentExitNodesImpl(TransformInfo).run(F, DT, PDT, UA)
374}
static BasicBlock * createDummyReturnBlock(Function &F, SmallVector< BasicBlock *, 4 > &ReturningBlocks)
static bool isUniformlyReached(const UniformityInfo &UA, BasicBlock &BB)
static void handleNBranch(Function &F, BasicBlock *BB, Instruction *BI, BasicBlock *DummyReturnBB, std::vector< DominatorTree::UpdateType > &Updates)
Handle conditional branch instructions (-> 2 targets) and callbr instructions with N targets.
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...
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
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:54
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
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)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
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:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
Analysis pass which computes a DominatorTree.
Definition Dominators.h:278
iterator_range< root_iterator > roots()
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:316
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:159
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
bool isUniform(ConstValueRefT V) const
Whether V is uniform/non-divergent.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition Pass.cpp:112
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
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.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Analysis pass providing the TargetTransformInfo.
LLVM_ABI 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:46
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
LLVM Value Representation.
Definition Value.h:75
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
char & AMDGPUUnifyDivergentExitNodesID
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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
LLVM_ABI char & BreakCriticalEdgesID
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI cl::opt< bool > RequireAndPreserveDomTree
This function is used to do simplification of a CFG.
LLVM_ABI bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, DomTreeUpdater *DTU=nullptr, const SimplifyCFGOptions &Options={}, ArrayRef< WeakVH > LoopHeaders={})
auto predecessors(const MachineBasicBlock *BB)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.