shader_environment.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project & 2024 suyu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <filesystem>
  5. #include <fstream>
  6. #include <memory>
  7. #include <optional>
  8. #include <utility>
  9. #include "common/assert.h"
  10. #include "common/cityhash.h"
  11. #include "common/common_types.h"
  12. #include "common/div_ceil.h"
  13. #include "common/fs/fs.h"
  14. #include "common/fs/path_util.h"
  15. #include "common/logging/log.h"
  16. #include "common/polyfill_ranges.h"
  17. #include "shader_recompiler/environment.h"
  18. #include "video_core/engines/kepler_compute.h"
  19. #include "video_core/memory_manager.h"
  20. #include "video_core/shader_environment.h"
  21. #include "video_core/texture_cache/format_lookup_table.h"
  22. #include "video_core/textures/texture.h"
  23. namespace VideoCommon {
  24. constexpr std::array<char, 8> MAGIC_NUMBER{'y', 'u', 'z', 'u', 'c', 'a', 'c', 'h'};
  25. constexpr size_t INST_SIZE = sizeof(u64);
  26. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  27. static u64 MakeCbufKey(u32 index, u32 offset) {
  28. return (static_cast<u64>(index) << 32) | offset;
  29. }
  30. static Shader::TextureType ConvertTextureType(const Tegra::Texture::TICEntry& entry) {
  31. switch (entry.texture_type) {
  32. case Tegra::Texture::TextureType::Texture1D:
  33. return Shader::TextureType::Color1D;
  34. case Tegra::Texture::TextureType::Texture2D:
  35. case Tegra::Texture::TextureType::Texture2DNoMipmap:
  36. return entry.normalized_coords ? Shader::TextureType::Color2D
  37. : Shader::TextureType::Color2DRect;
  38. case Tegra::Texture::TextureType::Texture3D:
  39. return Shader::TextureType::Color3D;
  40. case Tegra::Texture::TextureType::TextureCubemap:
  41. return Shader::TextureType::ColorCube;
  42. case Tegra::Texture::TextureType::Texture1DArray:
  43. return Shader::TextureType::ColorArray1D;
  44. case Tegra::Texture::TextureType::Texture2DArray:
  45. return Shader::TextureType::ColorArray2D;
  46. case Tegra::Texture::TextureType::Texture1DBuffer:
  47. return Shader::TextureType::Buffer;
  48. case Tegra::Texture::TextureType::TextureCubeArray:
  49. return Shader::TextureType::ColorArrayCube;
  50. default:
  51. UNIMPLEMENTED();
  52. return Shader::TextureType::Color2D;
  53. }
  54. }
  55. static Shader::TexturePixelFormat ConvertTexturePixelFormat(const Tegra::Texture::TICEntry& entry) {
  56. return static_cast<Shader::TexturePixelFormat>(
  57. PixelFormatFromTextureInfo(entry.format, entry.r_type, entry.g_type, entry.b_type,
  58. entry.a_type, entry.srgb_conversion));
  59. }
  60. static std::string_view StageToPrefix(Shader::Stage stage) {
  61. switch (stage) {
  62. case Shader::Stage::VertexB:
  63. return "VB";
  64. case Shader::Stage::TessellationControl:
  65. return "TC";
  66. case Shader::Stage::TessellationEval:
  67. return "TE";
  68. case Shader::Stage::Geometry:
  69. return "GS";
  70. case Shader::Stage::Fragment:
  71. return "FS";
  72. case Shader::Stage::Compute:
  73. return "CS";
  74. case Shader::Stage::VertexA:
  75. return "VA";
  76. default:
  77. return "UK";
  78. }
  79. }
  80. static void DumpImpl(u64 pipeline_hash, u64 shader_hash, std::span<const u64> code,
  81. [[maybe_unused]] u32 read_highest, [[maybe_unused]] u32 read_lowest,
  82. u32 initial_offset, Shader::Stage stage) {
  83. const auto shader_dir{Common::FS::GetSuyuPath(Common::FS::SuyuPath::DumpDir)};
  84. const auto base_dir{shader_dir / "shaders"};
  85. if (!Common::FS::CreateDir(shader_dir) || !Common::FS::CreateDir(base_dir)) {
  86. LOG_ERROR(Common_Filesystem, "Failed to create shader dump directories");
  87. return;
  88. }
  89. const auto prefix = StageToPrefix(stage);
  90. const auto name{base_dir /
  91. fmt::format("{:016x}_{}_{:016x}.ash", pipeline_hash, prefix, shader_hash)};
  92. std::fstream shader_file(name, std::ios::out | std::ios::binary);
  93. ASSERT(initial_offset % sizeof(u64) == 0);
  94. const size_t jump_index = initial_offset / sizeof(u64);
  95. const size_t code_size = code.size_bytes() - initial_offset;
  96. shader_file.write(reinterpret_cast<const char*>(&code[jump_index]), code_size);
  97. // + 1 instruction, due to the fact that we skip the final self branch instruction in the code,
  98. // but we need to consider it for padding, otherwise nvdisasm rages.
  99. const size_t padding_needed = (32 - ((code_size + INST_SIZE) % 32)) % 32;
  100. for (size_t i = 0; i < INST_SIZE + padding_needed; i++) {
  101. shader_file.put(0);
  102. }
  103. }
  104. GenericEnvironment::GenericEnvironment(Tegra::MemoryManager& gpu_memory_, GPUVAddr program_base_,
  105. u32 start_address_)
  106. : gpu_memory{&gpu_memory_}, program_base{program_base_} {
  107. start_address = start_address_;
  108. }
  109. GenericEnvironment::~GenericEnvironment() = default;
  110. u32 GenericEnvironment::TextureBoundBuffer() const {
  111. return texture_bound;
  112. }
  113. u32 GenericEnvironment::LocalMemorySize() const {
  114. return local_memory_size;
  115. }
  116. u32 GenericEnvironment::SharedMemorySize() const {
  117. return shared_memory_size;
  118. }
  119. std::array<u32, 3> GenericEnvironment::WorkgroupSize() const {
  120. return workgroup_size;
  121. }
  122. u64 GenericEnvironment::ReadInstruction(u32 address) {
  123. read_lowest = std::min(read_lowest, address);
  124. read_highest = std::max(read_highest, address);
  125. if (address >= cached_lowest && address < cached_highest) {
  126. return code[(address - cached_lowest) / INST_SIZE];
  127. }
  128. has_unbound_instructions = true;
  129. return gpu_memory->Read<u64>(program_base + address);
  130. }
  131. std::optional<u64> GenericEnvironment::Analyze() {
  132. const std::optional<u64> size{TryFindSize()};
  133. if (!size) {
  134. return std::nullopt;
  135. }
  136. cached_lowest = start_address;
  137. cached_highest = start_address + static_cast<u32>(*size);
  138. return Common::CityHash64(reinterpret_cast<const char*>(code.data()), *size);
  139. }
  140. void GenericEnvironment::SetCachedSize(size_t size_bytes) {
  141. cached_lowest = start_address;
  142. cached_highest = start_address + static_cast<u32>(size_bytes);
  143. code.resize(CachedSizeWords());
  144. gpu_memory->ReadBlock(program_base + cached_lowest, code.data(), code.size() * sizeof(u64));
  145. }
  146. size_t GenericEnvironment::CachedSizeWords() const noexcept {
  147. return CachedSizeBytes() / INST_SIZE;
  148. }
  149. size_t GenericEnvironment::CachedSizeBytes() const noexcept {
  150. return static_cast<size_t>(cached_highest) - cached_lowest + INST_SIZE;
  151. }
  152. size_t GenericEnvironment::ReadSizeBytes() const noexcept {
  153. return read_highest - read_lowest + INST_SIZE;
  154. }
  155. bool GenericEnvironment::CanBeSerialized() const noexcept {
  156. return !has_unbound_instructions;
  157. }
  158. u64 GenericEnvironment::CalculateHash() const {
  159. const size_t size{ReadSizeBytes()};
  160. const auto data{std::make_unique<char[]>(size)};
  161. gpu_memory->ReadBlock(program_base + read_lowest, data.get(), size);
  162. return Common::CityHash64(data.get(), size);
  163. }
  164. void GenericEnvironment::Dump(u64 pipeline_hash, u64 shader_hash) {
  165. DumpImpl(pipeline_hash, shader_hash, code, read_highest, read_lowest, initial_offset, stage);
  166. }
  167. void GenericEnvironment::Serialize(std::ofstream& file) const {
  168. const u64 code_size{static_cast<u64>(CachedSizeBytes())};
  169. const u64 num_texture_types{static_cast<u64>(texture_types.size())};
  170. const u64 num_texture_pixel_formats{static_cast<u64>(texture_pixel_formats.size())};
  171. const u64 num_cbuf_values{static_cast<u64>(cbuf_values.size())};
  172. const u64 num_cbuf_replacement_values{static_cast<u64>(cbuf_replacements.size())};
  173. file.write(reinterpret_cast<const char*>(&code_size), sizeof(code_size))
  174. .write(reinterpret_cast<const char*>(&num_texture_types), sizeof(num_texture_types))
  175. .write(reinterpret_cast<const char*>(&num_texture_pixel_formats),
  176. sizeof(num_texture_pixel_formats))
  177. .write(reinterpret_cast<const char*>(&num_cbuf_values), sizeof(num_cbuf_values))
  178. .write(reinterpret_cast<const char*>(&num_cbuf_replacement_values),
  179. sizeof(num_cbuf_replacement_values))
  180. .write(reinterpret_cast<const char*>(&local_memory_size), sizeof(local_memory_size))
  181. .write(reinterpret_cast<const char*>(&texture_bound), sizeof(texture_bound))
  182. .write(reinterpret_cast<const char*>(&start_address), sizeof(start_address))
  183. .write(reinterpret_cast<const char*>(&cached_lowest), sizeof(cached_lowest))
  184. .write(reinterpret_cast<const char*>(&cached_highest), sizeof(cached_highest))
  185. .write(reinterpret_cast<const char*>(&viewport_transform_state),
  186. sizeof(viewport_transform_state))
  187. .write(reinterpret_cast<const char*>(&stage), sizeof(stage))
  188. .write(reinterpret_cast<const char*>(code.data()), code_size);
  189. for (const auto& [key, type] : texture_types) {
  190. file.write(reinterpret_cast<const char*>(&key), sizeof(key))
  191. .write(reinterpret_cast<const char*>(&type), sizeof(type));
  192. }
  193. for (const auto& [key, format] : texture_pixel_formats) {
  194. file.write(reinterpret_cast<const char*>(&key), sizeof(key))
  195. .write(reinterpret_cast<const char*>(&format), sizeof(format));
  196. }
  197. for (const auto& [key, type] : cbuf_values) {
  198. file.write(reinterpret_cast<const char*>(&key), sizeof(key))
  199. .write(reinterpret_cast<const char*>(&type), sizeof(type));
  200. }
  201. for (const auto& [key, type] : cbuf_replacements) {
  202. file.write(reinterpret_cast<const char*>(&key), sizeof(key))
  203. .write(reinterpret_cast<const char*>(&type), sizeof(type));
  204. }
  205. if (stage == Shader::Stage::Compute) {
  206. file.write(reinterpret_cast<const char*>(&workgroup_size), sizeof(workgroup_size))
  207. .write(reinterpret_cast<const char*>(&shared_memory_size), sizeof(shared_memory_size));
  208. } else {
  209. file.write(reinterpret_cast<const char*>(&sph), sizeof(sph));
  210. if (stage == Shader::Stage::Geometry) {
  211. file.write(reinterpret_cast<const char*>(&gp_passthrough_mask),
  212. sizeof(gp_passthrough_mask));
  213. }
  214. }
  215. }
  216. std::optional<u64> GenericEnvironment::TryFindSize() {
  217. static constexpr size_t BLOCK_SIZE = 0x1000;
  218. static constexpr size_t MAXIMUM_SIZE = 0x100000;
  219. static constexpr u64 SELF_BRANCH_A = 0xE2400FFFFF87000FULL;
  220. static constexpr u64 SELF_BRANCH_B = 0xE2400FFFFF07000FULL;
  221. GPUVAddr guest_addr{program_base + start_address};
  222. size_t offset{0};
  223. size_t size{BLOCK_SIZE};
  224. while (size <= MAXIMUM_SIZE) {
  225. code.resize(size / INST_SIZE);
  226. u64* const data = code.data() + offset / INST_SIZE;
  227. gpu_memory->ReadBlock(guest_addr, data, BLOCK_SIZE);
  228. for (size_t index = 0; index < BLOCK_SIZE; index += INST_SIZE) {
  229. const u64 inst = data[index / INST_SIZE];
  230. if (inst == SELF_BRANCH_A || inst == SELF_BRANCH_B) {
  231. return offset + index;
  232. }
  233. }
  234. guest_addr += BLOCK_SIZE;
  235. size += BLOCK_SIZE;
  236. offset += BLOCK_SIZE;
  237. }
  238. return std::nullopt;
  239. }
  240. Tegra::Texture::TICEntry GenericEnvironment::ReadTextureInfo(GPUVAddr tic_addr, u32 tic_limit,
  241. bool via_header_index, u32 raw) {
  242. const auto handle{Tegra::Texture::TexturePair(raw, via_header_index)};
  243. ASSERT(handle.first <= tic_limit);
  244. const GPUVAddr descriptor_addr{tic_addr + handle.first * sizeof(Tegra::Texture::TICEntry)};
  245. Tegra::Texture::TICEntry entry;
  246. gpu_memory->ReadBlock(descriptor_addr, &entry, sizeof(entry));
  247. return entry;
  248. }
  249. GraphicsEnvironment::GraphicsEnvironment(Tegra::Engines::Maxwell3D& maxwell3d_,
  250. Tegra::MemoryManager& gpu_memory_,
  251. Maxwell::ShaderType program, GPUVAddr program_base_,
  252. u32 start_address_)
  253. : GenericEnvironment{gpu_memory_, program_base_, start_address_}, maxwell3d{&maxwell3d_} {
  254. gpu_memory->ReadBlock(program_base + start_address, &sph, sizeof(sph));
  255. initial_offset = sizeof(sph);
  256. gp_passthrough_mask = maxwell3d->regs.post_vtg_shader_attrib_skip_mask;
  257. switch (program) {
  258. case Maxwell::ShaderType::VertexA:
  259. stage = Shader::Stage::VertexA;
  260. stage_index = 0;
  261. break;
  262. case Maxwell::ShaderType::VertexB:
  263. stage = Shader::Stage::VertexB;
  264. stage_index = 0;
  265. break;
  266. case Maxwell::ShaderType::TessellationInit:
  267. stage = Shader::Stage::TessellationControl;
  268. stage_index = 1;
  269. break;
  270. case Maxwell::ShaderType::Tessellation:
  271. stage = Shader::Stage::TessellationEval;
  272. stage_index = 2;
  273. break;
  274. case Maxwell::ShaderType::Geometry:
  275. stage = Shader::Stage::Geometry;
  276. stage_index = 3;
  277. break;
  278. case Maxwell::ShaderType::Pixel:
  279. stage = Shader::Stage::Fragment;
  280. stage_index = 4;
  281. break;
  282. default:
  283. ASSERT_MSG(false, "Invalid program={}", program);
  284. break;
  285. }
  286. const u64 local_size{sph.LocalMemorySize()};
  287. ASSERT(local_size <= std::numeric_limits<u32>::max());
  288. local_memory_size = static_cast<u32>(local_size) + sph.common3.shader_local_memory_crs_size;
  289. texture_bound = maxwell3d->regs.bindless_texture_const_buffer_slot;
  290. is_proprietary_driver = texture_bound == 2;
  291. has_hle_engine_state =
  292. maxwell3d->engine_state == Tegra::Engines::Maxwell3D::EngineHint::OnHLEMacro;
  293. }
  294. u32 GraphicsEnvironment::ReadCbufValue(u32 cbuf_index, u32 cbuf_offset) {
  295. const auto& cbuf{maxwell3d->state.shader_stages[stage_index].const_buffers[cbuf_index]};
  296. ASSERT(cbuf.enabled);
  297. u32 value{};
  298. if (cbuf_offset < cbuf.size) {
  299. value = gpu_memory->Read<u32>(cbuf.address + cbuf_offset);
  300. }
  301. cbuf_values.emplace(MakeCbufKey(cbuf_index, cbuf_offset), value);
  302. return value;
  303. }
  304. std::optional<Shader::ReplaceConstant> GraphicsEnvironment::GetReplaceConstBuffer(u32 bank,
  305. u32 offset) {
  306. if (!has_hle_engine_state) {
  307. return std::nullopt;
  308. }
  309. const u64 key = (static_cast<u64>(bank) << 32) | static_cast<u64>(offset);
  310. auto it = maxwell3d->replace_table.find(key);
  311. if (it == maxwell3d->replace_table.end()) {
  312. return std::nullopt;
  313. }
  314. const auto converted_value = [](Tegra::Engines::Maxwell3D::HLEReplacementAttributeType name) {
  315. switch (name) {
  316. case Tegra::Engines::Maxwell3D::HLEReplacementAttributeType::BaseVertex:
  317. return Shader::ReplaceConstant::BaseVertex;
  318. case Tegra::Engines::Maxwell3D::HLEReplacementAttributeType::BaseInstance:
  319. return Shader::ReplaceConstant::BaseInstance;
  320. case Tegra::Engines::Maxwell3D::HLEReplacementAttributeType::DrawID:
  321. return Shader::ReplaceConstant::DrawID;
  322. default:
  323. UNREACHABLE();
  324. }
  325. }(it->second);
  326. cbuf_replacements.emplace(key, converted_value);
  327. return converted_value;
  328. }
  329. Shader::TextureType GraphicsEnvironment::ReadTextureType(u32 handle) {
  330. const auto& regs{maxwell3d->regs};
  331. const bool via_header_index{regs.sampler_binding == Maxwell::SamplerBinding::ViaHeaderBinding};
  332. auto entry =
  333. ReadTextureInfo(regs.tex_header.Address(), regs.tex_header.limit, via_header_index, handle);
  334. const Shader::TextureType result{ConvertTextureType(entry)};
  335. texture_types.emplace(handle, result);
  336. return result;
  337. }
  338. Shader::TexturePixelFormat GraphicsEnvironment::ReadTexturePixelFormat(u32 handle) {
  339. const auto& regs{maxwell3d->regs};
  340. const bool via_header_index{regs.sampler_binding == Maxwell::SamplerBinding::ViaHeaderBinding};
  341. auto entry =
  342. ReadTextureInfo(regs.tex_header.Address(), regs.tex_header.limit, via_header_index, handle);
  343. const Shader::TexturePixelFormat result(ConvertTexturePixelFormat(entry));
  344. texture_pixel_formats.emplace(handle, result);
  345. return result;
  346. }
  347. bool GraphicsEnvironment::IsTexturePixelFormatInteger(u32 handle) {
  348. return VideoCore::Surface::IsPixelFormatInteger(
  349. static_cast<VideoCore::Surface::PixelFormat>(ReadTexturePixelFormat(handle)));
  350. }
  351. u32 GraphicsEnvironment::ReadViewportTransformState() {
  352. const auto& regs{maxwell3d->regs};
  353. viewport_transform_state = regs.viewport_scale_offset_enabled;
  354. return viewport_transform_state;
  355. }
  356. ComputeEnvironment::ComputeEnvironment(Tegra::Engines::KeplerCompute& kepler_compute_,
  357. Tegra::MemoryManager& gpu_memory_, GPUVAddr program_base_,
  358. u32 start_address_)
  359. : GenericEnvironment{gpu_memory_, program_base_, start_address_},
  360. kepler_compute{&kepler_compute_} {
  361. const auto& qmd{kepler_compute->launch_description};
  362. stage = Shader::Stage::Compute;
  363. local_memory_size = qmd.local_pos_alloc + qmd.local_crs_alloc;
  364. texture_bound = kepler_compute->regs.tex_cb_index;
  365. is_proprietary_driver = texture_bound == 2;
  366. shared_memory_size = qmd.shared_alloc;
  367. workgroup_size = {qmd.block_dim_x, qmd.block_dim_y, qmd.block_dim_z};
  368. }
  369. u32 ComputeEnvironment::ReadCbufValue(u32 cbuf_index, u32 cbuf_offset) {
  370. const auto& qmd{kepler_compute->launch_description};
  371. ASSERT(((qmd.const_buffer_enable_mask.Value() >> cbuf_index) & 1) != 0);
  372. const auto& cbuf{qmd.const_buffer_config[cbuf_index]};
  373. u32 value{};
  374. if (cbuf_offset < cbuf.size) {
  375. value = gpu_memory->Read<u32>(cbuf.Address() + cbuf_offset);
  376. }
  377. cbuf_values.emplace(MakeCbufKey(cbuf_index, cbuf_offset), value);
  378. return value;
  379. }
  380. Shader::TextureType ComputeEnvironment::ReadTextureType(u32 handle) {
  381. const auto& regs{kepler_compute->regs};
  382. const auto& qmd{kepler_compute->launch_description};
  383. auto entry = ReadTextureInfo(regs.tic.Address(), regs.tic.limit, qmd.linked_tsc != 0, handle);
  384. const Shader::TextureType result{ConvertTextureType(entry)};
  385. texture_types.emplace(handle, result);
  386. return result;
  387. }
  388. Shader::TexturePixelFormat ComputeEnvironment::ReadTexturePixelFormat(u32 handle) {
  389. const auto& regs{kepler_compute->regs};
  390. const auto& qmd{kepler_compute->launch_description};
  391. auto entry = ReadTextureInfo(regs.tic.Address(), regs.tic.limit, qmd.linked_tsc != 0, handle);
  392. const Shader::TexturePixelFormat result(ConvertTexturePixelFormat(entry));
  393. texture_pixel_formats.emplace(handle, result);
  394. return result;
  395. }
  396. bool ComputeEnvironment::IsTexturePixelFormatInteger(u32 handle) {
  397. return VideoCore::Surface::IsPixelFormatInteger(
  398. static_cast<VideoCore::Surface::PixelFormat>(ReadTexturePixelFormat(handle)));
  399. }
  400. u32 ComputeEnvironment::ReadViewportTransformState() {
  401. return viewport_transform_state;
  402. }
  403. void FileEnvironment::Deserialize(std::ifstream& file) {
  404. u64 code_size{};
  405. u64 num_texture_types{};
  406. u64 num_texture_pixel_formats{};
  407. u64 num_cbuf_values{};
  408. u64 num_cbuf_replacement_values{};
  409. file.read(reinterpret_cast<char*>(&code_size), sizeof(code_size))
  410. .read(reinterpret_cast<char*>(&num_texture_types), sizeof(num_texture_types))
  411. .read(reinterpret_cast<char*>(&num_texture_pixel_formats),
  412. sizeof(num_texture_pixel_formats))
  413. .read(reinterpret_cast<char*>(&num_cbuf_values), sizeof(num_cbuf_values))
  414. .read(reinterpret_cast<char*>(&num_cbuf_replacement_values),
  415. sizeof(num_cbuf_replacement_values))
  416. .read(reinterpret_cast<char*>(&local_memory_size), sizeof(local_memory_size))
  417. .read(reinterpret_cast<char*>(&texture_bound), sizeof(texture_bound))
  418. .read(reinterpret_cast<char*>(&start_address), sizeof(start_address))
  419. .read(reinterpret_cast<char*>(&read_lowest), sizeof(read_lowest))
  420. .read(reinterpret_cast<char*>(&read_highest), sizeof(read_highest))
  421. .read(reinterpret_cast<char*>(&viewport_transform_state), sizeof(viewport_transform_state))
  422. .read(reinterpret_cast<char*>(&stage), sizeof(stage));
  423. code.resize(Common::DivCeil(code_size, sizeof(u64)));
  424. file.read(reinterpret_cast<char*>(code.data()), code_size);
  425. for (size_t i = 0; i < num_texture_types; ++i) {
  426. u32 key;
  427. Shader::TextureType type;
  428. file.read(reinterpret_cast<char*>(&key), sizeof(key))
  429. .read(reinterpret_cast<char*>(&type), sizeof(type));
  430. texture_types.emplace(key, type);
  431. }
  432. for (size_t i = 0; i < num_texture_pixel_formats; ++i) {
  433. u32 key;
  434. Shader::TexturePixelFormat format;
  435. file.read(reinterpret_cast<char*>(&key), sizeof(key))
  436. .read(reinterpret_cast<char*>(&format), sizeof(format));
  437. texture_pixel_formats.emplace(key, format);
  438. }
  439. for (size_t i = 0; i < num_cbuf_values; ++i) {
  440. u64 key;
  441. u32 value;
  442. file.read(reinterpret_cast<char*>(&key), sizeof(key))
  443. .read(reinterpret_cast<char*>(&value), sizeof(value));
  444. cbuf_values.emplace(key, value);
  445. }
  446. for (size_t i = 0; i < num_cbuf_replacement_values; ++i) {
  447. u64 key;
  448. Shader::ReplaceConstant value;
  449. file.read(reinterpret_cast<char*>(&key), sizeof(key))
  450. .read(reinterpret_cast<char*>(&value), sizeof(value));
  451. cbuf_replacements.emplace(key, value);
  452. }
  453. if (stage == Shader::Stage::Compute) {
  454. file.read(reinterpret_cast<char*>(&workgroup_size), sizeof(workgroup_size))
  455. .read(reinterpret_cast<char*>(&shared_memory_size), sizeof(shared_memory_size));
  456. initial_offset = 0;
  457. } else {
  458. file.read(reinterpret_cast<char*>(&sph), sizeof(sph));
  459. initial_offset = sizeof(sph);
  460. if (stage == Shader::Stage::Geometry) {
  461. file.read(reinterpret_cast<char*>(&gp_passthrough_mask), sizeof(gp_passthrough_mask));
  462. }
  463. }
  464. is_proprietary_driver = texture_bound == 2;
  465. }
  466. void FileEnvironment::Dump(u64 pipeline_hash, u64 shader_hash) {
  467. DumpImpl(pipeline_hash, shader_hash, code, read_highest, read_lowest, initial_offset, stage);
  468. }
  469. u64 FileEnvironment::ReadInstruction(u32 address) {
  470. if (address < read_lowest || address > read_highest) {
  471. throw Shader::LogicError("Out of bounds address {}", address);
  472. }
  473. return code[(address - read_lowest) / sizeof(u64)];
  474. }
  475. u32 FileEnvironment::ReadCbufValue(u32 cbuf_index, u32 cbuf_offset) {
  476. const auto it{cbuf_values.find(MakeCbufKey(cbuf_index, cbuf_offset))};
  477. if (it == cbuf_values.end()) {
  478. throw Shader::LogicError("Uncached read texture type");
  479. }
  480. return it->second;
  481. }
  482. Shader::TextureType FileEnvironment::ReadTextureType(u32 handle) {
  483. const auto it{texture_types.find(handle)};
  484. if (it == texture_types.end()) {
  485. throw Shader::LogicError("Uncached read texture type");
  486. }
  487. return it->second;
  488. }
  489. Shader::TexturePixelFormat FileEnvironment::ReadTexturePixelFormat(u32 handle) {
  490. const auto it{texture_pixel_formats.find(handle)};
  491. if (it == texture_pixel_formats.end()) {
  492. throw Shader::LogicError("Uncached read texture pixel format");
  493. }
  494. return it->second;
  495. }
  496. bool FileEnvironment::IsTexturePixelFormatInteger(u32 handle) {
  497. return VideoCore::Surface::IsPixelFormatInteger(
  498. static_cast<VideoCore::Surface::PixelFormat>(ReadTexturePixelFormat(handle)));
  499. }
  500. u32 FileEnvironment::ReadViewportTransformState() {
  501. return viewport_transform_state;
  502. }
  503. u32 FileEnvironment::LocalMemorySize() const {
  504. return local_memory_size;
  505. }
  506. u32 FileEnvironment::SharedMemorySize() const {
  507. return shared_memory_size;
  508. }
  509. u32 FileEnvironment::TextureBoundBuffer() const {
  510. return texture_bound;
  511. }
  512. std::array<u32, 3> FileEnvironment::WorkgroupSize() const {
  513. return workgroup_size;
  514. }
  515. std::optional<Shader::ReplaceConstant> FileEnvironment::GetReplaceConstBuffer(u32 bank,
  516. u32 offset) {
  517. const u64 key = (static_cast<u64>(bank) << 32) | static_cast<u64>(offset);
  518. auto it = cbuf_replacements.find(key);
  519. if (it == cbuf_replacements.end()) {
  520. return std::nullopt;
  521. }
  522. return it->second;
  523. }
  524. void SerializePipeline(std::span<const char> key, std::span<const GenericEnvironment* const> envs,
  525. const std::filesystem::path& filename, u32 cache_version) try {
  526. std::ofstream file(filename, std::ios::binary | std::ios::ate | std::ios::app);
  527. file.exceptions(std::ifstream::failbit);
  528. if (!file.is_open()) {
  529. LOG_ERROR(Common_Filesystem, "Failed to open pipeline cache file {}",
  530. Common::FS::PathToUTF8String(filename));
  531. return;
  532. }
  533. if (file.tellp() == 0) {
  534. // Write header
  535. file.write(MAGIC_NUMBER.data(), MAGIC_NUMBER.size())
  536. .write(reinterpret_cast<const char*>(&cache_version), sizeof(cache_version));
  537. }
  538. if (!std::ranges::all_of(envs, &GenericEnvironment::CanBeSerialized)) {
  539. return;
  540. }
  541. const u32 num_envs{static_cast<u32>(envs.size())};
  542. file.write(reinterpret_cast<const char*>(&num_envs), sizeof(num_envs));
  543. for (const GenericEnvironment* const env : envs) {
  544. env->Serialize(file);
  545. }
  546. file.write(key.data(), key.size_bytes());
  547. } catch (const std::ios_base::failure& e) {
  548. LOG_ERROR(Common_Filesystem, "{}", e.what());
  549. if (!Common::FS::RemoveFile(filename)) {
  550. LOG_ERROR(Common_Filesystem, "Failed to delete pipeline cache file {}",
  551. Common::FS::PathToUTF8String(filename));
  552. }
  553. }
  554. void LoadPipelines(
  555. std::stop_token stop_loading, const std::filesystem::path& filename, u32 expected_cache_version,
  556. Common::UniqueFunction<void, std::ifstream&, FileEnvironment> load_compute,
  557. Common::UniqueFunction<void, std::ifstream&, std::vector<FileEnvironment>> load_graphics) try {
  558. std::ifstream file(filename, std::ios::binary | std::ios::ate);
  559. if (!file.is_open()) {
  560. return;
  561. }
  562. file.exceptions(std::ifstream::failbit);
  563. const auto end{file.tellg()};
  564. file.seekg(0, std::ios::beg);
  565. std::array<char, 8> magic_number;
  566. u32 cache_version;
  567. file.read(magic_number.data(), magic_number.size())
  568. .read(reinterpret_cast<char*>(&cache_version), sizeof(cache_version));
  569. if (magic_number != MAGIC_NUMBER || cache_version != expected_cache_version) {
  570. file.close();
  571. if (Common::FS::RemoveFile(filename)) {
  572. if (magic_number != MAGIC_NUMBER) {
  573. LOG_ERROR(Common_Filesystem, "Invalid pipeline cache file");
  574. }
  575. if (cache_version != expected_cache_version) {
  576. LOG_INFO(Common_Filesystem, "Deleting old pipeline cache");
  577. }
  578. } else {
  579. LOG_ERROR(Common_Filesystem,
  580. "Invalid pipeline cache file and failed to delete it in \"{}\"",
  581. Common::FS::PathToUTF8String(filename));
  582. }
  583. return;
  584. }
  585. while (file.tellg() != end) {
  586. if (stop_loading.stop_requested()) {
  587. return;
  588. }
  589. u32 num_envs{};
  590. file.read(reinterpret_cast<char*>(&num_envs), sizeof(num_envs));
  591. std::vector<FileEnvironment> envs(num_envs);
  592. for (FileEnvironment& env : envs) {
  593. env.Deserialize(file);
  594. }
  595. if (envs.front().ShaderStage() == Shader::Stage::Compute) {
  596. load_compute(file, std::move(envs.front()));
  597. } else {
  598. load_graphics(file, std::move(envs));
  599. }
  600. }
  601. } catch (const std::ios_base::failure& e) {
  602. LOG_ERROR(Common_Filesystem, "{}", e.what());
  603. if (!Common::FS::RemoveFile(filename)) {
  604. LOG_ERROR(Common_Filesystem, "Failed to delete pipeline cache file {}",
  605. Common::FS::PathToUTF8String(filename));
  606. }
  607. }
  608. } // namespace VideoCommon