control_flow.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. // Copyright 2019 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <list>
  5. #include <map>
  6. #include <unordered_map>
  7. #include <unordered_set>
  8. #include <vector>
  9. #include "common/assert.h"
  10. #include "common/common_types.h"
  11. #include "video_core/shader/control_flow.h"
  12. #include "video_core/shader/shader_ir.h"
  13. namespace VideoCommon::Shader {
  14. using Tegra::Shader::Instruction;
  15. using Tegra::Shader::OpCode;
  16. constexpr s32 unassigned_branch = -2;
  17. /**
  18. * 'ControlStack' represents a static stack of control jumps such as SSY and PBK
  19. * stacks in Maxwell.
  20. **/
  21. struct ControlStack {
  22. static constexpr std::size_t stack_fixed_size = 20;
  23. std::array<u32, stack_fixed_size> stack{};
  24. u32 index{};
  25. bool Compare(const ControlStack& cs) const {
  26. if (index != cs.index) {
  27. return false;
  28. }
  29. return std::memcmp(stack.data(), cs.stack.data(), index * sizeof(u32)) == 0;
  30. }
  31. /// This compare just compares the top of the stack against one another
  32. bool SoftCompare(const ControlStack& cs) const {
  33. if (index == 0 || cs.index == 0) {
  34. return index == cs.index;
  35. }
  36. return Top() == cs.Top();
  37. }
  38. u32 Size() const {
  39. return index;
  40. }
  41. u32 Top() const {
  42. return stack[index - 1];
  43. }
  44. bool Push(u32 address) {
  45. if (index >= stack.size()) {
  46. return false;
  47. }
  48. stack[index] = address;
  49. index++;
  50. return true;
  51. }
  52. bool Pop() {
  53. if (index == 0) {
  54. return false;
  55. }
  56. index--;
  57. return true;
  58. }
  59. };
  60. struct Query {
  61. u32 address{};
  62. ControlStack ssy_stack{};
  63. ControlStack pbk_stack{};
  64. };
  65. struct BlockStack {
  66. BlockStack() = default;
  67. BlockStack(const BlockStack& b) = default;
  68. BlockStack(const Query& q) : ssy_stack{q.ssy_stack}, pbk_stack{q.pbk_stack} {}
  69. ControlStack ssy_stack{};
  70. ControlStack pbk_stack{};
  71. };
  72. struct BlockBranchInfo {
  73. Condition condition{};
  74. s32 address{exit_branch};
  75. bool kill{};
  76. bool is_sync{};
  77. bool is_brk{};
  78. bool ignore{};
  79. };
  80. struct BlockInfo {
  81. u32 start{};
  82. u32 end{};
  83. bool visited{};
  84. BlockBranchInfo branch{};
  85. bool IsInside(const u32 address) const {
  86. return start <= address && address <= end;
  87. }
  88. };
  89. struct CFGRebuildState {
  90. explicit CFGRebuildState(const ProgramCode& program_code, const std::size_t program_size,
  91. const u32 start)
  92. : program_code{program_code}, program_size{program_size}, start{start} {}
  93. u32 start{};
  94. std::vector<BlockInfo> block_info{};
  95. std::list<u32> inspect_queries{};
  96. std::list<Query> queries{};
  97. std::unordered_map<u32, u32> registered{};
  98. std::unordered_set<u32> labels{};
  99. std::map<u32, u32> ssy_labels{};
  100. std::map<u32, u32> pbk_labels{};
  101. std::unordered_map<u32, BlockStack> stacks{};
  102. const ProgramCode& program_code;
  103. const std::size_t program_size;
  104. };
  105. enum class BlockCollision : u32 { None, Found, Inside };
  106. std::pair<BlockCollision, std::vector<BlockInfo>::iterator> TryGetBlock(CFGRebuildState& state,
  107. u32 address) {
  108. auto it = state.block_info.begin();
  109. while (it != state.block_info.end()) {
  110. if (it->start == address) {
  111. return {BlockCollision::Found, it};
  112. }
  113. if (it->IsInside(address)) {
  114. return {BlockCollision::Inside, it};
  115. }
  116. it++;
  117. }
  118. return {BlockCollision::None, it};
  119. }
  120. struct ParseInfo {
  121. BlockBranchInfo branch_info{};
  122. u32 end_address{};
  123. };
  124. BlockInfo* CreateBlockInfo(CFGRebuildState& state, u32 start, u32 end) {
  125. auto& it = state.block_info.emplace_back();
  126. it.start = start;
  127. it.end = end;
  128. const u32 index = static_cast<u32>(state.block_info.size() - 1);
  129. state.registered.insert({start, index});
  130. return &it;
  131. }
  132. Pred GetPredicate(u32 index, bool negated) {
  133. return static_cast<Pred>(index + (negated ? 8 : 0));
  134. }
  135. /**
  136. * Returns whether the instruction at the specified offset is a 'sched' instruction.
  137. * Sched instructions always appear before a sequence of 3 instructions.
  138. */
  139. constexpr bool IsSchedInstruction(u32 offset, u32 main_offset) {
  140. constexpr u32 SchedPeriod = 4;
  141. u32 absolute_offset = offset - main_offset;
  142. return (absolute_offset % SchedPeriod) == 0;
  143. }
  144. enum class ParseResult : u32 {
  145. ControlCaught,
  146. BlockEnd,
  147. AbnormalFlow,
  148. };
  149. ParseResult ParseCode(CFGRebuildState& state, u32 address, ParseInfo& parse_info) {
  150. u32 offset = static_cast<u32>(address);
  151. const u32 end_address = static_cast<u32>(state.program_size / sizeof(Instruction));
  152. const auto insert_label = ([](CFGRebuildState& state, u32 address) {
  153. auto pair = state.labels.emplace(address);
  154. if (pair.second) {
  155. state.inspect_queries.push_back(address);
  156. }
  157. });
  158. while (true) {
  159. if (offset >= end_address) {
  160. parse_info.branch_info.address = exit_branch;
  161. parse_info.branch_info.ignore = false;
  162. break;
  163. }
  164. if (state.registered.count(offset) != 0) {
  165. parse_info.branch_info.address = offset;
  166. parse_info.branch_info.ignore = true;
  167. break;
  168. }
  169. if (IsSchedInstruction(offset, state.start)) {
  170. offset++;
  171. continue;
  172. }
  173. const Instruction instr = {state.program_code[offset]};
  174. const auto opcode = OpCode::Decode(instr);
  175. if (!opcode || opcode->get().GetType() != OpCode::Type::Flow) {
  176. offset++;
  177. continue;
  178. }
  179. switch (opcode->get().GetId()) {
  180. case OpCode::Id::EXIT: {
  181. const auto pred_index = static_cast<u32>(instr.pred.pred_index);
  182. parse_info.branch_info.condition.predicate =
  183. GetPredicate(pred_index, instr.negate_pred != 0);
  184. if (parse_info.branch_info.condition.predicate == Pred::NeverExecute) {
  185. offset++;
  186. continue;
  187. }
  188. const ConditionCode cc = instr.flow_condition_code;
  189. parse_info.branch_info.condition.cc = cc;
  190. if (cc == ConditionCode::F) {
  191. offset++;
  192. continue;
  193. }
  194. parse_info.branch_info.address = exit_branch;
  195. parse_info.branch_info.kill = false;
  196. parse_info.branch_info.is_sync = false;
  197. parse_info.branch_info.is_brk = false;
  198. parse_info.branch_info.ignore = false;
  199. parse_info.end_address = offset;
  200. return ParseResult::ControlCaught;
  201. }
  202. case OpCode::Id::BRA: {
  203. if (instr.bra.constant_buffer != 0) {
  204. return ParseResult::AbnormalFlow;
  205. }
  206. const auto pred_index = static_cast<u32>(instr.pred.pred_index);
  207. parse_info.branch_info.condition.predicate =
  208. GetPredicate(pred_index, instr.negate_pred != 0);
  209. if (parse_info.branch_info.condition.predicate == Pred::NeverExecute) {
  210. offset++;
  211. continue;
  212. }
  213. const ConditionCode cc = instr.flow_condition_code;
  214. parse_info.branch_info.condition.cc = cc;
  215. if (cc == ConditionCode::F) {
  216. offset++;
  217. continue;
  218. }
  219. u32 branch_offset = offset + instr.bra.GetBranchTarget();
  220. if (branch_offset == 0) {
  221. parse_info.branch_info.address = exit_branch;
  222. } else {
  223. parse_info.branch_info.address = branch_offset;
  224. }
  225. insert_label(state, branch_offset);
  226. parse_info.branch_info.kill = false;
  227. parse_info.branch_info.is_sync = false;
  228. parse_info.branch_info.is_brk = false;
  229. parse_info.branch_info.ignore = false;
  230. parse_info.end_address = offset;
  231. return ParseResult::ControlCaught;
  232. }
  233. case OpCode::Id::SYNC: {
  234. parse_info.branch_info.condition;
  235. const auto pred_index = static_cast<u32>(instr.pred.pred_index);
  236. parse_info.branch_info.condition.predicate =
  237. GetPredicate(pred_index, instr.negate_pred != 0);
  238. if (parse_info.branch_info.condition.predicate == Pred::NeverExecute) {
  239. offset++;
  240. continue;
  241. }
  242. const ConditionCode cc = instr.flow_condition_code;
  243. parse_info.branch_info.condition.cc = cc;
  244. if (cc == ConditionCode::F) {
  245. offset++;
  246. continue;
  247. }
  248. parse_info.branch_info.address = unassigned_branch;
  249. parse_info.branch_info.kill = false;
  250. parse_info.branch_info.is_sync = true;
  251. parse_info.branch_info.is_brk = false;
  252. parse_info.branch_info.ignore = false;
  253. parse_info.end_address = offset;
  254. return ParseResult::ControlCaught;
  255. }
  256. case OpCode::Id::BRK: {
  257. parse_info.branch_info.condition;
  258. const auto pred_index = static_cast<u32>(instr.pred.pred_index);
  259. parse_info.branch_info.condition.predicate =
  260. GetPredicate(pred_index, instr.negate_pred != 0);
  261. if (parse_info.branch_info.condition.predicate == Pred::NeverExecute) {
  262. offset++;
  263. continue;
  264. }
  265. const ConditionCode cc = instr.flow_condition_code;
  266. parse_info.branch_info.condition.cc = cc;
  267. if (cc == ConditionCode::F) {
  268. offset++;
  269. continue;
  270. }
  271. parse_info.branch_info.address = unassigned_branch;
  272. parse_info.branch_info.kill = false;
  273. parse_info.branch_info.is_sync = false;
  274. parse_info.branch_info.is_brk = true;
  275. parse_info.branch_info.ignore = false;
  276. parse_info.end_address = offset;
  277. return ParseResult::ControlCaught;
  278. }
  279. case OpCode::Id::KIL: {
  280. parse_info.branch_info.condition;
  281. const auto pred_index = static_cast<u32>(instr.pred.pred_index);
  282. parse_info.branch_info.condition.predicate =
  283. GetPredicate(pred_index, instr.negate_pred != 0);
  284. if (parse_info.branch_info.condition.predicate == Pred::NeverExecute) {
  285. offset++;
  286. continue;
  287. }
  288. const ConditionCode cc = instr.flow_condition_code;
  289. parse_info.branch_info.condition.cc = cc;
  290. if (cc == ConditionCode::F) {
  291. offset++;
  292. continue;
  293. }
  294. parse_info.branch_info.address = exit_branch;
  295. parse_info.branch_info.kill = true;
  296. parse_info.branch_info.is_sync = false;
  297. parse_info.branch_info.is_brk = false;
  298. parse_info.branch_info.ignore = false;
  299. parse_info.end_address = offset;
  300. return ParseResult::ControlCaught;
  301. }
  302. case OpCode::Id::SSY: {
  303. const u32 target = offset + instr.bra.GetBranchTarget();
  304. insert_label(state, target);
  305. state.ssy_labels.emplace(offset, target);
  306. break;
  307. }
  308. case OpCode::Id::PBK: {
  309. const u32 target = offset + instr.bra.GetBranchTarget();
  310. insert_label(state, target);
  311. state.pbk_labels.emplace(offset, target);
  312. break;
  313. }
  314. case OpCode::Id::BRX: {
  315. return ParseResult::AbnormalFlow;
  316. }
  317. default:
  318. break;
  319. }
  320. offset++;
  321. }
  322. parse_info.branch_info.kill = false;
  323. parse_info.branch_info.is_sync = false;
  324. parse_info.branch_info.is_brk = false;
  325. parse_info.end_address = offset - 1;
  326. return ParseResult::BlockEnd;
  327. }
  328. bool TryInspectAddress(CFGRebuildState& state) {
  329. if (state.inspect_queries.empty()) {
  330. return false;
  331. }
  332. const u32 address = state.inspect_queries.front();
  333. state.inspect_queries.pop_front();
  334. const auto search_result = TryGetBlock(state, address);
  335. switch (search_result.first) {
  336. case BlockCollision::Found: {
  337. return true;
  338. }
  339. case BlockCollision::Inside: {
  340. // This case is the tricky one:
  341. // We need to Split the block in 2 sepparate blocks
  342. auto it = search_result.second;
  343. BlockInfo* block_info = CreateBlockInfo(state, address, it->end);
  344. it->end = address - 1;
  345. block_info->branch = it->branch;
  346. BlockBranchInfo forward_branch{};
  347. forward_branch.address = address;
  348. forward_branch.ignore = true;
  349. it->branch = forward_branch;
  350. return true;
  351. }
  352. default:
  353. break;
  354. }
  355. ParseInfo parse_info;
  356. const ParseResult parse_result = ParseCode(state, address, parse_info);
  357. if (parse_result == ParseResult::AbnormalFlow) {
  358. // if it's AbnormalFlow, we end it as false, ending the CFG reconstruction
  359. return false;
  360. }
  361. BlockInfo* block_info = CreateBlockInfo(state, address, parse_info.end_address);
  362. block_info->branch = parse_info.branch_info;
  363. if (parse_info.branch_info.condition.IsUnconditional()) {
  364. return true;
  365. }
  366. const u32 fallthrough_address = parse_info.end_address + 1;
  367. state.inspect_queries.push_front(fallthrough_address);
  368. return true;
  369. }
  370. bool TryQuery(CFGRebuildState& state) {
  371. const auto gather_labels = ([](ControlStack& cc, std::map<u32, u32>& labels, BlockInfo& block) {
  372. auto gather_start = labels.lower_bound(block.start);
  373. const auto gather_end = labels.upper_bound(block.end);
  374. while (gather_start != gather_end) {
  375. cc.Push(gather_start->second);
  376. gather_start++;
  377. }
  378. });
  379. if (state.queries.empty()) {
  380. return false;
  381. }
  382. Query& q = state.queries.front();
  383. const u32 block_index = state.registered[q.address];
  384. BlockInfo& block = state.block_info[block_index];
  385. // If the block is visted, check if the stacks match, else gather the ssy/pbk
  386. // labels into the current stack and look if the branch at the end of the block
  387. // consumes a label. Schedule new queries accordingly
  388. if (block.visited) {
  389. BlockStack& stack = state.stacks[q.address];
  390. const bool all_okay =
  391. (stack.ssy_stack.Size() == 0 || q.ssy_stack.Compare(stack.ssy_stack)) &&
  392. (stack.pbk_stack.Size() == 0 || q.pbk_stack.Compare(stack.pbk_stack));
  393. state.queries.pop_front();
  394. return all_okay;
  395. }
  396. block.visited = true;
  397. state.stacks[q.address] = BlockStack{q};
  398. Query q2(q);
  399. state.queries.pop_front();
  400. gather_labels(q2.ssy_stack, state.ssy_labels, block);
  401. gather_labels(q2.pbk_stack, state.pbk_labels, block);
  402. if (!block.branch.condition.IsUnconditional()) {
  403. q2.address = block.end + 1;
  404. state.queries.push_back(q2);
  405. }
  406. Query conditional_query{q2};
  407. if (block.branch.is_sync) {
  408. if (block.branch.address == unassigned_branch) {
  409. block.branch.address = conditional_query.ssy_stack.Top();
  410. }
  411. conditional_query.ssy_stack.Pop();
  412. }
  413. if (block.branch.is_brk) {
  414. if (block.branch.address == unassigned_branch) {
  415. block.branch.address = conditional_query.pbk_stack.Top();
  416. }
  417. conditional_query.pbk_stack.Pop();
  418. }
  419. conditional_query.address = block.branch.address;
  420. state.queries.push_back(conditional_query);
  421. return true;
  422. }
  423. std::optional<ShaderCharacteristics> ScanFlow(const ProgramCode& program_code, u32 program_size,
  424. u32 start_address) {
  425. CFGRebuildState state{program_code, program_size, start_address};
  426. // Inspect Code and generate blocks
  427. state.labels.clear();
  428. state.labels.emplace(start_address);
  429. state.inspect_queries.push_back(state.start);
  430. while (!state.inspect_queries.empty()) {
  431. if (!TryInspectAddress(state)) {
  432. return {};
  433. }
  434. }
  435. // Decompile Stacks
  436. Query start_query{};
  437. start_query.address = state.start;
  438. state.queries.push_back(start_query);
  439. bool decompiled = true;
  440. while (!state.queries.empty()) {
  441. if (!TryQuery(state)) {
  442. decompiled = false;
  443. break;
  444. }
  445. }
  446. // Sort and organize results
  447. std::sort(state.block_info.begin(), state.block_info.end(),
  448. [](const BlockInfo& a, const BlockInfo& b) -> bool { return a.start < b.start; });
  449. ShaderCharacteristics result_out{};
  450. result_out.decompilable = decompiled;
  451. result_out.start = start_address;
  452. result_out.end = start_address;
  453. for (auto& block : state.block_info) {
  454. ShaderBlock new_block{};
  455. new_block.start = block.start;
  456. new_block.end = block.end;
  457. new_block.ignore_branch = block.branch.ignore;
  458. if (!new_block.ignore_branch) {
  459. new_block.branch.cond = block.branch.condition;
  460. new_block.branch.kills = block.branch.kill;
  461. new_block.branch.address = block.branch.address;
  462. }
  463. result_out.end = std::max(result_out.end, block.end);
  464. result_out.blocks.push_back(new_block);
  465. }
  466. if (result_out.decompilable) {
  467. result_out.labels = std::move(state.labels);
  468. return {result_out};
  469. }
  470. // If it's not decompilable, merge the unlabelled blocks together
  471. auto back = result_out.blocks.begin();
  472. auto next = std::next(back);
  473. while (next != result_out.blocks.end()) {
  474. if (state.labels.count(next->start) == 0 && next->start == back->end + 1) {
  475. back->end = next->end;
  476. next = result_out.blocks.erase(next);
  477. continue;
  478. }
  479. back = next;
  480. next++;
  481. }
  482. return {result_out};
  483. }
  484. } // namespace VideoCommon::Shader