blob: 52212e1c42aa6ab2393abb8dc99a68b76f00df9e [file] [log] [blame]
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +00001//===- LegacyDivergenceAnalysis.cpp --------- Legacy Divergence Analysis
2//Implementation -==//
Jingyue Wu5da831c2015-04-10 05:03:50 +00003//
Chandler Carruth2946cd72019-01-19 08:50:56 +00004// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Jingyue Wu5da831c2015-04-10 05:03:50 +00007//
8//===----------------------------------------------------------------------===//
9//
Marcello Maggioniab58c742015-09-21 17:58:14 +000010// This file implements divergence analysis which determines whether a branch
11// in a GPU program is divergent.It can help branch optimizations such as jump
Jingyue Wu5da831c2015-04-10 05:03:50 +000012// threading and loop unswitching to make better decisions.
13//
14// GPU programs typically use the SIMD execution model, where multiple threads
15// in the same execution group have to execute in lock-step. Therefore, if the
16// code contains divergent branches (i.e., threads in a group do not agree on
17// which path of the branch to take), the group of threads has to execute all
18// the paths from that branch with different subsets of threads enabled until
19// they converge at the immediately post-dominating BB of the paths.
20//
21// Due to this execution model, some optimizations such as jump
22// threading and loop unswitching can be unfortunately harmful when performed on
23// divergent branches. Therefore, an analysis that computes which branches in a
24// GPU program are divergent can help the compiler to selectively run these
25// optimizations.
26//
27// This file defines divergence analysis which computes a conservative but
28// non-trivial approximation of all divergent branches in a GPU program. It
29// partially implements the approach described in
30//
31// Divergence Analysis
32// Sampaio, Souza, Collange, Pereira
33// TOPLAS '13
34//
35// The divergence analysis identifies the sources of divergence (e.g., special
36// variables that hold the thread ID), and recursively marks variables that are
37// data or sync dependent on a source of divergence as divergent.
38//
39// While data dependency is a well-known concept, the notion of sync dependency
40// is worth more explanation. Sync dependence characterizes the control flow
41// aspect of the propagation of branch divergence. For example,
42//
43// %cond = icmp slt i32 %tid, 10
44// br i1 %cond, label %then, label %else
45// then:
46// br label %merge
47// else:
48// br label %merge
49// merge:
50// %a = phi i32 [ 0, %then ], [ 1, %else ]
51//
52// Suppose %tid holds the thread ID. Although %a is not data dependent on %tid
53// because %tid is not on its use-def chains, %a is sync dependent on %tid
54// because the branch "br i1 %cond" depends on %tid and affects which value %a
55// is assigned to.
56//
57// The current implementation has the following limitations:
58// 1. intra-procedural. It conservatively considers the arguments of a
59// non-kernel-entry function and the return value of a function call as
60// divergent.
61// 2. memory as black box. It conservatively considers values loaded from
62// generic or local address as divergent. This can be improved by leveraging
63// pointer analysis.
Marcello Maggioniab58c742015-09-21 17:58:14 +000064//
Jingyue Wu5da831c2015-04-10 05:03:50 +000065//===----------------------------------------------------------------------===//
66
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +000067#include "llvm/ADT/PostOrderIterator.h"
68#include "llvm/Analysis/CFG.h"
69#include "llvm/Analysis/DivergenceAnalysis.h"
Nicolai Haehnle35617ed2018-08-30 14:21:36 +000070#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
Jingyue Wu5da831c2015-04-10 05:03:50 +000071#include "llvm/Analysis/Passes.h"
72#include "llvm/Analysis/PostDominators.h"
73#include "llvm/Analysis/TargetTransformInfo.h"
Marcello Maggioniab58c742015-09-21 17:58:14 +000074#include "llvm/IR/Dominators.h"
Jingyue Wu5da831c2015-04-10 05:03:50 +000075#include "llvm/IR/InstIterator.h"
76#include "llvm/IR/Instructions.h"
Jingyue Wu5da831c2015-04-10 05:03:50 +000077#include "llvm/IR/Value.h"
Jingyue Wu5da831c2015-04-10 05:03:50 +000078#include "llvm/Support/Debug.h"
79#include "llvm/Support/raw_ostream.h"
Marcello Maggioniab58c742015-09-21 17:58:14 +000080#include <vector>
Jingyue Wu5da831c2015-04-10 05:03:50 +000081using namespace llvm;
82
Tim Renouff3d82952018-07-13 13:13:30 +000083#define DEBUG_TYPE "divergence"
84
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +000085// transparently use the GPUDivergenceAnalysis
86static cl::opt<bool> UseGPUDA("use-gpu-divergence-analysis", cl::init(false),
87 cl::Hidden,
88 cl::desc("turn the LegacyDivergenceAnalysis into "
89 "a wrapper for GPUDivergenceAnalysis"));
90
Jingyue Wu5da831c2015-04-10 05:03:50 +000091namespace {
92
93class DivergencePropagator {
94public:
Marcello Maggioniab58c742015-09-21 17:58:14 +000095 DivergencePropagator(Function &F, TargetTransformInfo &TTI, DominatorTree &DT,
96 PostDominatorTree &PDT, DenseSet<const Value *> &DV)
Jingyue Wu5da831c2015-04-10 05:03:50 +000097 : F(F), TTI(TTI), DT(DT), PDT(PDT), DV(DV) {}
98 void populateWithSourcesOfDivergence();
99 void propagate();
100
101private:
102 // A helper function that explores data dependents of V.
103 void exploreDataDependency(Value *V);
104 // A helper function that explores sync dependents of TI.
Chandler Carruth98716622018-10-18 00:36:15 +0000105 void exploreSyncDependency(Instruction *TI);
Jingyue Wu5da831c2015-04-10 05:03:50 +0000106 // Computes the influence region from Start to End. This region includes all
Jingyue Wu3f422282015-12-18 21:44:26 +0000107 // basic blocks on any simple path from Start to End.
Jingyue Wu5da831c2015-04-10 05:03:50 +0000108 void computeInfluenceRegion(BasicBlock *Start, BasicBlock *End,
109 DenseSet<BasicBlock *> &InfluenceRegion);
110 // Finds all users of I that are outside the influence region, and add these
111 // users to Worklist.
112 void findUsersOutsideInfluenceRegion(
113 Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion);
114
115 Function &F;
116 TargetTransformInfo &TTI;
117 DominatorTree &DT;
118 PostDominatorTree &PDT;
119 std::vector<Value *> Worklist; // Stack for DFS.
Marcello Maggioniab58c742015-09-21 17:58:14 +0000120 DenseSet<const Value *> &DV; // Stores all divergent values.
Jingyue Wu5da831c2015-04-10 05:03:50 +0000121};
122
123void DivergencePropagator::populateWithSourcesOfDivergence() {
124 Worklist.clear();
125 DV.clear();
Nico Rieck78199512015-08-06 19:10:45 +0000126 for (auto &I : instructions(F)) {
Jingyue Wu5da831c2015-04-10 05:03:50 +0000127 if (TTI.isSourceOfDivergence(&I)) {
128 Worklist.push_back(&I);
129 DV.insert(&I);
130 }
131 }
132 for (auto &Arg : F.args()) {
133 if (TTI.isSourceOfDivergence(&Arg)) {
134 Worklist.push_back(&Arg);
135 DV.insert(&Arg);
136 }
137 }
138}
139
Chandler Carruth98716622018-10-18 00:36:15 +0000140void DivergencePropagator::exploreSyncDependency(Instruction *TI) {
Jingyue Wu5da831c2015-04-10 05:03:50 +0000141 // Propagation rule 1: if branch TI is divergent, all PHINodes in TI's
142 // immediate post dominator are divergent. This rule handles if-then-else
143 // patterns. For example,
144 //
145 // if (tid < 5)
146 // a1 = 1;
147 // else
148 // a2 = 2;
149 // a = phi(a1, a2); // sync dependent on (tid < 5)
150 BasicBlock *ThisBB = TI->getParent();
Matt Arsenault790eb1c2016-04-29 06:17:47 +0000151
152 // Unreachable blocks may not be in the dominator tree.
153 if (!DT.isReachableFromEntry(ThisBB))
154 return;
155
Matt Arsenault1af53a92016-05-09 16:57:08 +0000156 // If the function has no exit blocks or doesn't reach any exit blocks, the
157 // post dominator may be null.
158 DomTreeNode *ThisNode = PDT.getNode(ThisBB);
159 if (!ThisNode)
160 return;
161
162 BasicBlock *IPostDom = ThisNode->getIDom()->getBlock();
Jingyue Wu5da831c2015-04-10 05:03:50 +0000163 if (IPostDom == nullptr)
164 return;
165
166 for (auto I = IPostDom->begin(); isa<PHINode>(I); ++I) {
167 // A PHINode is uniform if it returns the same value no matter which path is
168 // taken.
Nicolai Haehnle13d90f32016-04-14 17:42:47 +0000169 if (!cast<PHINode>(I)->hasConstantOrUndefValue() && DV.insert(&*I).second)
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000170 Worklist.push_back(&*I);
Jingyue Wu5da831c2015-04-10 05:03:50 +0000171 }
172
173 // Propagation rule 2: if a value defined in a loop is used outside, the user
174 // is sync dependent on the condition of the loop exits that dominate the
175 // user. For example,
176 //
177 // int i = 0;
178 // do {
179 // i++;
180 // if (foo(i)) ... // uniform
181 // } while (i < tid);
182 // if (bar(i)) ... // divergent
183 //
184 // A program may contain unstructured loops. Therefore, we cannot leverage
185 // LoopInfo, which only recognizes natural loops.
186 //
187 // The algorithm used here handles both natural and unstructured loops. Given
188 // a branch TI, we first compute its influence region, the union of all simple
189 // paths from TI to its immediate post dominator (IPostDom). Then, we search
190 // for all the values defined in the influence region but used outside. All
191 // these users are sync dependent on TI.
192 DenseSet<BasicBlock *> InfluenceRegion;
193 computeInfluenceRegion(ThisBB, IPostDom, InfluenceRegion);
194 // An insight that can speed up the search process is that all the in-region
195 // values that are used outside must dominate TI. Therefore, instead of
196 // searching every basic blocks in the influence region, we search all the
197 // dominators of TI until it is outside the influence region.
198 BasicBlock *InfluencedBB = ThisBB;
199 while (InfluenceRegion.count(InfluencedBB)) {
200 for (auto &I : *InfluencedBB)
201 findUsersOutsideInfluenceRegion(I, InfluenceRegion);
202 DomTreeNode *IDomNode = DT.getNode(InfluencedBB)->getIDom();
203 if (IDomNode == nullptr)
204 break;
205 InfluencedBB = IDomNode->getBlock();
206 }
207}
208
209void DivergencePropagator::findUsersOutsideInfluenceRegion(
210 Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion) {
211 for (User *U : I.users()) {
212 Instruction *UserInst = cast<Instruction>(U);
213 if (!InfluenceRegion.count(UserInst->getParent())) {
214 if (DV.insert(UserInst).second)
215 Worklist.push_back(UserInst);
216 }
217 }
218}
219
Jingyue Wu3f422282015-12-18 21:44:26 +0000220// A helper function for computeInfluenceRegion that adds successors of "ThisBB"
221// to the influence region.
222static void
223addSuccessorsToInfluenceRegion(BasicBlock *ThisBB, BasicBlock *End,
224 DenseSet<BasicBlock *> &InfluenceRegion,
225 std::vector<BasicBlock *> &InfluenceStack) {
226 for (BasicBlock *Succ : successors(ThisBB)) {
227 if (Succ != End && InfluenceRegion.insert(Succ).second)
228 InfluenceStack.push_back(Succ);
229 }
230}
231
Jingyue Wu5da831c2015-04-10 05:03:50 +0000232void DivergencePropagator::computeInfluenceRegion(
233 BasicBlock *Start, BasicBlock *End,
234 DenseSet<BasicBlock *> &InfluenceRegion) {
235 assert(PDT.properlyDominates(End, Start) &&
236 "End does not properly dominate Start");
Jingyue Wu3f422282015-12-18 21:44:26 +0000237
238 // The influence region starts from the end of "Start" to the beginning of
239 // "End". Therefore, "Start" should not be in the region unless "Start" is in
240 // a loop that doesn't contain "End".
Jingyue Wu5da831c2015-04-10 05:03:50 +0000241 std::vector<BasicBlock *> InfluenceStack;
Jingyue Wu3f422282015-12-18 21:44:26 +0000242 addSuccessorsToInfluenceRegion(Start, End, InfluenceRegion, InfluenceStack);
Jingyue Wu5da831c2015-04-10 05:03:50 +0000243 while (!InfluenceStack.empty()) {
244 BasicBlock *BB = InfluenceStack.back();
245 InfluenceStack.pop_back();
Jingyue Wu3f422282015-12-18 21:44:26 +0000246 addSuccessorsToInfluenceRegion(BB, End, InfluenceRegion, InfluenceStack);
Jingyue Wu5da831c2015-04-10 05:03:50 +0000247 }
248}
249
250void DivergencePropagator::exploreDataDependency(Value *V) {
251 // Follow def-use chains of V.
252 for (User *U : V->users()) {
253 Instruction *UserInst = cast<Instruction>(U);
Alexander Timofeev0f9c84c2017-06-15 19:33:10 +0000254 if (!TTI.isAlwaysUniform(U) && DV.insert(UserInst).second)
Jingyue Wu5da831c2015-04-10 05:03:50 +0000255 Worklist.push_back(UserInst);
256 }
257}
258
259void DivergencePropagator::propagate() {
260 // Traverse the dependency graph using DFS.
261 while (!Worklist.empty()) {
262 Value *V = Worklist.back();
263 Worklist.pop_back();
Chandler Carruth98716622018-10-18 00:36:15 +0000264 if (Instruction *I = dyn_cast<Instruction>(V)) {
Jingyue Wu5da831c2015-04-10 05:03:50 +0000265 // Terminators with less than two successors won't introduce sync
266 // dependency. Ignore them.
Chandler Carruth98716622018-10-18 00:36:15 +0000267 if (I->isTerminator() && I->getNumSuccessors() > 1)
268 exploreSyncDependency(I);
Jingyue Wu5da831c2015-04-10 05:03:50 +0000269 }
270 exploreDataDependency(V);
271 }
272}
273
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000274} // namespace
Jingyue Wu5da831c2015-04-10 05:03:50 +0000275
Marcello Maggioniab58c742015-09-21 17:58:14 +0000276// Register this pass.
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000277char LegacyDivergenceAnalysis::ID = 0;
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000278INITIALIZE_PASS_BEGIN(LegacyDivergenceAnalysis, "divergence",
279 "Legacy Divergence Analysis", false, true)
Marcello Maggioniab58c742015-09-21 17:58:14 +0000280INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Hongbin Zheng3f978402016-02-25 17:54:07 +0000281INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000282INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
283INITIALIZE_PASS_END(LegacyDivergenceAnalysis, "divergence",
284 "Legacy Divergence Analysis", false, true)
Marcello Maggioniab58c742015-09-21 17:58:14 +0000285
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000286FunctionPass *llvm::createLegacyDivergenceAnalysisPass() {
287 return new LegacyDivergenceAnalysis();
Jingyue Wu5da831c2015-04-10 05:03:50 +0000288}
289
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000290void LegacyDivergenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
Marcello Maggioniab58c742015-09-21 17:58:14 +0000291 AU.addRequired<DominatorTreeWrapperPass>();
Hongbin Zheng3f978402016-02-25 17:54:07 +0000292 AU.addRequired<PostDominatorTreeWrapperPass>();
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000293 if (UseGPUDA)
294 AU.addRequired<LoopInfoWrapperPass>();
Marcello Maggioniab58c742015-09-21 17:58:14 +0000295 AU.setPreservesAll();
296}
297
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000298bool LegacyDivergenceAnalysis::shouldUseGPUDivergenceAnalysis(
299 const Function &F) const {
300 if (!UseGPUDA)
301 return false;
302
303 // GPUDivergenceAnalysis requires a reducible CFG.
304 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
305 using RPOTraversal = ReversePostOrderTraversal<const Function *>;
306 RPOTraversal FuncRPOT(&F);
307 return !containsIrreducibleCFG<const BasicBlock *, const RPOTraversal,
308 const LoopInfo>(FuncRPOT, LI);
309}
310
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000311bool LegacyDivergenceAnalysis::runOnFunction(Function &F) {
Jingyue Wu5da831c2015-04-10 05:03:50 +0000312 auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
313 if (TTIWP == nullptr)
314 return false;
315
316 TargetTransformInfo &TTI = TTIWP->getTTI(F);
317 // Fast path: if the target does not have branch divergence, we do not mark
318 // any branch as divergent.
319 if (!TTI.hasBranchDivergence())
320 return false;
321
322 DivergentValues.clear();
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000323 gpuDA = nullptr;
324
325 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Hongbin Zheng3f978402016-02-25 17:54:07 +0000326 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000327
328 if (shouldUseGPUDivergenceAnalysis(F)) {
329 // run the new GPU divergence analysis
330 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
331 gpuDA = llvm::make_unique<GPUDivergenceAnalysis>(F, DT, PDT, LI, TTI);
332
333 } else {
334 // run LLVM's existing DivergenceAnalysis
335 DivergencePropagator DP(F, TTI, DT, PDT, DivergentValues);
336 DP.populateWithSourcesOfDivergence();
337 DP.propagate();
338 }
339
340 LLVM_DEBUG(dbgs() << "\nAfter divergence analysis on " << F.getName()
341 << ":\n";
342 print(dbgs(), F.getParent()));
343
Jingyue Wu5da831c2015-04-10 05:03:50 +0000344 return false;
345}
346
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000347bool LegacyDivergenceAnalysis::isDivergent(const Value *V) const {
348 if (gpuDA) {
349 return gpuDA->isDivergent(*V);
350 }
351 return DivergentValues.count(V);
352}
353
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000354void LegacyDivergenceAnalysis::print(raw_ostream &OS, const Module *) const {
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000355 if ((!gpuDA || !gpuDA->hasDivergence()) && DivergentValues.empty())
Jingyue Wu5da831c2015-04-10 05:03:50 +0000356 return;
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000357
Nicolai Haehnle413f86912018-11-30 23:07:49 +0000358 const Function *F = nullptr;
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000359 if (!DivergentValues.empty()) {
360 const Value *FirstDivergentValue = *DivergentValues.begin();
361 if (const Argument *Arg = dyn_cast<Argument>(FirstDivergentValue)) {
362 F = Arg->getParent();
363 } else if (const Instruction *I =
364 dyn_cast<Instruction>(FirstDivergentValue)) {
365 F = I->getParent()->getParent();
366 } else {
367 llvm_unreachable("Only arguments and instructions can be divergent");
368 }
369 } else if (gpuDA) {
370 F = &gpuDA->getFunction();
Jingyue Wu5da831c2015-04-10 05:03:50 +0000371 }
Nicolai Haehnle413f86912018-11-30 23:07:49 +0000372 if (!F)
373 return;
Jingyue Wu5da831c2015-04-10 05:03:50 +0000374
375 // Dumps all divergent values in F, arguments and then instructions.
376 for (auto &Arg : F->args()) {
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000377 OS << (isDivergent(&Arg) ? "DIVERGENT: " : " ");
Tim Renouff3d82952018-07-13 13:13:30 +0000378 OS << Arg << "\n";
Jingyue Wu5da831c2015-04-10 05:03:50 +0000379 }
Nico Rieck78199512015-08-06 19:10:45 +0000380 // Iterate instructions using instructions() to ensure a deterministic order.
Tim Renouff3d82952018-07-13 13:13:30 +0000381 for (auto BI = F->begin(), BE = F->end(); BI != BE; ++BI) {
382 auto &BB = *BI;
383 OS << "\n " << BB.getName() << ":\n";
384 for (auto &I : BB.instructionsWithoutDebug()) {
Nicolai Haehnle56d0ed22018-11-30 22:55:20 +0000385 OS << (isDivergent(&I) ? "DIVERGENT: " : " ");
Tim Renouff3d82952018-07-13 13:13:30 +0000386 OS << I << "\n";
387 }
Jingyue Wu5da831c2015-04-10 05:03:50 +0000388 }
Tim Renouff3d82952018-07-13 13:13:30 +0000389 OS << "\n";
Jingyue Wu5da831c2015-04-10 05:03:50 +0000390}