decode.cpp 13 KB

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