DivergenceAnalysis.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. //===- DivergenceAnalysis.cpp --------- Divergence Analysis Implementation -==//
  2. //
  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. //
  10. // 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
  12. // 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.
  64. //
  65. //===----------------------------------------------------------------------===//
  66. #include "llvm/Analysis/DivergenceAnalysis.h"
  67. #include "llvm/Analysis/Passes.h"
  68. #include "llvm/Analysis/PostDominators.h"
  69. #include "llvm/Analysis/TargetTransformInfo.h"
  70. #include "llvm/IR/Dominators.h"
  71. #include "llvm/IR/InstIterator.h"
  72. #include "llvm/IR/Instructions.h"
  73. #include "llvm/IR/IntrinsicInst.h"
  74. #include "llvm/IR/Value.h"
  75. #include "llvm/Support/CommandLine.h"
  76. #include "llvm/Support/Debug.h"
  77. #include "llvm/Support/raw_ostream.h"
  78. #include "llvm/Transforms/Scalar.h"
  79. #include <vector>
  80. using namespace llvm;
  81. namespace {
  82. class DivergencePropagator {
  83. public:
  84. DivergencePropagator(Function &F, TargetTransformInfo &TTI, DominatorTree &DT,
  85. PostDominatorTree &PDT, DenseSet<const Value *> &DV)
  86. : F(F), TTI(TTI), DT(DT), PDT(PDT), DV(DV) {}
  87. void populateWithSourcesOfDivergence();
  88. void propagate();
  89. private:
  90. // A helper function that explores data dependents of V.
  91. void exploreDataDependency(Value *V);
  92. // A helper function that explores sync dependents of TI.
  93. void exploreSyncDependency(TerminatorInst *TI);
  94. // Computes the influence region from Start to End. This region includes all
  95. // basic blocks on any simple path from Start to End.
  96. void computeInfluenceRegion(BasicBlock *Start, BasicBlock *End,
  97. DenseSet<BasicBlock *> &InfluenceRegion);
  98. // Finds all users of I that are outside the influence region, and add these
  99. // users to Worklist.
  100. void findUsersOutsideInfluenceRegion(
  101. Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion);
  102. Function &F;
  103. TargetTransformInfo &TTI;
  104. DominatorTree &DT;
  105. PostDominatorTree &PDT;
  106. std::vector<Value *> Worklist; // Stack for DFS.
  107. DenseSet<const Value *> &DV; // Stores all divergent values.
  108. };
  109. void DivergencePropagator::populateWithSourcesOfDivergence() {
  110. Worklist.clear();
  111. DV.clear();
  112. for (auto &I : inst_range(F)) {
  113. if (TTI.isSourceOfDivergence(&I)) {
  114. Worklist.push_back(&I);
  115. DV.insert(&I);
  116. }
  117. }
  118. for (auto &Arg : F.args()) {
  119. if (TTI.isSourceOfDivergence(&Arg)) {
  120. Worklist.push_back(&Arg);
  121. DV.insert(&Arg);
  122. }
  123. }
  124. }
  125. void DivergencePropagator::exploreSyncDependency(TerminatorInst *TI) {
  126. // Propagation rule 1: if branch TI is divergent, all PHINodes in TI's
  127. // immediate post dominator are divergent. This rule handles if-then-else
  128. // patterns. For example,
  129. //
  130. // if (tid < 5)
  131. // a1 = 1;
  132. // else
  133. // a2 = 2;
  134. // a = phi(a1, a2); // sync dependent on (tid < 5)
  135. BasicBlock *ThisBB = TI->getParent();
  136. BasicBlock *IPostDom = PDT.getNode(ThisBB)->getIDom()->getBlock();
  137. if (IPostDom == nullptr)
  138. return;
  139. for (auto I = IPostDom->begin(); isa<PHINode>(I); ++I) {
  140. // A PHINode is uniform if it returns the same value no matter which path is
  141. // taken.
  142. if (!cast<PHINode>(I)->hasConstantValue() && DV.insert(&*I).second)
  143. Worklist.push_back(&*I);
  144. }
  145. // Propagation rule 2: if a value defined in a loop is used outside, the user
  146. // is sync dependent on the condition of the loop exits that dominate the
  147. // user. For example,
  148. //
  149. // int i = 0;
  150. // do {
  151. // i++;
  152. // if (foo(i)) ... // uniform
  153. // } while (i < tid);
  154. // if (bar(i)) ... // divergent
  155. //
  156. // A program may contain unstructured loops. Therefore, we cannot leverage
  157. // LoopInfo, which only recognizes natural loops.
  158. //
  159. // The algorithm used here handles both natural and unstructured loops. Given
  160. // a branch TI, we first compute its influence region, the union of all simple
  161. // paths from TI to its immediate post dominator (IPostDom). Then, we search
  162. // for all the values defined in the influence region but used outside. All
  163. // these users are sync dependent on TI.
  164. DenseSet<BasicBlock *> InfluenceRegion;
  165. computeInfluenceRegion(ThisBB, IPostDom, InfluenceRegion);
  166. // An insight that can speed up the search process is that all the in-region
  167. // values that are used outside must dominate TI. Therefore, instead of
  168. // searching every basic blocks in the influence region, we search all the
  169. // dominators of TI until it is outside the influence region.
  170. BasicBlock *InfluencedBB = ThisBB;
  171. while (InfluenceRegion.count(InfluencedBB)) {
  172. for (auto &I : *InfluencedBB)
  173. findUsersOutsideInfluenceRegion(I, InfluenceRegion);
  174. DomTreeNode *IDomNode = DT.getNode(InfluencedBB)->getIDom();
  175. if (IDomNode == nullptr)
  176. break;
  177. InfluencedBB = IDomNode->getBlock();
  178. }
  179. }
  180. void DivergencePropagator::findUsersOutsideInfluenceRegion(
  181. Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion) {
  182. for (User *U : I.users()) {
  183. Instruction *UserInst = cast<Instruction>(U);
  184. if (!InfluenceRegion.count(UserInst->getParent())) {
  185. if (DV.insert(UserInst).second)
  186. Worklist.push_back(UserInst);
  187. }
  188. }
  189. }
  190. // A helper function for computeInfluenceRegion that adds successors of "ThisBB"
  191. // to the influence region.
  192. static void
  193. addSuccessorsToInfluenceRegion(BasicBlock *ThisBB, BasicBlock *End,
  194. DenseSet<BasicBlock *> &InfluenceRegion,
  195. std::vector<BasicBlock *> &InfluenceStack) {
  196. for (BasicBlock *Succ : successors(ThisBB)) {
  197. if (Succ != End && InfluenceRegion.insert(Succ).second)
  198. InfluenceStack.push_back(Succ);
  199. }
  200. }
  201. void DivergencePropagator::computeInfluenceRegion(
  202. BasicBlock *Start, BasicBlock *End,
  203. DenseSet<BasicBlock *> &InfluenceRegion) {
  204. assert(PDT.properlyDominates(End, Start) &&
  205. "End does not properly dominate Start");
  206. // The influence region starts from the end of "Start" to the beginning of
  207. // "End". Therefore, "Start" should not be in the region unless "Start" is in
  208. // a loop that doesn't contain "End".
  209. std::vector<BasicBlock *> InfluenceStack;
  210. addSuccessorsToInfluenceRegion(Start, End, InfluenceRegion, InfluenceStack);
  211. while (!InfluenceStack.empty()) {
  212. BasicBlock *BB = InfluenceStack.back();
  213. InfluenceStack.pop_back();
  214. addSuccessorsToInfluenceRegion(BB, End, InfluenceRegion, InfluenceStack);
  215. }
  216. }
  217. void DivergencePropagator::exploreDataDependency(Value *V) {
  218. // Follow def-use chains of V.
  219. for (User *U : V->users()) {
  220. Instruction *UserInst = cast<Instruction>(U);
  221. if (DV.insert(UserInst).second)
  222. Worklist.push_back(UserInst);
  223. }
  224. }
  225. void DivergencePropagator::propagate() {
  226. // Traverse the dependency graph using DFS.
  227. while (!Worklist.empty()) {
  228. Value *V = Worklist.back();
  229. Worklist.pop_back();
  230. if (TerminatorInst *TI = dyn_cast<TerminatorInst>(V)) {
  231. // Terminators with less than two successors won't introduce sync
  232. // dependency. Ignore them.
  233. if (TI->getNumSuccessors() > 1)
  234. exploreSyncDependency(TI);
  235. }
  236. exploreDataDependency(V);
  237. }
  238. }
  239. } /// end namespace anonymous
  240. // Register this pass.
  241. char DivergenceAnalysis::ID = 0;
  242. INITIALIZE_PASS_BEGIN(DivergenceAnalysis, "divergence", "Divergence Analysis",
  243. false, true)
  244. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  245. INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
  246. INITIALIZE_PASS_END(DivergenceAnalysis, "divergence", "Divergence Analysis",
  247. false, true)
  248. FunctionPass *llvm::createDivergenceAnalysisPass() {
  249. return new DivergenceAnalysis();
  250. }
  251. void DivergenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  252. AU.addRequired<DominatorTreeWrapperPass>();
  253. AU.addRequired<PostDominatorTree>();
  254. AU.setPreservesAll();
  255. }
  256. bool DivergenceAnalysis::runOnFunction(Function &F) {
  257. auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
  258. if (TTIWP == nullptr)
  259. return false;
  260. TargetTransformInfo &TTI = TTIWP->getTTI(F);
  261. // Fast path: if the target does not have branch divergence, we do not mark
  262. // any branch as divergent.
  263. if (!TTI.hasBranchDivergence())
  264. return false;
  265. DivergentValues.clear();
  266. DivergencePropagator DP(F, TTI,
  267. getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
  268. getAnalysis<PostDominatorTree>(), DivergentValues);
  269. DP.populateWithSourcesOfDivergence();
  270. DP.propagate();
  271. return false;
  272. }
  273. void DivergenceAnalysis::print(raw_ostream &OS, const Module *) const {
  274. if (DivergentValues.empty())
  275. return;
  276. const Value *FirstDivergentValue = *DivergentValues.begin();
  277. const Function *F;
  278. if (const Argument *Arg = dyn_cast<Argument>(FirstDivergentValue)) {
  279. F = Arg->getParent();
  280. } else if (const Instruction *I =
  281. dyn_cast<Instruction>(FirstDivergentValue)) {
  282. F = I->getParent()->getParent();
  283. } else {
  284. llvm_unreachable("Only arguments and instructions can be divergent");
  285. }
  286. // Dumps all divergent values in F, arguments and then instructions.
  287. for (auto &Arg : F->args()) {
  288. if (DivergentValues.count(&Arg))
  289. OS << "DIVERGENT: " << Arg << "\n";
  290. }
  291. // Iterate instructions using inst_range to ensure a deterministic order.
  292. for (auto &I : inst_range(F)) {
  293. if (DivergentValues.count(&I))
  294. OS << "DIVERGENT:" << I << "\n";
  295. }
  296. }