ssa_rewrite_pass.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. // This file implements the SSA rewriting algorithm proposed in
  5. //
  6. // Simple and Efficient Construction of Static Single Assignment Form.
  7. // Braun M., Buchwald S., Hack S., Leiba R., Mallon C., Zwinkau A. (2013)
  8. // In: Jhala R., De Bosschere K. (eds)
  9. // Compiler Construction. CC 2013.
  10. // Lecture Notes in Computer Science, vol 7791.
  11. // Springer, Berlin, Heidelberg
  12. //
  13. // https://link.springer.com/chapter/10.1007/978-3-642-37051-9_6
  14. //
  15. #include <ranges>
  16. #include <span>
  17. #include <variant>
  18. #include <vector>
  19. #include <boost/container/flat_map.hpp>
  20. #include <boost/container/flat_set.hpp>
  21. #include "shader_recompiler/frontend/ir/basic_block.h"
  22. #include "shader_recompiler/frontend/ir/microinstruction.h"
  23. #include "shader_recompiler/frontend/ir/opcodes.h"
  24. #include "shader_recompiler/frontend/ir/pred.h"
  25. #include "shader_recompiler/frontend/ir/reg.h"
  26. #include "shader_recompiler/ir_opt/passes.h"
  27. namespace Shader::Optimization {
  28. namespace {
  29. struct FlagTag {
  30. auto operator<=>(const FlagTag&) const noexcept = default;
  31. };
  32. struct ZeroFlagTag : FlagTag {};
  33. struct SignFlagTag : FlagTag {};
  34. struct CarryFlagTag : FlagTag {};
  35. struct OverflowFlagTag : FlagTag {};
  36. struct GotoVariable : FlagTag {
  37. GotoVariable() = default;
  38. explicit GotoVariable(u32 index_) : index{index_} {}
  39. auto operator<=>(const GotoVariable&) const noexcept = default;
  40. u32 index;
  41. };
  42. struct IndirectBranchVariable {
  43. auto operator<=>(const IndirectBranchVariable&) const noexcept = default;
  44. };
  45. using Variant = std::variant<IR::Reg, IR::Pred, ZeroFlagTag, SignFlagTag, CarryFlagTag,
  46. OverflowFlagTag, GotoVariable, IndirectBranchVariable>;
  47. using ValueMap = boost::container::flat_map<IR::Block*, IR::Value, std::less<IR::Block*>>;
  48. struct DefTable {
  49. [[nodiscard]] ValueMap& operator[](IR::Reg variable) noexcept {
  50. return regs[IR::RegIndex(variable)];
  51. }
  52. [[nodiscard]] ValueMap& operator[](IR::Pred variable) noexcept {
  53. return preds[IR::PredIndex(variable)];
  54. }
  55. [[nodiscard]] ValueMap& operator[](GotoVariable goto_variable) {
  56. return goto_vars[goto_variable.index];
  57. }
  58. [[nodiscard]] ValueMap& operator[](IndirectBranchVariable) {
  59. return indirect_branch_var;
  60. }
  61. [[nodiscard]] ValueMap& operator[](ZeroFlagTag) noexcept {
  62. return zero_flag;
  63. }
  64. [[nodiscard]] ValueMap& operator[](SignFlagTag) noexcept {
  65. return sign_flag;
  66. }
  67. [[nodiscard]] ValueMap& operator[](CarryFlagTag) noexcept {
  68. return carry_flag;
  69. }
  70. [[nodiscard]] ValueMap& operator[](OverflowFlagTag) noexcept {
  71. return overflow_flag;
  72. }
  73. std::array<ValueMap, IR::NUM_USER_REGS> regs;
  74. std::array<ValueMap, IR::NUM_USER_PREDS> preds;
  75. boost::container::flat_map<u32, ValueMap> goto_vars;
  76. ValueMap indirect_branch_var;
  77. ValueMap zero_flag;
  78. ValueMap sign_flag;
  79. ValueMap carry_flag;
  80. ValueMap overflow_flag;
  81. };
  82. IR::Opcode UndefOpcode(IR::Reg) noexcept {
  83. return IR::Opcode::UndefU32;
  84. }
  85. IR::Opcode UndefOpcode(IR::Pred) noexcept {
  86. return IR::Opcode::UndefU1;
  87. }
  88. IR::Opcode UndefOpcode(const FlagTag&) noexcept {
  89. return IR::Opcode::UndefU1;
  90. }
  91. IR::Opcode UndefOpcode(IndirectBranchVariable) noexcept {
  92. return IR::Opcode::UndefU32;
  93. }
  94. [[nodiscard]] bool IsPhi(const IR::Inst& inst) noexcept {
  95. return inst.GetOpcode() == IR::Opcode::Phi;
  96. }
  97. enum class Status {
  98. Start,
  99. SetValue,
  100. PreparePhiArgument,
  101. PushPhiArgument,
  102. };
  103. template <typename Type>
  104. struct ReadState {
  105. ReadState(IR::Block* block_) : block{block_} {}
  106. ReadState() = default;
  107. IR::Block* block{};
  108. IR::Value result{};
  109. IR::Inst* phi{};
  110. IR::Block* const* pred_it{};
  111. IR::Block* const* pred_end{};
  112. Status pc{Status::Start};
  113. };
  114. class Pass {
  115. public:
  116. template <typename Type>
  117. void WriteVariable(Type variable, IR::Block* block, const IR::Value& value) {
  118. current_def[variable].insert_or_assign(block, value);
  119. }
  120. template <typename Type>
  121. IR::Value ReadVariable(Type variable, IR::Block* root_block) {
  122. boost::container::small_vector<ReadState<Type>, 64> stack{
  123. ReadState<Type>(nullptr),
  124. ReadState<Type>(root_block),
  125. };
  126. const auto prepare_phi_operand{[&] {
  127. if (stack.back().pred_it == stack.back().pred_end) {
  128. IR::Inst* const phi{stack.back().phi};
  129. IR::Block* const block{stack.back().block};
  130. const IR::Value result{TryRemoveTrivialPhi(*phi, block, UndefOpcode(variable))};
  131. stack.pop_back();
  132. stack.back().result = result;
  133. WriteVariable(variable, block, result);
  134. } else {
  135. IR::Block* const imm_pred{*stack.back().pred_it};
  136. stack.back().pc = Status::PushPhiArgument;
  137. stack.emplace_back(imm_pred);
  138. }
  139. }};
  140. do {
  141. IR::Block* const block{stack.back().block};
  142. switch (stack.back().pc) {
  143. case Status::Start: {
  144. const ValueMap& def{current_def[variable]};
  145. if (const auto it{def.find(block)}; it != def.end()) {
  146. stack.back().result = it->second;
  147. } else if (!sealed_blocks.contains(block)) {
  148. // Incomplete CFG
  149. IR::Inst* phi{&*block->PrependNewInst(block->begin(), IR::Opcode::Phi)};
  150. incomplete_phis[block].insert_or_assign(variable, phi);
  151. stack.back().result = IR::Value{&*phi};
  152. } else if (const std::span imm_preds{block->ImmediatePredecessors()};
  153. imm_preds.size() == 1) {
  154. // Optimize the common case of one predecessor: no phi needed
  155. stack.back().pc = Status::SetValue;
  156. stack.emplace_back(imm_preds.front());
  157. break;
  158. } else {
  159. // Break potential cycles with operandless phi
  160. IR::Inst* const phi{&*block->PrependNewInst(block->begin(), IR::Opcode::Phi)};
  161. WriteVariable(variable, block, IR::Value{phi});
  162. stack.back().phi = phi;
  163. stack.back().pred_it = imm_preds.data();
  164. stack.back().pred_end = imm_preds.data() + imm_preds.size();
  165. prepare_phi_operand();
  166. break;
  167. }
  168. }
  169. [[fallthrough]];
  170. case Status::SetValue: {
  171. const IR::Value result{stack.back().result};
  172. WriteVariable(variable, block, result);
  173. stack.pop_back();
  174. stack.back().result = result;
  175. break;
  176. }
  177. case Status::PushPhiArgument: {
  178. IR::Inst* const phi{stack.back().phi};
  179. phi->AddPhiOperand(*stack.back().pred_it, stack.back().result);
  180. ++stack.back().pred_it;
  181. }
  182. [[fallthrough]];
  183. case Status::PreparePhiArgument:
  184. prepare_phi_operand();
  185. break;
  186. }
  187. } while (stack.size() > 1);
  188. return stack.back().result;
  189. }
  190. void SealBlock(IR::Block* block) {
  191. const auto it{incomplete_phis.find(block)};
  192. if (it != incomplete_phis.end()) {
  193. for (auto& [variant, phi] : it->second) {
  194. std::visit([&](auto& variable) { AddPhiOperands(variable, *phi, block); }, variant);
  195. }
  196. }
  197. sealed_blocks.insert(block);
  198. }
  199. private:
  200. template <typename Type>
  201. IR::Value AddPhiOperands(Type variable, IR::Inst& phi, IR::Block* block) {
  202. for (IR::Block* const imm_pred : block->ImmediatePredecessors()) {
  203. phi.AddPhiOperand(imm_pred, ReadVariable(variable, imm_pred));
  204. }
  205. return TryRemoveTrivialPhi(phi, block, UndefOpcode(variable));
  206. }
  207. IR::Value TryRemoveTrivialPhi(IR::Inst& phi, IR::Block* block, IR::Opcode undef_opcode) {
  208. IR::Value same;
  209. const size_t num_args{phi.NumArgs()};
  210. for (size_t arg_index = 0; arg_index < num_args; ++arg_index) {
  211. const IR::Value& op{phi.Arg(arg_index)};
  212. if (op.Resolve() == same.Resolve() || op == IR::Value{&phi}) {
  213. // Unique value or self-reference
  214. continue;
  215. }
  216. if (!same.IsEmpty()) {
  217. // The phi merges at least two values: not trivial
  218. return IR::Value{&phi};
  219. }
  220. same = op;
  221. }
  222. if (same.IsEmpty()) {
  223. // The phi is unreachable or in the start block
  224. // First remove the phi node from the block, it will be reinserted
  225. IR::Block::InstructionList& list{block->Instructions()};
  226. list.erase(IR::Block::InstructionList::s_iterator_to(phi));
  227. // Insert an undef instruction after all phi nodes (to keep phi instructions on top)
  228. const auto first_not_phi{std::ranges::find_if_not(list, IsPhi)};
  229. same = IR::Value{&*block->PrependNewInst(first_not_phi, undef_opcode)};
  230. // Insert the phi node after the undef opcode, this will be replaced with an identity
  231. list.insert(first_not_phi, phi);
  232. }
  233. // Reroute all uses of phi to same and remove phi
  234. phi.ReplaceUsesWith(same);
  235. // TODO: Try to recursively remove all phi users, which might have become trivial
  236. return same;
  237. }
  238. boost::container::flat_set<IR::Block*> sealed_blocks;
  239. boost::container::flat_map<IR::Block*, boost::container::flat_map<Variant, IR::Inst*>>
  240. incomplete_phis;
  241. DefTable current_def;
  242. };
  243. void VisitInst(Pass& pass, IR::Block* block, IR::Inst& inst) {
  244. switch (inst.GetOpcode()) {
  245. case IR::Opcode::SetRegister:
  246. if (const IR::Reg reg{inst.Arg(0).Reg()}; reg != IR::Reg::RZ) {
  247. pass.WriteVariable(reg, block, inst.Arg(1));
  248. }
  249. break;
  250. case IR::Opcode::SetPred:
  251. if (const IR::Pred pred{inst.Arg(0).Pred()}; pred != IR::Pred::PT) {
  252. pass.WriteVariable(pred, block, inst.Arg(1));
  253. }
  254. break;
  255. case IR::Opcode::SetGotoVariable:
  256. pass.WriteVariable(GotoVariable{inst.Arg(0).U32()}, block, inst.Arg(1));
  257. break;
  258. case IR::Opcode::SetIndirectBranchVariable:
  259. pass.WriteVariable(IndirectBranchVariable{}, block, inst.Arg(0));
  260. break;
  261. case IR::Opcode::SetZFlag:
  262. pass.WriteVariable(ZeroFlagTag{}, block, inst.Arg(0));
  263. break;
  264. case IR::Opcode::SetSFlag:
  265. pass.WriteVariable(SignFlagTag{}, block, inst.Arg(0));
  266. break;
  267. case IR::Opcode::SetCFlag:
  268. pass.WriteVariable(CarryFlagTag{}, block, inst.Arg(0));
  269. break;
  270. case IR::Opcode::SetOFlag:
  271. pass.WriteVariable(OverflowFlagTag{}, block, inst.Arg(0));
  272. break;
  273. case IR::Opcode::GetRegister:
  274. if (const IR::Reg reg{inst.Arg(0).Reg()}; reg != IR::Reg::RZ) {
  275. inst.ReplaceUsesWith(pass.ReadVariable(reg, block));
  276. }
  277. break;
  278. case IR::Opcode::GetPred:
  279. if (const IR::Pred pred{inst.Arg(0).Pred()}; pred != IR::Pred::PT) {
  280. inst.ReplaceUsesWith(pass.ReadVariable(pred, block));
  281. }
  282. break;
  283. case IR::Opcode::GetGotoVariable:
  284. inst.ReplaceUsesWith(pass.ReadVariable(GotoVariable{inst.Arg(0).U32()}, block));
  285. break;
  286. case IR::Opcode::GetIndirectBranchVariable:
  287. inst.ReplaceUsesWith(pass.ReadVariable(IndirectBranchVariable{}, block));
  288. break;
  289. case IR::Opcode::GetZFlag:
  290. inst.ReplaceUsesWith(pass.ReadVariable(ZeroFlagTag{}, block));
  291. break;
  292. case IR::Opcode::GetSFlag:
  293. inst.ReplaceUsesWith(pass.ReadVariable(SignFlagTag{}, block));
  294. break;
  295. case IR::Opcode::GetCFlag:
  296. inst.ReplaceUsesWith(pass.ReadVariable(CarryFlagTag{}, block));
  297. break;
  298. case IR::Opcode::GetOFlag:
  299. inst.ReplaceUsesWith(pass.ReadVariable(OverflowFlagTag{}, block));
  300. break;
  301. default:
  302. break;
  303. }
  304. }
  305. void VisitBlock(Pass& pass, IR::Block* block) {
  306. for (IR::Inst& inst : block->Instructions()) {
  307. VisitInst(pass, block, inst);
  308. }
  309. pass.SealBlock(block);
  310. }
  311. } // Anonymous namespace
  312. void SsaRewritePass(IR::Program& program) {
  313. Pass pass;
  314. for (IR::Block* const block : program.post_order_blocks | std::views::reverse) {
  315. VisitBlock(pass, block);
  316. }
  317. }
  318. } // namespace Shader::Optimization