divergence_analysis.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // Copyright (c) 2021 Google LLC.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "source/lint/divergence_analysis.h"
  15. #include "source/opt/basic_block.h"
  16. #include "source/opt/control_dependence.h"
  17. #include "source/opt/dataflow.h"
  18. #include "source/opt/function.h"
  19. #include "source/opt/instruction.h"
  20. #include "spirv/unified1/spirv.h"
  21. namespace spvtools {
  22. namespace lint {
  23. void DivergenceAnalysis::EnqueueSuccessors(opt::Instruction* inst) {
  24. // Enqueue control dependents of block, if applicable.
  25. // There are two ways for a dependence source to be updated:
  26. // 1. control -> control: source block is marked divergent.
  27. // 2. data -> control: branch condition is marked divergent.
  28. uint32_t block_id;
  29. if (inst->IsBlockTerminator()) {
  30. block_id = context().get_instr_block(inst)->id();
  31. } else if (inst->opcode() == SpvOpLabel) {
  32. block_id = inst->result_id();
  33. opt::BasicBlock* bb = context().cfg()->block(block_id);
  34. // Only enqueue phi instructions, as other uses don't affect divergence.
  35. bb->ForEachPhiInst([this](opt::Instruction* phi) { Enqueue(phi); });
  36. } else {
  37. opt::ForwardDataFlowAnalysis::EnqueueUsers(inst);
  38. return;
  39. }
  40. if (!cd_.HasBlock(block_id)) {
  41. return;
  42. }
  43. for (const spvtools::opt::ControlDependence& dep :
  44. cd_.GetDependenceTargets(block_id)) {
  45. opt::Instruction* target_inst =
  46. context().cfg()->block(dep.target_bb_id())->GetLabelInst();
  47. Enqueue(target_inst);
  48. }
  49. }
  50. opt::DataFlowAnalysis::VisitResult DivergenceAnalysis::Visit(
  51. opt::Instruction* inst) {
  52. if (inst->opcode() == SpvOpLabel) {
  53. return VisitBlock(inst->result_id());
  54. } else {
  55. return VisitInstruction(inst);
  56. }
  57. }
  58. opt::DataFlowAnalysis::VisitResult DivergenceAnalysis::VisitBlock(uint32_t id) {
  59. if (!cd_.HasBlock(id)) {
  60. return opt::DataFlowAnalysis::VisitResult::kResultFixed;
  61. }
  62. DivergenceLevel& cur_level = divergence_[id];
  63. if (cur_level == DivergenceLevel::kDivergent) {
  64. return opt::DataFlowAnalysis::VisitResult::kResultFixed;
  65. }
  66. DivergenceLevel orig = cur_level;
  67. for (const spvtools::opt::ControlDependence& dep :
  68. cd_.GetDependenceSources(id)) {
  69. if (divergence_[dep.source_bb_id()] > cur_level) {
  70. cur_level = divergence_[dep.source_bb_id()];
  71. divergence_source_[id] = dep.source_bb_id();
  72. } else if (dep.source_bb_id() != 0) {
  73. uint32_t condition_id = dep.GetConditionID(*context().cfg());
  74. DivergenceLevel dep_level = divergence_[condition_id];
  75. // Check if we are along the chain of unconditional branches starting from
  76. // the branch target.
  77. if (follow_unconditional_branches_[dep.branch_target_bb_id()] !=
  78. follow_unconditional_branches_[dep.target_bb_id()]) {
  79. // We must have reconverged in order to reach this block.
  80. // Promote partially uniform to divergent.
  81. if (dep_level == DivergenceLevel::kPartiallyUniform) {
  82. dep_level = DivergenceLevel::kDivergent;
  83. }
  84. }
  85. if (dep_level > cur_level) {
  86. cur_level = dep_level;
  87. divergence_source_[id] = condition_id;
  88. divergence_dependence_source_[id] = dep.source_bb_id();
  89. }
  90. }
  91. }
  92. return cur_level > orig ? VisitResult::kResultChanged
  93. : VisitResult::kResultFixed;
  94. }
  95. opt::DataFlowAnalysis::VisitResult DivergenceAnalysis::VisitInstruction(
  96. opt::Instruction* inst) {
  97. if (inst->IsBlockTerminator()) {
  98. // This is called only when the condition has changed, so return changed.
  99. return VisitResult::kResultChanged;
  100. }
  101. if (!inst->HasResultId()) {
  102. return VisitResult::kResultFixed;
  103. }
  104. uint32_t id = inst->result_id();
  105. DivergenceLevel& cur_level = divergence_[id];
  106. if (cur_level == DivergenceLevel::kDivergent) {
  107. return opt::DataFlowAnalysis::VisitResult::kResultFixed;
  108. }
  109. DivergenceLevel orig = cur_level;
  110. cur_level = ComputeInstructionDivergence(inst);
  111. return cur_level > orig ? VisitResult::kResultChanged
  112. : VisitResult::kResultFixed;
  113. }
  114. DivergenceAnalysis::DivergenceLevel
  115. DivergenceAnalysis::ComputeInstructionDivergence(opt::Instruction* inst) {
  116. // TODO(kuhar): Check to see if inst is decorated with Uniform or UniformId
  117. // and use that to short circuit other checks. Uniform is for subgroups which
  118. // would satisfy derivative groups too. UniformId takes a scope, so if it is
  119. // subgroup or greater it could satisfy derivative group and
  120. // Device/QueueFamily could satisfy fully uniform.
  121. uint32_t id = inst->result_id();
  122. // Handle divergence roots.
  123. if (inst->opcode() == SpvOpFunctionParameter) {
  124. divergence_source_[id] = 0;
  125. return divergence_[id] = DivergenceLevel::kDivergent;
  126. } else if (inst->IsLoad()) {
  127. spvtools::opt::Instruction* var = inst->GetBaseAddress();
  128. if (var->opcode() != SpvOpVariable) {
  129. // Assume divergent.
  130. divergence_source_[id] = 0;
  131. return DivergenceLevel::kDivergent;
  132. }
  133. DivergenceLevel ret = ComputeVariableDivergence(var);
  134. if (ret > DivergenceLevel::kUniform) {
  135. divergence_source_[inst->result_id()] = 0;
  136. }
  137. return divergence_[id] = ret;
  138. }
  139. // Get the maximum divergence of the operands.
  140. DivergenceLevel ret = DivergenceLevel::kUniform;
  141. inst->ForEachInId([this, inst, &ret](const uint32_t* op) {
  142. if (!op) return;
  143. if (divergence_[*op] > ret) {
  144. divergence_source_[inst->result_id()] = *op;
  145. ret = divergence_[*op];
  146. }
  147. });
  148. divergence_[inst->result_id()] = ret;
  149. return ret;
  150. }
  151. DivergenceAnalysis::DivergenceLevel
  152. DivergenceAnalysis::ComputeVariableDivergence(opt::Instruction* var) {
  153. uint32_t type_id = var->type_id();
  154. spvtools::opt::analysis::Pointer* type =
  155. context().get_type_mgr()->GetType(type_id)->AsPointer();
  156. assert(type != nullptr);
  157. uint32_t def_id = var->result_id();
  158. DivergenceLevel ret;
  159. switch (type->storage_class()) {
  160. case SpvStorageClassFunction:
  161. case SpvStorageClassGeneric:
  162. case SpvStorageClassAtomicCounter:
  163. case SpvStorageClassStorageBuffer:
  164. case SpvStorageClassPhysicalStorageBuffer:
  165. case SpvStorageClassOutput:
  166. case SpvStorageClassWorkgroup:
  167. case SpvStorageClassImage: // Image atomics probably aren't uniform.
  168. case SpvStorageClassPrivate:
  169. ret = DivergenceLevel::kDivergent;
  170. break;
  171. case SpvStorageClassInput:
  172. ret = DivergenceLevel::kDivergent;
  173. // If this variable has a Flat decoration, it is partially uniform.
  174. // TODO(kuhar): Track access chain indices and also consider Flat members
  175. // of a structure.
  176. context().get_decoration_mgr()->WhileEachDecoration(
  177. def_id, SpvDecorationFlat, [&ret](const opt::Instruction&) {
  178. ret = DivergenceLevel::kPartiallyUniform;
  179. return false;
  180. });
  181. break;
  182. case SpvStorageClassUniformConstant:
  183. // May be a storage image which is also written to; mark those as
  184. // divergent.
  185. if (!var->IsVulkanStorageImage() || var->IsReadOnlyPointer()) {
  186. ret = DivergenceLevel::kUniform;
  187. } else {
  188. ret = DivergenceLevel::kDivergent;
  189. }
  190. break;
  191. case SpvStorageClassUniform:
  192. case SpvStorageClassPushConstant:
  193. case SpvStorageClassCrossWorkgroup: // Not for shaders; default uniform.
  194. default:
  195. ret = DivergenceLevel::kUniform;
  196. break;
  197. }
  198. return ret;
  199. }
  200. void DivergenceAnalysis::Setup(opt::Function* function) {
  201. // TODO(kuhar): Run functions called by |function| so we can detect
  202. // reconvergence caused by multiple returns.
  203. cd_.ComputeControlDependenceGraph(
  204. *context().cfg(), *context().GetPostDominatorAnalysis(function));
  205. context().cfg()->ForEachBlockInPostOrder(
  206. function->entry().get(), [this](const opt::BasicBlock* bb) {
  207. uint32_t id = bb->id();
  208. if (bb->terminator() == nullptr ||
  209. bb->terminator()->opcode() != SpvOpBranch) {
  210. follow_unconditional_branches_[id] = id;
  211. } else {
  212. uint32_t target_id = bb->terminator()->GetSingleWordInOperand(0);
  213. // Target is guaranteed to have been visited before us in postorder.
  214. follow_unconditional_branches_[id] =
  215. follow_unconditional_branches_[target_id];
  216. }
  217. });
  218. }
  219. std::ostream& operator<<(std::ostream& os,
  220. DivergenceAnalysis::DivergenceLevel level) {
  221. switch (level) {
  222. case DivergenceAnalysis::DivergenceLevel::kUniform:
  223. return os << "uniform";
  224. case DivergenceAnalysis::DivergenceLevel::kPartiallyUniform:
  225. return os << "partially uniform";
  226. case DivergenceAnalysis::DivergenceLevel::kDivergent:
  227. return os << "divergent";
  228. default:
  229. return os << "<invalid divergence level>";
  230. }
  231. }
  232. } // namespace lint
  233. } // namespace spvtools