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 UnifyDivergentExitNodes 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 
22 #include "AMDGPU.h"
23 #include "SIDefines.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/Analysis/DomTreeUpdater.h"
29 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
30 #include "llvm/Analysis/PostDominators.h"
31 #include "llvm/Analysis/TargetTransformInfo.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"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/InitializePasses.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Transforms/Scalar.h"
46 #include "llvm/Transforms/Utils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "amdgpu-unify-divergent-exit-nodes"
52 
53 namespace {
54 
55 class AMDGPUUnifyDivergentExitNodes : public FunctionPass {
56 public:
57   static char ID; // Pass identification, replacement for typeid
58 
59   AMDGPUUnifyDivergentExitNodes() : FunctionPass(ID) {
60     initializeAMDGPUUnifyDivergentExitNodesPass(*PassRegistry::getPassRegistry());
61   }
62 
63   // We can preserve non-critical-edgeness when we unify function exit nodes
64   void getAnalysisUsage(AnalysisUsage &AU) const override;
65   bool runOnFunction(Function &F) override;
66 };
67 
68 } // end anonymous namespace
69 
70 char AMDGPUUnifyDivergentExitNodes::ID = 0;
71 
72 char &llvm::AMDGPUUnifyDivergentExitNodesID = AMDGPUUnifyDivergentExitNodes::ID;
73 
74 INITIALIZE_PASS_BEGIN(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE,
75                      "Unify divergent function exit nodes", false, false)
76 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
77 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
78 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
79 INITIALIZE_PASS_END(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE,
80                     "Unify divergent function exit nodes", false, false)
81 
82 void AMDGPUUnifyDivergentExitNodes::getAnalysisUsage(AnalysisUsage &AU) const{
83   if (RequireAndPreserveDomTree)
84     AU.addRequired<DominatorTreeWrapperPass>();
85 
86   AU.addRequired<PostDominatorTreeWrapperPass>();
87 
88   AU.addRequired<LegacyDivergenceAnalysis>();
89 
90   if (RequireAndPreserveDomTree) {
91     AU.addPreserved<DominatorTreeWrapperPass>();
92     // FIXME: preserve PostDominatorTreeWrapperPass
93   }
94 
95   // No divergent values are changed, only blocks and branch edges.
96   AU.addPreserved<LegacyDivergenceAnalysis>();
97 
98   // We preserve the non-critical-edgeness property
99   AU.addPreservedID(BreakCriticalEdgesID);
100 
101   // This is a cluster of orthogonal Transforms
102   AU.addPreservedID(LowerSwitchID);
103   FunctionPass::getAnalysisUsage(AU);
104 
105   AU.addRequired<TargetTransformInfoWrapperPass>();
106 }
107 
108 /// \returns true if \p BB is reachable through only uniform branches.
109 /// XXX - Is there a more efficient way to find this?
110 static bool isUniformlyReached(const LegacyDivergenceAnalysis &DA,
111                                BasicBlock &BB) {
112   SmallVector<BasicBlock *, 8> Stack;
113   SmallPtrSet<BasicBlock *, 8> Visited;
114 
115   for (BasicBlock *Pred : predecessors(&BB))
116     Stack.push_back(Pred);
117 
118   while (!Stack.empty()) {
119     BasicBlock *Top = Stack.pop_back_val();
120     if (!DA.isUniform(Top->getTerminator()))
121       return false;
122 
123     for (BasicBlock *Pred : predecessors(Top)) {
124       if (Visited.insert(Pred).second)
125         Stack.push_back(Pred);
126     }
127   }
128 
129   return true;
130 }
131 
132 static void removeDoneExport(Function &F) {
133   ConstantInt *BoolFalse = ConstantInt::getFalse(F.getContext());
134   for (BasicBlock &BB : F) {
135     for (Instruction &I : BB) {
136       if (IntrinsicInst *Intrin = llvm::dyn_cast<IntrinsicInst>(&I)) {
137         if (Intrin->getIntrinsicID() == Intrinsic::amdgcn_exp) {
138           Intrin->setArgOperand(6, BoolFalse); // done
139         } else if (Intrin->getIntrinsicID() == Intrinsic::amdgcn_exp_compr) {
140           Intrin->setArgOperand(4, BoolFalse); // done
141         }
142       }
143     }
144   }
145 }
146 
147 static BasicBlock *unifyReturnBlockSet(Function &F, DomTreeUpdater &DTU,
148                                        ArrayRef<BasicBlock *> ReturningBlocks,
149                                        bool InsertExport,
150                                        const TargetTransformInfo &TTI,
151                                        StringRef Name) {
152   // Otherwise, we need to insert a new basic block into the function, add a PHI
153   // nodes (if the function returns values), and convert all of the return
154   // instructions into unconditional branches.
155   BasicBlock *NewRetBlock = BasicBlock::Create(F.getContext(), Name, &F);
156   IRBuilder<> B(NewRetBlock);
157 
158   if (InsertExport) {
159     // Ensure that there's only one "done" export in the shader by removing the
160     // "done" bit set on the original final export. More than one "done" export
161     // can lead to undefined behavior.
162     removeDoneExport(F);
163 
164     Value *Undef = UndefValue::get(B.getFloatTy());
165     B.CreateIntrinsic(Intrinsic::amdgcn_exp, { B.getFloatTy() },
166                       {
167                         B.getInt32(AMDGPU::Exp::ET_NULL),
168                         B.getInt32(0), // enabled channels
169                         Undef, Undef, Undef, Undef, // values
170                         B.getTrue(), // done
171                         B.getTrue(), // valid mask
172                       });
173   }
174 
175   PHINode *PN = nullptr;
176   if (F.getReturnType()->isVoidTy()) {
177     B.CreateRetVoid();
178   } else {
179     // If the function doesn't return void... add a PHI node to the block...
180     PN = B.CreatePHI(F.getReturnType(), ReturningBlocks.size(),
181                      "UnifiedRetVal");
182     assert(!InsertExport);
183     B.CreateRet(PN);
184   }
185 
186   // Loop over all of the blocks, replacing the return instruction with an
187   // unconditional branch.
188   std::vector<DominatorTree::UpdateType> Updates;
189   Updates.reserve(ReturningBlocks.size());
190   for (BasicBlock *BB : ReturningBlocks) {
191     // Add an incoming element to the PHI node for every return instruction that
192     // is merging into this new block...
193     if (PN)
194       PN->addIncoming(BB->getTerminator()->getOperand(0), BB);
195 
196     // Remove and delete the return inst.
197     BB->getTerminator()->eraseFromParent();
198     BranchInst::Create(NewRetBlock, BB);
199     Updates.push_back({DominatorTree::Insert, BB, NewRetBlock});
200   }
201 
202   if (RequireAndPreserveDomTree)
203     DTU.applyUpdates(Updates);
204   Updates.clear();
205 
206   for (BasicBlock *BB : ReturningBlocks) {
207     // Cleanup possible branch to unconditional branch to the return.
208     simplifyCFG(BB, TTI, RequireAndPreserveDomTree ? &DTU : nullptr,
209                 SimplifyCFGOptions().bonusInstThreshold(2));
210   }
211 
212   return NewRetBlock;
213 }
214 
215 bool AMDGPUUnifyDivergentExitNodes::runOnFunction(Function &F) {
216   DominatorTree *DT = nullptr;
217   if (RequireAndPreserveDomTree)
218     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
219 
220   auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
221 
222   // If there's only one exit, we don't need to do anything, unless this is a
223   // pixel shader and that exit is an infinite loop, since we still have to
224   // insert an export in that case.
225   if (PDT.root_size() <= 1 && F.getCallingConv() != CallingConv::AMDGPU_PS)
226     return false;
227 
228   LegacyDivergenceAnalysis &DA = getAnalysis<LegacyDivergenceAnalysis>();
229 
230   // Loop over all of the blocks in a function, tracking all of the blocks that
231   // return.
232   SmallVector<BasicBlock *, 4> ReturningBlocks;
233   SmallVector<BasicBlock *, 4> UniformlyReachedRetBlocks;
234   SmallVector<BasicBlock *, 4> UnreachableBlocks;
235 
236   // Dummy return block for infinite loop.
237   BasicBlock *DummyReturnBB = nullptr;
238 
239   bool InsertExport = false;
240 
241   bool Changed = false;
242   std::vector<DominatorTree::UpdateType> Updates;
243 
244   for (BasicBlock *BB : PDT.roots()) {
245     if (isa<ReturnInst>(BB->getTerminator())) {
246       if (!isUniformlyReached(DA, *BB))
247         ReturningBlocks.push_back(BB);
248       else
249         UniformlyReachedRetBlocks.push_back(BB);
250     } else if (isa<UnreachableInst>(BB->getTerminator())) {
251       if (!isUniformlyReached(DA, *BB))
252         UnreachableBlocks.push_back(BB);
253     } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
254 
255       ConstantInt *BoolTrue = ConstantInt::getTrue(F.getContext());
256       if (DummyReturnBB == nullptr) {
257         DummyReturnBB = BasicBlock::Create(F.getContext(),
258                                            "DummyReturnBlock", &F);
259         Type *RetTy = F.getReturnType();
260         Value *RetVal = RetTy->isVoidTy() ? nullptr : UndefValue::get(RetTy);
261 
262         // For pixel shaders, the producer guarantees that an export is
263         // executed before each return instruction. However, if there is an
264         // infinite loop and we insert a return ourselves, we need to uphold
265         // that guarantee by inserting a null export. This can happen e.g. in
266         // an infinite loop with kill instructions, which is supposed to
267         // terminate. However, we don't need to do this if there is a non-void
268         // return value, since then there is an epilog afterwards which will
269         // still export.
270         //
271         // Note: In the case where only some threads enter the infinite loop,
272         // this can result in the null export happening redundantly after the
273         // original exports. However, The last "real" export happens after all
274         // the threads that didn't enter an infinite loop converged, which
275         // means that the only extra threads to execute the null export are
276         // threads that entered the infinite loop, and they only could've
277         // exited through being killed which sets their exec bit to 0.
278         // Therefore, unless there's an actual infinite loop, which can have
279         // invalid results, or there's a kill after the last export, which we
280         // assume the frontend won't do, this export will have the same exec
281         // mask as the last "real" export, and therefore the valid mask will be
282         // overwritten with the same value and will still be correct. Also,
283         // even though this forces an extra unnecessary export wait, we assume
284         // that this happens rare enough in practice to that we don't have to
285         // worry about performance.
286         if (F.getCallingConv() == CallingConv::AMDGPU_PS &&
287             RetTy->isVoidTy()) {
288           InsertExport = true;
289         }
290 
291         ReturnInst::Create(F.getContext(), RetVal, DummyReturnBB);
292         ReturningBlocks.push_back(DummyReturnBB);
293       }
294 
295       if (BI->isUnconditional()) {
296         BasicBlock *LoopHeaderBB = BI->getSuccessor(0);
297         BI->eraseFromParent(); // Delete the unconditional branch.
298         // Add a new conditional branch with a dummy edge to the return block.
299         BranchInst::Create(LoopHeaderBB, DummyReturnBB, BoolTrue, BB);
300         Updates.push_back({DominatorTree::Insert, BB, DummyReturnBB});
301       } else { // Conditional branch.
302         SmallVector<BasicBlock *, 2> Successors(succ_begin(BB), succ_end(BB));
303 
304         // Create a new transition block to hold the conditional branch.
305         BasicBlock *TransitionBB = BB->splitBasicBlock(BI, "TransitionBlock");
306 
307         Updates.reserve(Updates.size() + 2 * Successors.size() + 2);
308 
309         // 'Successors' become successors of TransitionBB instead of BB,
310         // and TransitionBB becomes a single successor of BB.
311         Updates.push_back({DominatorTree::Insert, BB, TransitionBB});
312         for (BasicBlock *Successor : Successors) {
313           Updates.push_back({DominatorTree::Insert, TransitionBB, Successor});
314           Updates.push_back({DominatorTree::Delete, BB, Successor});
315         }
316 
317         // Create a branch that will always branch to the transition block and
318         // references DummyReturnBB.
319         BB->getTerminator()->eraseFromParent();
320         BranchInst::Create(TransitionBB, DummyReturnBB, BoolTrue, BB);
321         Updates.push_back({DominatorTree::Insert, BB, DummyReturnBB});
322       }
323       Changed = true;
324     }
325   }
326 
327   if (!UnreachableBlocks.empty()) {
328     BasicBlock *UnreachableBlock = nullptr;
329 
330     if (UnreachableBlocks.size() == 1) {
331       UnreachableBlock = UnreachableBlocks.front();
332     } else {
333       UnreachableBlock = BasicBlock::Create(F.getContext(),
334                                             "UnifiedUnreachableBlock", &F);
335       new UnreachableInst(F.getContext(), UnreachableBlock);
336 
337       Updates.reserve(Updates.size() + UnreachableBlocks.size());
338       for (BasicBlock *BB : UnreachableBlocks) {
339         // Remove and delete the unreachable inst.
340         BB->getTerminator()->eraseFromParent();
341         BranchInst::Create(UnreachableBlock, BB);
342         Updates.push_back({DominatorTree::Insert, BB, UnreachableBlock});
343       }
344       Changed = true;
345     }
346 
347     if (!ReturningBlocks.empty()) {
348       // Don't create a new unreachable inst if we have a return. The
349       // structurizer/annotator can't handle the multiple exits
350 
351       Type *RetTy = F.getReturnType();
352       Value *RetVal = RetTy->isVoidTy() ? nullptr : UndefValue::get(RetTy);
353       // Remove and delete the unreachable inst.
354       UnreachableBlock->getTerminator()->eraseFromParent();
355 
356       Function *UnreachableIntrin =
357         Intrinsic::getDeclaration(F.getParent(), Intrinsic::amdgcn_unreachable);
358 
359       // Insert a call to an intrinsic tracking that this is an unreachable
360       // point, in case we want to kill the active lanes or something later.
361       CallInst::Create(UnreachableIntrin, {}, "", UnreachableBlock);
362 
363       // Don't create a scalar trap. We would only want to trap if this code was
364       // really reached, but a scalar trap would happen even if no lanes
365       // actually reached here.
366       ReturnInst::Create(F.getContext(), RetVal, UnreachableBlock);
367       ReturningBlocks.push_back(UnreachableBlock);
368       Changed = true;
369     }
370   }
371 
372   // FIXME: add PDT here once simplifycfg is ready.
373   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
374   if (RequireAndPreserveDomTree)
375     DTU.applyUpdates(Updates);
376   Updates.clear();
377 
378   // Now handle return blocks.
379   if (ReturningBlocks.empty())
380     return Changed; // No blocks return
381 
382   if (ReturningBlocks.size() == 1 && !InsertExport)
383     return Changed; // Already has a single return block
384 
385   const TargetTransformInfo &TTI
386     = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
387 
388   // Unify returning blocks. If we are going to insert the export it is also
389   // necessary to include blocks that are uniformly reached, because in addition
390   // to inserting the export the "done" bits on existing exports will be cleared
391   // and we do not want to end up with the normal export in a non-unified,
392   // uniformly reached block with the "done" bit cleared.
393   auto BlocksToUnify = std::move(ReturningBlocks);
394   if (InsertExport) {
395     llvm::append_range(BlocksToUnify, UniformlyReachedRetBlocks);
396   }
397 
398   unifyReturnBlockSet(F, DTU, BlocksToUnify, InsertExport, TTI,
399                       "UnifiedReturnBlock");
400   return true;
401 }
402