decode.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // Copyright 2018 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <cstring>
  5. #include <set>
  6. #include <fmt/format.h>
  7. #include "common/assert.h"
  8. #include "common/common_types.h"
  9. #include "video_core/engines/shader_bytecode.h"
  10. #include "video_core/engines/shader_header.h"
  11. #include "video_core/shader/control_flow.h"
  12. #include "video_core/shader/node_helper.h"
  13. #include "video_core/shader/shader_ir.h"
  14. namespace VideoCommon::Shader {
  15. using Tegra::Shader::Instruction;
  16. using Tegra::Shader::OpCode;
  17. namespace {
  18. /**
  19. * Returns whether the instruction at the specified offset is a 'sched' instruction.
  20. * Sched instructions always appear before a sequence of 3 instructions.
  21. */
  22. constexpr bool IsSchedInstruction(u32 offset, u32 main_offset) {
  23. constexpr u32 SchedPeriod = 4;
  24. u32 absolute_offset = offset - main_offset;
  25. return (absolute_offset % SchedPeriod) == 0;
  26. }
  27. } // Anonymous namespace
  28. class ASTDecoder {
  29. public:
  30. ASTDecoder(ShaderIR& ir) : ir(ir) {}
  31. void operator()(ASTProgram& ast) {
  32. ASTNode current = ast.nodes.GetFirst();
  33. while (current) {
  34. Visit(current);
  35. current = current->GetNext();
  36. }
  37. }
  38. void operator()(ASTIfThen& ast) {
  39. ASTNode current = ast.nodes.GetFirst();
  40. while (current) {
  41. Visit(current);
  42. current = current->GetNext();
  43. }
  44. }
  45. void operator()(ASTIfElse& ast) {
  46. ASTNode current = ast.nodes.GetFirst();
  47. while (current) {
  48. Visit(current);
  49. current = current->GetNext();
  50. }
  51. }
  52. void operator()(ASTBlockEncoded& ast) {}
  53. void operator()(ASTBlockDecoded& ast) {}
  54. void operator()(ASTVarSet& ast) {}
  55. void operator()(ASTLabel& ast) {}
  56. void operator()(ASTGoto& ast) {}
  57. void operator()(ASTDoWhile& ast) {
  58. ASTNode current = ast.nodes.GetFirst();
  59. while (current) {
  60. Visit(current);
  61. current = current->GetNext();
  62. }
  63. }
  64. void operator()(ASTReturn& ast) {}
  65. void operator()(ASTBreak& ast) {}
  66. void Visit(ASTNode& node) {
  67. std::visit(*this, *node->GetInnerData());
  68. if (node->IsBlockEncoded()) {
  69. auto block = std::get_if<ASTBlockEncoded>(node->GetInnerData());
  70. NodeBlock bb = ir.DecodeRange(block->start, block->end);
  71. node->TransformBlockEncoded(std::move(bb));
  72. }
  73. }
  74. private:
  75. ShaderIR& ir;
  76. };
  77. void ShaderIR::Decode() {
  78. std::memcpy(&header, program_code.data(), sizeof(Tegra::Shader::Header));
  79. decompiled = false;
  80. auto info = ScanFlow(program_code, main_offset, settings, locker);
  81. auto& shader_info = *info;
  82. coverage_begin = shader_info.start;
  83. coverage_end = shader_info.end;
  84. switch (shader_info.settings.depth) {
  85. case CompileDepth::FlowStack: {
  86. for (const auto& block : shader_info.blocks) {
  87. basic_blocks.insert({block.start, DecodeRange(block.start, block.end + 1)});
  88. }
  89. break;
  90. }
  91. case CompileDepth::NoFlowStack: {
  92. disable_flow_stack = true;
  93. const auto insert_block = [this](NodeBlock& nodes, u32 label) {
  94. if (label == static_cast<u32>(exit_branch)) {
  95. return;
  96. }
  97. basic_blocks.insert({label, nodes});
  98. };
  99. const auto& blocks = shader_info.blocks;
  100. NodeBlock current_block;
  101. u32 current_label = static_cast<u32>(exit_branch);
  102. for (auto& block : blocks) {
  103. if (shader_info.labels.count(block.start) != 0) {
  104. insert_block(current_block, current_label);
  105. current_block.clear();
  106. current_label = block.start;
  107. }
  108. if (!block.ignore_branch) {
  109. DecodeRangeInner(current_block, block.start, block.end);
  110. InsertControlFlow(current_block, block);
  111. } else {
  112. DecodeRangeInner(current_block, block.start, block.end + 1);
  113. }
  114. }
  115. insert_block(current_block, current_label);
  116. break;
  117. }
  118. case CompileDepth::DecompileBackwards:
  119. case CompileDepth::FullDecompile: {
  120. program_manager = std::move(shader_info.manager);
  121. disable_flow_stack = true;
  122. decompiled = true;
  123. ASTDecoder decoder{*this};
  124. ASTNode program = GetASTProgram();
  125. decoder.Visit(program);
  126. break;
  127. }
  128. default:
  129. LOG_CRITICAL(HW_GPU, "Unknown decompilation mode!");
  130. [[fallthrough]];
  131. case CompileDepth::BruteForce: {
  132. const auto shader_end = static_cast<u32>(program_code.size());
  133. coverage_begin = main_offset;
  134. coverage_end = shader_end;
  135. for (u32 label = main_offset; label < shader_end; ++label) {
  136. basic_blocks.insert({label, DecodeRange(label, label + 1)});
  137. }
  138. break;
  139. }
  140. }
  141. if (settings.depth != shader_info.settings.depth) {
  142. LOG_WARNING(
  143. HW_GPU, "Decompiling to this setting \"{}\" failed, downgrading to this setting \"{}\"",
  144. CompileDepthAsString(settings.depth), CompileDepthAsString(shader_info.settings.depth));
  145. }
  146. }
  147. NodeBlock ShaderIR::DecodeRange(u32 begin, u32 end) {
  148. NodeBlock basic_block;
  149. DecodeRangeInner(basic_block, begin, end);
  150. return basic_block;
  151. }
  152. void ShaderIR::DecodeRangeInner(NodeBlock& bb, u32 begin, u32 end) {
  153. for (u32 pc = begin; pc < (begin > end ? MAX_PROGRAM_LENGTH : end);) {
  154. pc = DecodeInstr(bb, pc);
  155. }
  156. }
  157. void ShaderIR::InsertControlFlow(NodeBlock& bb, const ShaderBlock& block) {
  158. const auto apply_conditions = [&](const Condition& cond, Node n) -> Node {
  159. Node result = n;
  160. if (cond.cc != ConditionCode::T) {
  161. result = Conditional(GetConditionCode(cond.cc), {result});
  162. }
  163. if (cond.predicate != Pred::UnusedIndex) {
  164. u32 pred = static_cast<u32>(cond.predicate);
  165. const bool is_neg = pred > 7;
  166. if (is_neg) {
  167. pred -= 8;
  168. }
  169. result = Conditional(GetPredicate(pred, is_neg), {result});
  170. }
  171. return result;
  172. };
  173. if (std::holds_alternative<SingleBranch>(*block.branch)) {
  174. auto branch = std::get_if<SingleBranch>(block.branch.get());
  175. if (branch->address < 0) {
  176. if (branch->kill) {
  177. Node n = Operation(OperationCode::Discard);
  178. n = apply_conditions(branch->condition, n);
  179. bb.push_back(n);
  180. global_code.push_back(n);
  181. return;
  182. }
  183. Node n = Operation(OperationCode::Exit);
  184. n = apply_conditions(branch->condition, n);
  185. bb.push_back(n);
  186. global_code.push_back(n);
  187. return;
  188. }
  189. Node n = Operation(OperationCode::Branch, Immediate(branch->address));
  190. n = apply_conditions(branch->condition, n);
  191. bb.push_back(n);
  192. global_code.push_back(n);
  193. return;
  194. }
  195. auto multi_branch = std::get_if<MultiBranch>(block.branch.get());
  196. Node op_a = GetRegister(multi_branch->gpr);
  197. for (auto& branch_case : multi_branch->branches) {
  198. Node n = Operation(OperationCode::Branch, Immediate(branch_case.address));
  199. Node op_b = Immediate(branch_case.cmp_value);
  200. Node condition =
  201. GetPredicateComparisonInteger(Tegra::Shader::PredCondition::Equal, false, op_a, op_b);
  202. auto result = Conditional(condition, {n});
  203. bb.push_back(result);
  204. global_code.push_back(result);
  205. }
  206. }
  207. u32 ShaderIR::DecodeInstr(NodeBlock& bb, u32 pc) {
  208. // Ignore sched instructions when generating code.
  209. if (IsSchedInstruction(pc, main_offset)) {
  210. return pc + 1;
  211. }
  212. const Instruction instr = {program_code[pc]};
  213. const auto opcode = OpCode::Decode(instr);
  214. const u32 nv_address = ConvertAddressToNvidiaSpace(pc);
  215. // Decoding failure
  216. if (!opcode) {
  217. UNIMPLEMENTED_MSG("Unhandled instruction: {0:x}", instr.value);
  218. bb.push_back(Comment(fmt::format("{:05x} Unimplemented Shader instruction (0x{:016x})",
  219. nv_address, instr.value)));
  220. return pc + 1;
  221. }
  222. bb.push_back(Comment(
  223. fmt::format("{:05x} {} (0x{:016x})", nv_address, opcode->get().GetName(), instr.value)));
  224. using Tegra::Shader::Pred;
  225. UNIMPLEMENTED_IF_MSG(instr.pred.full_pred == Pred::NeverExecute,
  226. "NeverExecute predicate not implemented");
  227. static const std::map<OpCode::Type, u32 (ShaderIR::*)(NodeBlock&, u32)> decoders = {
  228. {OpCode::Type::Arithmetic, &ShaderIR::DecodeArithmetic},
  229. {OpCode::Type::ArithmeticImmediate, &ShaderIR::DecodeArithmeticImmediate},
  230. {OpCode::Type::Bfe, &ShaderIR::DecodeBfe},
  231. {OpCode::Type::Bfi, &ShaderIR::DecodeBfi},
  232. {OpCode::Type::Shift, &ShaderIR::DecodeShift},
  233. {OpCode::Type::ArithmeticInteger, &ShaderIR::DecodeArithmeticInteger},
  234. {OpCode::Type::ArithmeticIntegerImmediate, &ShaderIR::DecodeArithmeticIntegerImmediate},
  235. {OpCode::Type::ArithmeticHalf, &ShaderIR::DecodeArithmeticHalf},
  236. {OpCode::Type::ArithmeticHalfImmediate, &ShaderIR::DecodeArithmeticHalfImmediate},
  237. {OpCode::Type::Ffma, &ShaderIR::DecodeFfma},
  238. {OpCode::Type::Hfma2, &ShaderIR::DecodeHfma2},
  239. {OpCode::Type::Conversion, &ShaderIR::DecodeConversion},
  240. {OpCode::Type::Warp, &ShaderIR::DecodeWarp},
  241. {OpCode::Type::Memory, &ShaderIR::DecodeMemory},
  242. {OpCode::Type::Texture, &ShaderIR::DecodeTexture},
  243. {OpCode::Type::Image, &ShaderIR::DecodeImage},
  244. {OpCode::Type::FloatSetPredicate, &ShaderIR::DecodeFloatSetPredicate},
  245. {OpCode::Type::IntegerSetPredicate, &ShaderIR::DecodeIntegerSetPredicate},
  246. {OpCode::Type::HalfSetPredicate, &ShaderIR::DecodeHalfSetPredicate},
  247. {OpCode::Type::PredicateSetRegister, &ShaderIR::DecodePredicateSetRegister},
  248. {OpCode::Type::PredicateSetPredicate, &ShaderIR::DecodePredicateSetPredicate},
  249. {OpCode::Type::RegisterSetPredicate, &ShaderIR::DecodeRegisterSetPredicate},
  250. {OpCode::Type::FloatSet, &ShaderIR::DecodeFloatSet},
  251. {OpCode::Type::IntegerSet, &ShaderIR::DecodeIntegerSet},
  252. {OpCode::Type::HalfSet, &ShaderIR::DecodeHalfSet},
  253. {OpCode::Type::Video, &ShaderIR::DecodeVideo},
  254. {OpCode::Type::Xmad, &ShaderIR::DecodeXmad},
  255. };
  256. std::vector<Node> tmp_block;
  257. if (const auto decoder = decoders.find(opcode->get().GetType()); decoder != decoders.end()) {
  258. pc = (this->*decoder->second)(tmp_block, pc);
  259. } else {
  260. pc = DecodeOther(tmp_block, pc);
  261. }
  262. // Some instructions (like SSY) don't have a predicate field, they are always unconditionally
  263. // executed.
  264. const bool can_be_predicated = OpCode::IsPredicatedInstruction(opcode->get().GetId());
  265. const auto pred_index = static_cast<u32>(instr.pred.pred_index);
  266. if (can_be_predicated && pred_index != static_cast<u32>(Pred::UnusedIndex)) {
  267. const Node conditional =
  268. Conditional(GetPredicate(pred_index, instr.negate_pred != 0), std::move(tmp_block));
  269. global_code.push_back(conditional);
  270. bb.push_back(conditional);
  271. } else {
  272. for (auto& node : tmp_block) {
  273. global_code.push_back(node);
  274. bb.push_back(node);
  275. }
  276. }
  277. return pc + 1;
  278. }
  279. } // namespace VideoCommon::Shader