blob: b30539f3b31ecb3823dadea81be71f18600f6d60 [file] [log] [blame]
Marcello Maggioniab58c742015-09-21 17:58:14 +00001//===- DivergenceAnalysis.cpp --------- Divergence Analysis Implementation -==//
Jingyue Wu5da831c2015-04-10 05:03:50 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
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
Marcello Maggioniab58c742015-09-21 17:58:14 +000067#include "llvm/Analysis/DivergenceAnalysis.h"
Jingyue Wu5da831c2015-04-10 05:03:50 +000068#include "llvm/Analysis/Passes.h"
69#include "llvm/Analysis/PostDominators.h"
70#include "llvm/Analysis/TargetTransformInfo.h"
Marcello Maggioniab58c742015-09-21 17:58:14 +000071#include "llvm/IR/Dominators.h"
Jingyue Wu5da831c2015-04-10 05:03:50 +000072#include "llvm/IR/InstIterator.h"
73#include "llvm/IR/Instructions.h"
74#include "llvm/IR/IntrinsicInst.h"
75#include "llvm/IR/Value.h"
Jingyue Wu5da831c2015-04-10 05:03:50 +000076#include "llvm/Support/Debug.h"
77#include "llvm/Support/raw_ostream.h"
Marcello Maggioniab58c742015-09-21 17:58:14 +000078#include <vector>
Jingyue Wu5da831c2015-04-10 05:03:50 +000079using namespace llvm;
80
Jingyue Wu5da831c2015-04-10 05:03:50 +000081namespace {
82
83class DivergencePropagator {
84public:
Marcello Maggioniab58c742015-09-21 17:58:14 +000085 DivergencePropagator(Function &F, TargetTransformInfo &TTI, DominatorTree &DT,
86 PostDominatorTree &PDT, DenseSet<const Value *> &DV)
Jingyue Wu5da831c2015-04-10 05:03:50 +000087 : F(F), TTI(TTI), DT(DT), PDT(PDT), DV(DV) {}
88 void populateWithSourcesOfDivergence();
89 void propagate();
90
91private:
92 // A helper function that explores data dependents of V.
93 void exploreDataDependency(Value *V);
94 // A helper function that explores sync dependents of TI.
95 void exploreSyncDependency(TerminatorInst *TI);
96 // Computes the influence region from Start to End. This region includes all
Jingyue Wu3f422282015-12-18 21:44:26 +000097 // basic blocks on any simple path from Start to End.
Jingyue Wu5da831c2015-04-10 05:03:50 +000098 void computeInfluenceRegion(BasicBlock *Start, BasicBlock *End,
99 DenseSet<BasicBlock *> &InfluenceRegion);
100 // Finds all users of I that are outside the influence region, and add these
101 // users to Worklist.
102 void findUsersOutsideInfluenceRegion(
103 Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion);
104
105 Function &F;
106 TargetTransformInfo &TTI;
107 DominatorTree &DT;
108 PostDominatorTree &PDT;
109 std::vector<Value *> Worklist; // Stack for DFS.
Marcello Maggioniab58c742015-09-21 17:58:14 +0000110 DenseSet<const Value *> &DV; // Stores all divergent values.
Jingyue Wu5da831c2015-04-10 05:03:50 +0000111};
112
113void DivergencePropagator::populateWithSourcesOfDivergence() {
114 Worklist.clear();
115 DV.clear();
Nico Rieck78199512015-08-06 19:10:45 +0000116 for (auto &I : instructions(F)) {
Jingyue Wu5da831c2015-04-10 05:03:50 +0000117 if (TTI.isSourceOfDivergence(&I)) {
118 Worklist.push_back(&I);
119 DV.insert(&I);
120 }
121 }
122 for (auto &Arg : F.args()) {
123 if (TTI.isSourceOfDivergence(&Arg)) {
124 Worklist.push_back(&Arg);
125 DV.insert(&Arg);
126 }
127 }
128}
129
130void DivergencePropagator::exploreSyncDependency(TerminatorInst *TI) {
131 // Propagation rule 1: if branch TI is divergent, all PHINodes in TI's
132 // immediate post dominator are divergent. This rule handles if-then-else
133 // patterns. For example,
134 //
135 // if (tid < 5)
136 // a1 = 1;
137 // else
138 // a2 = 2;
139 // a = phi(a1, a2); // sync dependent on (tid < 5)
140 BasicBlock *ThisBB = TI->getParent();
141 BasicBlock *IPostDom = PDT.getNode(ThisBB)->getIDom()->getBlock();
142 if (IPostDom == nullptr)
143 return;
144
145 for (auto I = IPostDom->begin(); isa<PHINode>(I); ++I) {
146 // A PHINode is uniform if it returns the same value no matter which path is
147 // taken.
Nicolai Haehnle13d90f32016-04-14 17:42:47 +0000148 if (!cast<PHINode>(I)->hasConstantOrUndefValue() && DV.insert(&*I).second)
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000149 Worklist.push_back(&*I);
Jingyue Wu5da831c2015-04-10 05:03:50 +0000150 }
151
152 // Propagation rule 2: if a value defined in a loop is used outside, the user
153 // is sync dependent on the condition of the loop exits that dominate the
154 // user. For example,
155 //
156 // int i = 0;
157 // do {
158 // i++;
159 // if (foo(i)) ... // uniform
160 // } while (i < tid);
161 // if (bar(i)) ... // divergent
162 //
163 // A program may contain unstructured loops. Therefore, we cannot leverage
164 // LoopInfo, which only recognizes natural loops.
165 //
166 // The algorithm used here handles both natural and unstructured loops. Given
167 // a branch TI, we first compute its influence region, the union of all simple
168 // paths from TI to its immediate post dominator (IPostDom). Then, we search
169 // for all the values defined in the influence region but used outside. All
170 // these users are sync dependent on TI.
171 DenseSet<BasicBlock *> InfluenceRegion;
172 computeInfluenceRegion(ThisBB, IPostDom, InfluenceRegion);
173 // An insight that can speed up the search process is that all the in-region
174 // values that are used outside must dominate TI. Therefore, instead of
175 // searching every basic blocks in the influence region, we search all the
176 // dominators of TI until it is outside the influence region.
177 BasicBlock *InfluencedBB = ThisBB;
178 while (InfluenceRegion.count(InfluencedBB)) {
179 for (auto &I : *InfluencedBB)
180 findUsersOutsideInfluenceRegion(I, InfluenceRegion);
181 DomTreeNode *IDomNode = DT.getNode(InfluencedBB)->getIDom();
182 if (IDomNode == nullptr)
183 break;
184 InfluencedBB = IDomNode->getBlock();
185 }
186}
187
188void DivergencePropagator::findUsersOutsideInfluenceRegion(
189 Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion) {
190 for (User *U : I.users()) {
191 Instruction *UserInst = cast<Instruction>(U);
192 if (!InfluenceRegion.count(UserInst->getParent())) {
193 if (DV.insert(UserInst).second)
194 Worklist.push_back(UserInst);
195 }
196 }
197}
198
Jingyue Wu3f422282015-12-18 21:44:26 +0000199// A helper function for computeInfluenceRegion that adds successors of "ThisBB"
200// to the influence region.
201static void
202addSuccessorsToInfluenceRegion(BasicBlock *ThisBB, BasicBlock *End,
203 DenseSet<BasicBlock *> &InfluenceRegion,
204 std::vector<BasicBlock *> &InfluenceStack) {
205 for (BasicBlock *Succ : successors(ThisBB)) {
206 if (Succ != End && InfluenceRegion.insert(Succ).second)
207 InfluenceStack.push_back(Succ);
208 }
209}
210
Jingyue Wu5da831c2015-04-10 05:03:50 +0000211void DivergencePropagator::computeInfluenceRegion(
212 BasicBlock *Start, BasicBlock *End,
213 DenseSet<BasicBlock *> &InfluenceRegion) {
214 assert(PDT.properlyDominates(End, Start) &&
215 "End does not properly dominate Start");
Jingyue Wu3f422282015-12-18 21:44:26 +0000216
217 // The influence region starts from the end of "Start" to the beginning of
218 // "End". Therefore, "Start" should not be in the region unless "Start" is in
219 // a loop that doesn't contain "End".
Jingyue Wu5da831c2015-04-10 05:03:50 +0000220 std::vector<BasicBlock *> InfluenceStack;
Jingyue Wu3f422282015-12-18 21:44:26 +0000221 addSuccessorsToInfluenceRegion(Start, End, InfluenceRegion, InfluenceStack);
Jingyue Wu5da831c2015-04-10 05:03:50 +0000222 while (!InfluenceStack.empty()) {
223 BasicBlock *BB = InfluenceStack.back();
224 InfluenceStack.pop_back();
Jingyue Wu3f422282015-12-18 21:44:26 +0000225 addSuccessorsToInfluenceRegion(BB, End, InfluenceRegion, InfluenceStack);
Jingyue Wu5da831c2015-04-10 05:03:50 +0000226 }
227}
228
229void DivergencePropagator::exploreDataDependency(Value *V) {
230 // Follow def-use chains of V.
231 for (User *U : V->users()) {
232 Instruction *UserInst = cast<Instruction>(U);
233 if (DV.insert(UserInst).second)
234 Worklist.push_back(UserInst);
235 }
236}
237
238void DivergencePropagator::propagate() {
239 // Traverse the dependency graph using DFS.
240 while (!Worklist.empty()) {
241 Value *V = Worklist.back();
242 Worklist.pop_back();
243 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(V)) {
244 // Terminators with less than two successors won't introduce sync
245 // dependency. Ignore them.
246 if (TI->getNumSuccessors() > 1)
247 exploreSyncDependency(TI);
248 }
249 exploreDataDependency(V);
250 }
251}
252
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000253} /// end namespace anonymous
Jingyue Wu5da831c2015-04-10 05:03:50 +0000254
Marcello Maggioniab58c742015-09-21 17:58:14 +0000255// Register this pass.
256char DivergenceAnalysis::ID = 0;
257INITIALIZE_PASS_BEGIN(DivergenceAnalysis, "divergence", "Divergence Analysis",
258 false, true)
259INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Hongbin Zheng3f978402016-02-25 17:54:07 +0000260INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Marcello Maggioniab58c742015-09-21 17:58:14 +0000261INITIALIZE_PASS_END(DivergenceAnalysis, "divergence", "Divergence Analysis",
262 false, true)
263
Jingyue Wu5da831c2015-04-10 05:03:50 +0000264FunctionPass *llvm::createDivergenceAnalysisPass() {
265 return new DivergenceAnalysis();
266}
267
Marcello Maggioniab58c742015-09-21 17:58:14 +0000268void DivergenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
269 AU.addRequired<DominatorTreeWrapperPass>();
Hongbin Zheng3f978402016-02-25 17:54:07 +0000270 AU.addRequired<PostDominatorTreeWrapperPass>();
Marcello Maggioniab58c742015-09-21 17:58:14 +0000271 AU.setPreservesAll();
272}
273
Jingyue Wu5da831c2015-04-10 05:03:50 +0000274bool DivergenceAnalysis::runOnFunction(Function &F) {
275 auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
276 if (TTIWP == nullptr)
277 return false;
278
279 TargetTransformInfo &TTI = TTIWP->getTTI(F);
280 // Fast path: if the target does not have branch divergence, we do not mark
281 // any branch as divergent.
282 if (!TTI.hasBranchDivergence())
283 return false;
284
285 DivergentValues.clear();
Hongbin Zheng3f978402016-02-25 17:54:07 +0000286 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
Jingyue Wu5da831c2015-04-10 05:03:50 +0000287 DivergencePropagator DP(F, TTI,
288 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
Hongbin Zheng3f978402016-02-25 17:54:07 +0000289 PDT, DivergentValues);
Jingyue Wu5da831c2015-04-10 05:03:50 +0000290 DP.populateWithSourcesOfDivergence();
291 DP.propagate();
292 return false;
293}
294
295void DivergenceAnalysis::print(raw_ostream &OS, const Module *) const {
296 if (DivergentValues.empty())
297 return;
298 const Value *FirstDivergentValue = *DivergentValues.begin();
299 const Function *F;
300 if (const Argument *Arg = dyn_cast<Argument>(FirstDivergentValue)) {
301 F = Arg->getParent();
302 } else if (const Instruction *I =
303 dyn_cast<Instruction>(FirstDivergentValue)) {
304 F = I->getParent()->getParent();
305 } else {
306 llvm_unreachable("Only arguments and instructions can be divergent");
307 }
308
309 // Dumps all divergent values in F, arguments and then instructions.
310 for (auto &Arg : F->args()) {
311 if (DivergentValues.count(&Arg))
312 OS << "DIVERGENT: " << Arg << "\n";
313 }
Nico Rieck78199512015-08-06 19:10:45 +0000314 // Iterate instructions using instructions() to ensure a deterministic order.
315 for (auto &I : instructions(F)) {
Jingyue Wu5da831c2015-04-10 05:03:50 +0000316 if (DivergentValues.count(&I))
317 OS << "DIVERGENT:" << I << "\n";
318 }
319}