decode.cpp 13 KB

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