ssa_rewrite_pass.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 <deque>
  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/opcodes.h"
  23. #include "shader_recompiler/frontend/ir/pred.h"
  24. #include "shader_recompiler/frontend/ir/reg.h"
  25. #include "shader_recompiler/frontend/ir/value.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>;
  48. struct DefTable {
  49. const IR::Value& Def(IR::Block* block, IR::Reg variable) {
  50. return block->SsaRegValue(variable);
  51. }
  52. void SetDef(IR::Block* block, IR::Reg variable, const IR::Value& value) {
  53. block->SetSsaRegValue(variable, value);
  54. }
  55. const IR::Value& Def(IR::Block* block, IR::Pred variable) {
  56. return preds[IR::PredIndex(variable)][block];
  57. }
  58. void SetDef(IR::Block* block, IR::Pred variable, const IR::Value& value) {
  59. preds[IR::PredIndex(variable)].insert_or_assign(block, value);
  60. }
  61. const IR::Value& Def(IR::Block* block, GotoVariable variable) {
  62. return goto_vars[variable.index][block];
  63. }
  64. void SetDef(IR::Block* block, GotoVariable variable, const IR::Value& value) {
  65. goto_vars[variable.index].insert_or_assign(block, value);
  66. }
  67. const IR::Value& Def(IR::Block* block, IndirectBranchVariable) {
  68. return indirect_branch_var[block];
  69. }
  70. void SetDef(IR::Block* block, IndirectBranchVariable, const IR::Value& value) {
  71. indirect_branch_var.insert_or_assign(block, value);
  72. }
  73. const IR::Value& Def(IR::Block* block, ZeroFlagTag) {
  74. return zero_flag[block];
  75. }
  76. void SetDef(IR::Block* block, ZeroFlagTag, const IR::Value& value) {
  77. zero_flag.insert_or_assign(block, value);
  78. }
  79. const IR::Value& Def(IR::Block* block, SignFlagTag) {
  80. return sign_flag[block];
  81. }
  82. void SetDef(IR::Block* block, SignFlagTag, const IR::Value& value) {
  83. sign_flag.insert_or_assign(block, value);
  84. }
  85. const IR::Value& Def(IR::Block* block, CarryFlagTag) {
  86. return carry_flag[block];
  87. }
  88. void SetDef(IR::Block* block, CarryFlagTag, const IR::Value& value) {
  89. carry_flag.insert_or_assign(block, value);
  90. }
  91. const IR::Value& Def(IR::Block* block, OverflowFlagTag) {
  92. return overflow_flag[block];
  93. }
  94. void SetDef(IR::Block* block, OverflowFlagTag, const IR::Value& value) {
  95. overflow_flag.insert_or_assign(block, value);
  96. }
  97. std::array<ValueMap, IR::NUM_USER_PREDS> preds;
  98. boost::container::flat_map<u32, ValueMap> goto_vars;
  99. ValueMap indirect_branch_var;
  100. ValueMap zero_flag;
  101. ValueMap sign_flag;
  102. ValueMap carry_flag;
  103. ValueMap overflow_flag;
  104. };
  105. IR::Opcode UndefOpcode(IR::Reg) noexcept {
  106. return IR::Opcode::UndefU32;
  107. }
  108. IR::Opcode UndefOpcode(IR::Pred) noexcept {
  109. return IR::Opcode::UndefU1;
  110. }
  111. IR::Opcode UndefOpcode(const FlagTag&) noexcept {
  112. return IR::Opcode::UndefU1;
  113. }
  114. IR::Opcode UndefOpcode(IndirectBranchVariable) noexcept {
  115. return IR::Opcode::UndefU32;
  116. }
  117. enum class Status {
  118. Start,
  119. SetValue,
  120. PreparePhiArgument,
  121. PushPhiArgument,
  122. };
  123. template <typename Type>
  124. struct ReadState {
  125. ReadState(IR::Block* block_) : block{block_} {}
  126. ReadState() = default;
  127. IR::Block* block{};
  128. IR::Value result{};
  129. IR::Inst* phi{};
  130. IR::Block* const* pred_it{};
  131. IR::Block* const* pred_end{};
  132. Status pc{Status::Start};
  133. };
  134. class Pass {
  135. public:
  136. template <typename Type>
  137. void WriteVariable(Type variable, IR::Block* block, const IR::Value& value) {
  138. current_def.SetDef(block, variable, value);
  139. }
  140. template <typename Type>
  141. IR::Value ReadVariable(Type variable, IR::Block* root_block) {
  142. boost::container::small_vector<ReadState<Type>, 64> stack{
  143. ReadState<Type>(nullptr),
  144. ReadState<Type>(root_block),
  145. };
  146. const auto prepare_phi_operand{[&] {
  147. if (stack.back().pred_it == stack.back().pred_end) {
  148. IR::Inst* const phi{stack.back().phi};
  149. IR::Block* const block{stack.back().block};
  150. const IR::Value result{TryRemoveTrivialPhi(*phi, block, UndefOpcode(variable))};
  151. stack.pop_back();
  152. stack.back().result = result;
  153. WriteVariable(variable, block, result);
  154. } else {
  155. IR::Block* const imm_pred{*stack.back().pred_it};
  156. stack.back().pc = Status::PushPhiArgument;
  157. stack.emplace_back(imm_pred);
  158. }
  159. }};
  160. do {
  161. IR::Block* const block{stack.back().block};
  162. switch (stack.back().pc) {
  163. case Status::Start: {
  164. if (const IR::Value& def = current_def.Def(block, variable); !def.IsEmpty()) {
  165. stack.back().result = def;
  166. } else if (!block->IsSsaSealed()) {
  167. // Incomplete CFG
  168. IR::Inst* phi{&*block->PrependNewInst(block->begin(), IR::Opcode::Phi)};
  169. phi->SetFlags(IR::TypeOf(UndefOpcode(variable)));
  170. incomplete_phis[block].insert_or_assign(variable, phi);
  171. stack.back().result = IR::Value{&*phi};
  172. } else if (const std::span imm_preds = block->ImmPredecessors();
  173. imm_preds.size() == 1) {
  174. // Optimize the common case of one predecessor: no phi needed
  175. stack.back().pc = Status::SetValue;
  176. stack.emplace_back(imm_preds.front());
  177. break;
  178. } else {
  179. // Break potential cycles with operandless phi
  180. IR::Inst* const phi{&*block->PrependNewInst(block->begin(), IR::Opcode::Phi)};
  181. phi->SetFlags(IR::TypeOf(UndefOpcode(variable)));
  182. WriteVariable(variable, block, IR::Value{phi});
  183. stack.back().phi = phi;
  184. stack.back().pred_it = imm_preds.data();
  185. stack.back().pred_end = imm_preds.data() + imm_preds.size();
  186. prepare_phi_operand();
  187. break;
  188. }
  189. }
  190. [[fallthrough]];
  191. case Status::SetValue: {
  192. const IR::Value result{stack.back().result};
  193. WriteVariable(variable, block, result);
  194. stack.pop_back();
  195. stack.back().result = result;
  196. break;
  197. }
  198. case Status::PushPhiArgument: {
  199. IR::Inst* const phi{stack.back().phi};
  200. phi->AddPhiOperand(*stack.back().pred_it, stack.back().result);
  201. ++stack.back().pred_it;
  202. }
  203. [[fallthrough]];
  204. case Status::PreparePhiArgument:
  205. prepare_phi_operand();
  206. break;
  207. }
  208. } while (stack.size() > 1);
  209. return stack.back().result;
  210. }
  211. void SealBlock(IR::Block* block) {
  212. const auto it{incomplete_phis.find(block)};
  213. if (it != incomplete_phis.end()) {
  214. for (auto& pair : it->second) {
  215. auto& variant{pair.first};
  216. auto& phi{pair.second};
  217. std::visit([&](auto& variable) { AddPhiOperands(variable, *phi, block); }, variant);
  218. }
  219. }
  220. block->SsaSeal();
  221. }
  222. private:
  223. template <typename Type>
  224. IR::Value AddPhiOperands(Type variable, IR::Inst& phi, IR::Block* block) {
  225. for (IR::Block* const imm_pred : block->ImmPredecessors()) {
  226. phi.AddPhiOperand(imm_pred, ReadVariable(variable, imm_pred));
  227. }
  228. return TryRemoveTrivialPhi(phi, block, UndefOpcode(variable));
  229. }
  230. IR::Value TryRemoveTrivialPhi(IR::Inst& phi, IR::Block* block, IR::Opcode undef_opcode) {
  231. IR::Value same;
  232. const size_t num_args{phi.NumArgs()};
  233. for (size_t arg_index = 0; arg_index < num_args; ++arg_index) {
  234. const IR::Value& op{phi.Arg(arg_index)};
  235. if (op.Resolve() == same.Resolve() || op == IR::Value{&phi}) {
  236. // Unique value or self-reference
  237. continue;
  238. }
  239. if (!same.IsEmpty()) {
  240. // The phi merges at least two values: not trivial
  241. return IR::Value{&phi};
  242. }
  243. same = op;
  244. }
  245. // Remove the phi node from the block, it will be reinserted
  246. IR::Block::InstructionList& list{block->Instructions()};
  247. list.erase(IR::Block::InstructionList::s_iterator_to(phi));
  248. // Find the first non-phi instruction and use it as an insertion point
  249. IR::Block::iterator reinsert_point{std::ranges::find_if_not(list, IR::IsPhi)};
  250. if (same.IsEmpty()) {
  251. // The phi is unreachable or in the start block
  252. // Insert an undefined instruction and make it the phi node replacement
  253. // The "phi" node reinsertion point is specified after this instruction
  254. reinsert_point = block->PrependNewInst(reinsert_point, undef_opcode);
  255. same = IR::Value{&*reinsert_point};
  256. ++reinsert_point;
  257. }
  258. // Reinsert the phi node and reroute all its uses to the "same" value
  259. list.insert(reinsert_point, phi);
  260. phi.ReplaceUsesWith(same);
  261. // TODO: Try to recursively remove all phi users, which might have become trivial
  262. return same;
  263. }
  264. boost::container::flat_map<IR::Block*, boost::container::flat_map<Variant, IR::Inst*>>
  265. incomplete_phis;
  266. DefTable current_def;
  267. };
  268. void VisitInst(Pass& pass, IR::Block* block, IR::Inst& inst) {
  269. switch (inst.GetOpcode()) {
  270. case IR::Opcode::SetRegister:
  271. if (const IR::Reg reg{inst.Arg(0).Reg()}; reg != IR::Reg::RZ) {
  272. pass.WriteVariable(reg, block, inst.Arg(1));
  273. }
  274. break;
  275. case IR::Opcode::SetPred:
  276. if (const IR::Pred pred{inst.Arg(0).Pred()}; pred != IR::Pred::PT) {
  277. pass.WriteVariable(pred, block, inst.Arg(1));
  278. }
  279. break;
  280. case IR::Opcode::SetGotoVariable:
  281. pass.WriteVariable(GotoVariable{inst.Arg(0).U32()}, block, inst.Arg(1));
  282. break;
  283. case IR::Opcode::SetIndirectBranchVariable:
  284. pass.WriteVariable(IndirectBranchVariable{}, block, inst.Arg(0));
  285. break;
  286. case IR::Opcode::SetZFlag:
  287. pass.WriteVariable(ZeroFlagTag{}, block, inst.Arg(0));
  288. break;
  289. case IR::Opcode::SetSFlag:
  290. pass.WriteVariable(SignFlagTag{}, block, inst.Arg(0));
  291. break;
  292. case IR::Opcode::SetCFlag:
  293. pass.WriteVariable(CarryFlagTag{}, block, inst.Arg(0));
  294. break;
  295. case IR::Opcode::SetOFlag:
  296. pass.WriteVariable(OverflowFlagTag{}, block, inst.Arg(0));
  297. break;
  298. case IR::Opcode::GetRegister:
  299. if (const IR::Reg reg{inst.Arg(0).Reg()}; reg != IR::Reg::RZ) {
  300. inst.ReplaceUsesWith(pass.ReadVariable(reg, block));
  301. }
  302. break;
  303. case IR::Opcode::GetPred:
  304. if (const IR::Pred pred{inst.Arg(0).Pred()}; pred != IR::Pred::PT) {
  305. inst.ReplaceUsesWith(pass.ReadVariable(pred, block));
  306. }
  307. break;
  308. case IR::Opcode::GetGotoVariable:
  309. inst.ReplaceUsesWith(pass.ReadVariable(GotoVariable{inst.Arg(0).U32()}, block));
  310. break;
  311. case IR::Opcode::GetIndirectBranchVariable:
  312. inst.ReplaceUsesWith(pass.ReadVariable(IndirectBranchVariable{}, block));
  313. break;
  314. case IR::Opcode::GetZFlag:
  315. inst.ReplaceUsesWith(pass.ReadVariable(ZeroFlagTag{}, block));
  316. break;
  317. case IR::Opcode::GetSFlag:
  318. inst.ReplaceUsesWith(pass.ReadVariable(SignFlagTag{}, block));
  319. break;
  320. case IR::Opcode::GetCFlag:
  321. inst.ReplaceUsesWith(pass.ReadVariable(CarryFlagTag{}, block));
  322. break;
  323. case IR::Opcode::GetOFlag:
  324. inst.ReplaceUsesWith(pass.ReadVariable(OverflowFlagTag{}, block));
  325. break;
  326. default:
  327. break;
  328. }
  329. }
  330. void VisitBlock(Pass& pass, IR::Block* block) {
  331. for (IR::Inst& inst : block->Instructions()) {
  332. VisitInst(pass, block, inst);
  333. }
  334. pass.SealBlock(block);
  335. }
  336. IR::Type GetConcreteType(IR::Inst* inst) {
  337. std::deque<IR::Inst*> queue;
  338. queue.push_back(inst);
  339. while (!queue.empty()) {
  340. IR::Inst* current = queue.front();
  341. queue.pop_front();
  342. const size_t num_args{current->NumArgs()};
  343. for (size_t i = 0; i < num_args; ++i) {
  344. const auto set_type = current->Arg(i).Type();
  345. if (set_type != IR::Type::Opaque) {
  346. return set_type;
  347. }
  348. if (!current->Arg(i).IsImmediate()) {
  349. queue.push_back(current->Arg(i).Inst());
  350. }
  351. }
  352. }
  353. return IR::Type::Opaque;
  354. }
  355. } // Anonymous namespace
  356. void SsaRewritePass(IR::Program& program) {
  357. Pass pass;
  358. const auto end{program.post_order_blocks.rend()};
  359. for (auto block = program.post_order_blocks.rbegin(); block != end; ++block) {
  360. VisitBlock(pass, *block);
  361. }
  362. for (auto block = program.post_order_blocks.rbegin(); block != end; ++block) {
  363. for (IR::Inst& inst : (*block)->Instructions()) {
  364. if (inst.GetOpcode() == IR::Opcode::Phi) {
  365. if (inst.Type() == IR::Type::Opaque) {
  366. inst.SetFlags(GetConcreteType(&inst));
  367. }
  368. inst.OrderPhiArgs();
  369. }
  370. }
  371. }
  372. }
  373. } // namespace Shader::Optimization