emit_context.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <climits>
  7. #include <string_view>
  8. #include <fmt/format.h>
  9. #include "common/common_types.h"
  10. #include "common/div_ceil.h"
  11. #include "shader_recompiler/backend/spirv/emit_context.h"
  12. namespace Shader::Backend::SPIRV {
  13. namespace {
  14. enum class Operation {
  15. Increment,
  16. Decrement,
  17. FPAdd,
  18. FPMin,
  19. FPMax,
  20. };
  21. struct AttrInfo {
  22. Id pointer;
  23. Id id;
  24. bool needs_cast;
  25. };
  26. Id ImageType(EmitContext& ctx, const TextureDescriptor& desc) {
  27. const spv::ImageFormat format{spv::ImageFormat::Unknown};
  28. const Id type{ctx.F32[1]};
  29. const bool depth{desc.is_depth};
  30. switch (desc.type) {
  31. case TextureType::Color1D:
  32. return ctx.TypeImage(type, spv::Dim::Dim1D, depth, false, false, 1, format);
  33. case TextureType::ColorArray1D:
  34. return ctx.TypeImage(type, spv::Dim::Dim1D, depth, true, false, 1, format);
  35. case TextureType::Color2D:
  36. return ctx.TypeImage(type, spv::Dim::Dim2D, depth, false, false, 1, format);
  37. case TextureType::ColorArray2D:
  38. return ctx.TypeImage(type, spv::Dim::Dim2D, depth, true, false, 1, format);
  39. case TextureType::Color3D:
  40. return ctx.TypeImage(type, spv::Dim::Dim3D, depth, false, false, 1, format);
  41. case TextureType::ColorCube:
  42. return ctx.TypeImage(type, spv::Dim::Cube, depth, false, false, 1, format);
  43. case TextureType::ColorArrayCube:
  44. return ctx.TypeImage(type, spv::Dim::Cube, depth, true, false, 1, format);
  45. case TextureType::Buffer:
  46. break;
  47. }
  48. throw InvalidArgument("Invalid texture type {}", desc.type);
  49. }
  50. spv::ImageFormat GetImageFormat(ImageFormat format) {
  51. switch (format) {
  52. case ImageFormat::Typeless:
  53. return spv::ImageFormat::Unknown;
  54. case ImageFormat::R8_UINT:
  55. return spv::ImageFormat::R8ui;
  56. case ImageFormat::R8_SINT:
  57. return spv::ImageFormat::R8i;
  58. case ImageFormat::R16_UINT:
  59. return spv::ImageFormat::R16ui;
  60. case ImageFormat::R16_SINT:
  61. return spv::ImageFormat::R16i;
  62. case ImageFormat::R32_UINT:
  63. return spv::ImageFormat::R32ui;
  64. case ImageFormat::R32G32_UINT:
  65. return spv::ImageFormat::Rg32ui;
  66. case ImageFormat::R32G32B32A32_UINT:
  67. return spv::ImageFormat::Rgba32ui;
  68. }
  69. throw InvalidArgument("Invalid image format {}", format);
  70. }
  71. Id ImageType(EmitContext& ctx, const ImageDescriptor& desc) {
  72. const spv::ImageFormat format{GetImageFormat(desc.format)};
  73. const Id type{ctx.U32[1]};
  74. switch (desc.type) {
  75. case TextureType::Color1D:
  76. return ctx.TypeImage(type, spv::Dim::Dim1D, false, false, false, 2, format);
  77. case TextureType::ColorArray1D:
  78. return ctx.TypeImage(type, spv::Dim::Dim1D, false, true, false, 2, format);
  79. case TextureType::Color2D:
  80. return ctx.TypeImage(type, spv::Dim::Dim2D, false, false, false, 2, format);
  81. case TextureType::ColorArray2D:
  82. return ctx.TypeImage(type, spv::Dim::Dim2D, false, true, false, 2, format);
  83. case TextureType::Color3D:
  84. return ctx.TypeImage(type, spv::Dim::Dim3D, false, false, false, 2, format);
  85. case TextureType::Buffer:
  86. throw NotImplementedException("Image buffer");
  87. default:
  88. break;
  89. }
  90. throw InvalidArgument("Invalid texture type {}", desc.type);
  91. }
  92. Id DefineVariable(EmitContext& ctx, Id type, std::optional<spv::BuiltIn> builtin,
  93. spv::StorageClass storage_class) {
  94. const Id pointer_type{ctx.TypePointer(storage_class, type)};
  95. const Id id{ctx.AddGlobalVariable(pointer_type, storage_class)};
  96. if (builtin) {
  97. ctx.Decorate(id, spv::Decoration::BuiltIn, *builtin);
  98. }
  99. ctx.interfaces.push_back(id);
  100. return id;
  101. }
  102. u32 NumVertices(InputTopology input_topology) {
  103. switch (input_topology) {
  104. case InputTopology::Points:
  105. return 1;
  106. case InputTopology::Lines:
  107. return 2;
  108. case InputTopology::LinesAdjacency:
  109. return 4;
  110. case InputTopology::Triangles:
  111. return 3;
  112. case InputTopology::TrianglesAdjacency:
  113. return 6;
  114. }
  115. throw InvalidArgument("Invalid input topology {}", input_topology);
  116. }
  117. Id DefineInput(EmitContext& ctx, Id type, bool per_invocation,
  118. std::optional<spv::BuiltIn> builtin = std::nullopt) {
  119. switch (ctx.stage) {
  120. case Stage::TessellationControl:
  121. case Stage::TessellationEval:
  122. if (per_invocation) {
  123. type = ctx.TypeArray(type, ctx.Constant(ctx.U32[1], 32u));
  124. }
  125. break;
  126. case Stage::Geometry:
  127. if (per_invocation) {
  128. const u32 num_vertices{NumVertices(ctx.profile.input_topology)};
  129. type = ctx.TypeArray(type, ctx.Constant(ctx.U32[1], num_vertices));
  130. }
  131. break;
  132. default:
  133. break;
  134. }
  135. return DefineVariable(ctx, type, builtin, spv::StorageClass::Input);
  136. }
  137. Id DefineOutput(EmitContext& ctx, Id type, std::optional<u32> invocations,
  138. std::optional<spv::BuiltIn> builtin = std::nullopt) {
  139. if (invocations && ctx.stage == Stage::TessellationControl) {
  140. type = ctx.TypeArray(type, ctx.Constant(ctx.U32[1], *invocations));
  141. }
  142. return DefineVariable(ctx, type, builtin, spv::StorageClass::Output);
  143. }
  144. void DefineGenericOutput(EmitContext& ctx, size_t index, std::optional<u32> invocations) {
  145. static constexpr std::string_view swizzle{"xyzw"};
  146. const size_t base_attr_index{static_cast<size_t>(IR::Attribute::Generic0X) + index * 4};
  147. u32 element{0};
  148. while (element < 4) {
  149. const u32 remainder{4 - element};
  150. const TransformFeedbackVarying* xfb_varying{};
  151. if (!ctx.profile.xfb_varyings.empty()) {
  152. xfb_varying = &ctx.profile.xfb_varyings[base_attr_index + element];
  153. xfb_varying = xfb_varying && xfb_varying->components > 0 ? xfb_varying : nullptr;
  154. }
  155. const u32 num_components{xfb_varying ? xfb_varying->components : remainder};
  156. const Id id{DefineOutput(ctx, ctx.F32[num_components], invocations)};
  157. ctx.Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  158. if (element > 0) {
  159. ctx.Decorate(id, spv::Decoration::Component, element);
  160. }
  161. if (xfb_varying) {
  162. ctx.Decorate(id, spv::Decoration::XfbBuffer, xfb_varying->buffer);
  163. ctx.Decorate(id, spv::Decoration::XfbStride, xfb_varying->stride);
  164. ctx.Decorate(id, spv::Decoration::Offset, xfb_varying->offset);
  165. }
  166. if (num_components < 4 || element > 0) {
  167. const std::string_view subswizzle{swizzle.substr(element, num_components)};
  168. ctx.Name(id, fmt::format("out_attr{}_{}", index, subswizzle));
  169. } else {
  170. ctx.Name(id, fmt::format("out_attr{}", index));
  171. }
  172. const GenericElementInfo info{
  173. .id = id,
  174. .first_element = element,
  175. .num_components = num_components,
  176. };
  177. std::fill_n(ctx.output_generics[index].begin(), num_components, info);
  178. element += num_components;
  179. }
  180. }
  181. Id GetAttributeType(EmitContext& ctx, AttributeType type) {
  182. switch (type) {
  183. case AttributeType::Float:
  184. return ctx.F32[4];
  185. case AttributeType::SignedInt:
  186. return ctx.TypeVector(ctx.TypeInt(32, true), 4);
  187. case AttributeType::UnsignedInt:
  188. return ctx.U32[4];
  189. case AttributeType::Disabled:
  190. break;
  191. }
  192. throw InvalidArgument("Invalid attribute type {}", type);
  193. }
  194. std::optional<AttrInfo> AttrTypes(EmitContext& ctx, u32 index) {
  195. const AttributeType type{ctx.profile.generic_input_types.at(index)};
  196. switch (type) {
  197. case AttributeType::Float:
  198. return AttrInfo{ctx.input_f32, ctx.F32[1], false};
  199. case AttributeType::UnsignedInt:
  200. return AttrInfo{ctx.input_u32, ctx.U32[1], true};
  201. case AttributeType::SignedInt:
  202. return AttrInfo{ctx.input_s32, ctx.TypeInt(32, true), true};
  203. case AttributeType::Disabled:
  204. return std::nullopt;
  205. }
  206. throw InvalidArgument("Invalid attribute type {}", type);
  207. }
  208. void DefineConstBuffers(EmitContext& ctx, const Info& info, Id UniformDefinitions::*member_type,
  209. u32 binding, Id type, char type_char, u32 element_size) {
  210. const Id array_type{ctx.TypeArray(type, ctx.Constant(ctx.U32[1], 65536U / element_size))};
  211. ctx.Decorate(array_type, spv::Decoration::ArrayStride, element_size);
  212. const Id struct_type{ctx.TypeStruct(array_type)};
  213. ctx.Name(struct_type, fmt::format("cbuf_block_{}{}", type_char, element_size * CHAR_BIT));
  214. ctx.Decorate(struct_type, spv::Decoration::Block);
  215. ctx.MemberName(struct_type, 0, "data");
  216. ctx.MemberDecorate(struct_type, 0, spv::Decoration::Offset, 0U);
  217. const Id struct_pointer_type{ctx.TypePointer(spv::StorageClass::Uniform, struct_type)};
  218. const Id uniform_type{ctx.TypePointer(spv::StorageClass::Uniform, type)};
  219. ctx.uniform_types.*member_type = uniform_type;
  220. for (const ConstantBufferDescriptor& desc : info.constant_buffer_descriptors) {
  221. const Id id{ctx.AddGlobalVariable(struct_pointer_type, spv::StorageClass::Uniform)};
  222. ctx.Decorate(id, spv::Decoration::Binding, binding);
  223. ctx.Decorate(id, spv::Decoration::DescriptorSet, 0U);
  224. ctx.Name(id, fmt::format("c{}", desc.index));
  225. for (size_t i = 0; i < desc.count; ++i) {
  226. ctx.cbufs[desc.index + i].*member_type = id;
  227. }
  228. if (ctx.profile.supported_spirv >= 0x00010400) {
  229. ctx.interfaces.push_back(id);
  230. }
  231. binding += desc.count;
  232. }
  233. }
  234. void DefineSsbos(EmitContext& ctx, StorageTypeDefinition& type_def,
  235. Id StorageDefinitions::*member_type, const Info& info, u32 binding, Id type,
  236. u32 stride) {
  237. const Id array_type{ctx.TypeRuntimeArray(type)};
  238. ctx.Decorate(array_type, spv::Decoration::ArrayStride, stride);
  239. const Id struct_type{ctx.TypeStruct(array_type)};
  240. ctx.Decorate(struct_type, spv::Decoration::Block);
  241. ctx.MemberDecorate(struct_type, 0, spv::Decoration::Offset, 0U);
  242. const Id struct_pointer{ctx.TypePointer(spv::StorageClass::StorageBuffer, struct_type)};
  243. type_def.array = struct_pointer;
  244. type_def.element = ctx.TypePointer(spv::StorageClass::StorageBuffer, type);
  245. u32 index{};
  246. for (const StorageBufferDescriptor& desc : info.storage_buffers_descriptors) {
  247. const Id id{ctx.AddGlobalVariable(struct_pointer, spv::StorageClass::StorageBuffer)};
  248. ctx.Decorate(id, spv::Decoration::Binding, binding);
  249. ctx.Decorate(id, spv::Decoration::DescriptorSet, 0U);
  250. ctx.Name(id, fmt::format("ssbo{}", index));
  251. if (ctx.profile.supported_spirv >= 0x00010400) {
  252. ctx.interfaces.push_back(id);
  253. }
  254. for (size_t i = 0; i < desc.count; ++i) {
  255. ctx.ssbos[index + i].*member_type = id;
  256. }
  257. index += desc.count;
  258. binding += desc.count;
  259. }
  260. }
  261. Id CasFunction(EmitContext& ctx, Operation operation, Id value_type) {
  262. const Id func_type{ctx.TypeFunction(value_type, value_type, value_type)};
  263. const Id func{ctx.OpFunction(value_type, spv::FunctionControlMask::MaskNone, func_type)};
  264. const Id op_a{ctx.OpFunctionParameter(value_type)};
  265. const Id op_b{ctx.OpFunctionParameter(value_type)};
  266. ctx.AddLabel();
  267. Id result{};
  268. switch (operation) {
  269. case Operation::Increment: {
  270. const Id pred{ctx.OpUGreaterThanEqual(ctx.U1, op_a, op_b)};
  271. const Id incr{ctx.OpIAdd(value_type, op_a, ctx.Constant(value_type, 1))};
  272. result = ctx.OpSelect(value_type, pred, ctx.u32_zero_value, incr);
  273. break;
  274. }
  275. case Operation::Decrement: {
  276. const Id lhs{ctx.OpIEqual(ctx.U1, op_a, ctx.Constant(value_type, 0u))};
  277. const Id rhs{ctx.OpUGreaterThan(ctx.U1, op_a, op_b)};
  278. const Id pred{ctx.OpLogicalOr(ctx.U1, lhs, rhs)};
  279. const Id decr{ctx.OpISub(value_type, op_a, ctx.Constant(value_type, 1))};
  280. result = ctx.OpSelect(value_type, pred, op_b, decr);
  281. break;
  282. }
  283. case Operation::FPAdd:
  284. result = ctx.OpFAdd(value_type, op_a, op_b);
  285. break;
  286. case Operation::FPMin:
  287. result = ctx.OpFMin(value_type, op_a, op_b);
  288. break;
  289. case Operation::FPMax:
  290. result = ctx.OpFMax(value_type, op_a, op_b);
  291. break;
  292. default:
  293. break;
  294. }
  295. ctx.OpReturnValue(result);
  296. ctx.OpFunctionEnd();
  297. return func;
  298. }
  299. Id CasLoop(EmitContext& ctx, Operation operation, Id array_pointer, Id element_pointer,
  300. Id value_type, Id memory_type, spv::Scope scope) {
  301. const bool is_shared{scope == spv::Scope::Workgroup};
  302. const bool is_struct{!is_shared || ctx.profile.support_explicit_workgroup_layout};
  303. const Id cas_func{CasFunction(ctx, operation, value_type)};
  304. const Id zero{ctx.u32_zero_value};
  305. const Id scope_id{ctx.Constant(ctx.U32[1], static_cast<u32>(scope))};
  306. const Id loop_header{ctx.OpLabel()};
  307. const Id continue_block{ctx.OpLabel()};
  308. const Id merge_block{ctx.OpLabel()};
  309. const Id func_type{is_shared
  310. ? ctx.TypeFunction(value_type, ctx.U32[1], value_type)
  311. : ctx.TypeFunction(value_type, ctx.U32[1], value_type, array_pointer)};
  312. const Id func{ctx.OpFunction(value_type, spv::FunctionControlMask::MaskNone, func_type)};
  313. const Id index{ctx.OpFunctionParameter(ctx.U32[1])};
  314. const Id op_b{ctx.OpFunctionParameter(value_type)};
  315. const Id base{is_shared ? ctx.shared_memory_u32 : ctx.OpFunctionParameter(array_pointer)};
  316. ctx.AddLabel();
  317. ctx.OpBranch(loop_header);
  318. ctx.AddLabel(loop_header);
  319. ctx.OpLoopMerge(merge_block, continue_block, spv::LoopControlMask::MaskNone);
  320. ctx.OpBranch(continue_block);
  321. ctx.AddLabel(continue_block);
  322. const Id word_pointer{is_struct ? ctx.OpAccessChain(element_pointer, base, zero, index)
  323. : ctx.OpAccessChain(element_pointer, base, index)};
  324. if (value_type.value == ctx.F32[2].value) {
  325. const Id u32_value{ctx.OpLoad(ctx.U32[1], word_pointer)};
  326. const Id value{ctx.OpUnpackHalf2x16(ctx.F32[2], u32_value)};
  327. const Id new_value{ctx.OpFunctionCall(value_type, cas_func, value, op_b)};
  328. const Id u32_new_value{ctx.OpPackHalf2x16(ctx.U32[1], new_value)};
  329. const Id atomic_res{ctx.OpAtomicCompareExchange(ctx.U32[1], word_pointer, scope_id, zero,
  330. zero, u32_new_value, u32_value)};
  331. const Id success{ctx.OpIEqual(ctx.U1, atomic_res, u32_value)};
  332. ctx.OpBranchConditional(success, merge_block, loop_header);
  333. ctx.AddLabel(merge_block);
  334. ctx.OpReturnValue(ctx.OpUnpackHalf2x16(ctx.F32[2], atomic_res));
  335. } else {
  336. const Id value{ctx.OpLoad(memory_type, word_pointer)};
  337. const bool matching_type{value_type.value == memory_type.value};
  338. const Id bitcast_value{matching_type ? value : ctx.OpBitcast(value_type, value)};
  339. const Id cal_res{ctx.OpFunctionCall(value_type, cas_func, bitcast_value, op_b)};
  340. const Id new_value{matching_type ? cal_res : ctx.OpBitcast(memory_type, cal_res)};
  341. const Id atomic_res{ctx.OpAtomicCompareExchange(ctx.U32[1], word_pointer, scope_id, zero,
  342. zero, new_value, value)};
  343. const Id success{ctx.OpIEqual(ctx.U1, atomic_res, value)};
  344. ctx.OpBranchConditional(success, merge_block, loop_header);
  345. ctx.AddLabel(merge_block);
  346. ctx.OpReturnValue(ctx.OpBitcast(value_type, atomic_res));
  347. }
  348. ctx.OpFunctionEnd();
  349. return func;
  350. }
  351. } // Anonymous namespace
  352. void VectorTypes::Define(Sirit::Module& sirit_ctx, Id base_type, std::string_view name) {
  353. defs[0] = sirit_ctx.Name(base_type, name);
  354. std::array<char, 6> def_name;
  355. for (int i = 1; i < 4; ++i) {
  356. const std::string_view def_name_view(
  357. def_name.data(),
  358. fmt::format_to_n(def_name.data(), def_name.size(), "{}x{}", name, i + 1).size);
  359. defs[static_cast<size_t>(i)] =
  360. sirit_ctx.Name(sirit_ctx.TypeVector(base_type, i + 1), def_name_view);
  361. }
  362. }
  363. EmitContext::EmitContext(const Profile& profile_, IR::Program& program, u32& binding)
  364. : Sirit::Module(profile_.supported_spirv), profile{profile_}, stage{program.stage} {
  365. AddCapability(spv::Capability::Shader);
  366. DefineCommonTypes(program.info);
  367. DefineCommonConstants();
  368. DefineInterfaces(program);
  369. DefineLocalMemory(program);
  370. DefineSharedMemory(program);
  371. DefineSharedMemoryFunctions(program);
  372. DefineConstantBuffers(program.info, binding);
  373. DefineStorageBuffers(program.info, binding);
  374. DefineTextureBuffers(program.info, binding);
  375. DefineImageBuffers(program.info, binding);
  376. DefineTextures(program.info, binding);
  377. DefineImages(program.info, binding);
  378. DefineAttributeMemAccess(program.info);
  379. DefineLabels(program);
  380. }
  381. EmitContext::~EmitContext() = default;
  382. Id EmitContext::Def(const IR::Value& value) {
  383. if (!value.IsImmediate()) {
  384. return value.InstRecursive()->Definition<Id>();
  385. }
  386. switch (value.Type()) {
  387. case IR::Type::Void:
  388. // Void instructions are used for optional arguments (e.g. texture offsets)
  389. // They are not meant to be used in the SPIR-V module
  390. return Id{};
  391. case IR::Type::U1:
  392. return value.U1() ? true_value : false_value;
  393. case IR::Type::U32:
  394. return Constant(U32[1], value.U32());
  395. case IR::Type::U64:
  396. return Constant(U64, value.U64());
  397. case IR::Type::F32:
  398. return Constant(F32[1], value.F32());
  399. case IR::Type::F64:
  400. return Constant(F64[1], value.F64());
  401. case IR::Type::Label:
  402. return value.Label()->Definition<Id>();
  403. default:
  404. throw NotImplementedException("Immediate type {}", value.Type());
  405. }
  406. }
  407. void EmitContext::DefineCommonTypes(const Info& info) {
  408. void_id = TypeVoid();
  409. U1 = Name(TypeBool(), "u1");
  410. F32.Define(*this, TypeFloat(32), "f32");
  411. U32.Define(*this, TypeInt(32, false), "u32");
  412. private_u32 = Name(TypePointer(spv::StorageClass::Private, U32[1]), "private_u32");
  413. input_f32 = Name(TypePointer(spv::StorageClass::Input, F32[1]), "input_f32");
  414. input_u32 = Name(TypePointer(spv::StorageClass::Input, U32[1]), "input_u32");
  415. input_s32 = Name(TypePointer(spv::StorageClass::Input, TypeInt(32, true)), "input_s32");
  416. output_f32 = Name(TypePointer(spv::StorageClass::Output, F32[1]), "output_f32");
  417. if (info.uses_int8) {
  418. AddCapability(spv::Capability::Int8);
  419. U8 = Name(TypeInt(8, false), "u8");
  420. S8 = Name(TypeInt(8, true), "s8");
  421. }
  422. if (info.uses_int16) {
  423. AddCapability(spv::Capability::Int16);
  424. U16 = Name(TypeInt(16, false), "u16");
  425. S16 = Name(TypeInt(16, true), "s16");
  426. }
  427. if (info.uses_int64) {
  428. AddCapability(spv::Capability::Int64);
  429. U64 = Name(TypeInt(64, false), "u64");
  430. }
  431. if (info.uses_fp16) {
  432. AddCapability(spv::Capability::Float16);
  433. F16.Define(*this, TypeFloat(16), "f16");
  434. }
  435. if (info.uses_fp64) {
  436. AddCapability(spv::Capability::Float64);
  437. F64.Define(*this, TypeFloat(64), "f64");
  438. }
  439. }
  440. void EmitContext::DefineCommonConstants() {
  441. true_value = ConstantTrue(U1);
  442. false_value = ConstantFalse(U1);
  443. u32_zero_value = Constant(U32[1], 0U);
  444. f32_zero_value = Constant(F32[1], 0.0f);
  445. }
  446. void EmitContext::DefineInterfaces(const IR::Program& program) {
  447. DefineInputs(program.info);
  448. DefineOutputs(program);
  449. }
  450. void EmitContext::DefineLocalMemory(const IR::Program& program) {
  451. if (program.local_memory_size == 0) {
  452. return;
  453. }
  454. const u32 num_elements{Common::DivCeil(program.local_memory_size, 4U)};
  455. const Id type{TypeArray(U32[1], Constant(U32[1], num_elements))};
  456. const Id pointer{TypePointer(spv::StorageClass::Private, type)};
  457. local_memory = AddGlobalVariable(pointer, spv::StorageClass::Private);
  458. if (profile.supported_spirv >= 0x00010400) {
  459. interfaces.push_back(local_memory);
  460. }
  461. }
  462. void EmitContext::DefineSharedMemory(const IR::Program& program) {
  463. if (program.shared_memory_size == 0) {
  464. return;
  465. }
  466. const auto make{[&](Id element_type, u32 element_size) {
  467. const u32 num_elements{Common::DivCeil(program.shared_memory_size, element_size)};
  468. const Id array_type{TypeArray(element_type, Constant(U32[1], num_elements))};
  469. Decorate(array_type, spv::Decoration::ArrayStride, element_size);
  470. const Id struct_type{TypeStruct(array_type)};
  471. MemberDecorate(struct_type, 0U, spv::Decoration::Offset, 0U);
  472. Decorate(struct_type, spv::Decoration::Block);
  473. const Id pointer{TypePointer(spv::StorageClass::Workgroup, struct_type)};
  474. const Id element_pointer{TypePointer(spv::StorageClass::Workgroup, element_type)};
  475. const Id variable{AddGlobalVariable(pointer, spv::StorageClass::Workgroup)};
  476. Decorate(variable, spv::Decoration::Aliased);
  477. interfaces.push_back(variable);
  478. return std::make_tuple(variable, element_pointer, pointer);
  479. }};
  480. if (profile.support_explicit_workgroup_layout) {
  481. AddExtension("SPV_KHR_workgroup_memory_explicit_layout");
  482. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayoutKHR);
  483. if (program.info.uses_int8) {
  484. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayout8BitAccessKHR);
  485. std::tie(shared_memory_u8, shared_u8, std::ignore) = make(U8, 1);
  486. }
  487. if (program.info.uses_int16) {
  488. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayout16BitAccessKHR);
  489. std::tie(shared_memory_u16, shared_u16, std::ignore) = make(U16, 2);
  490. }
  491. if (program.info.uses_int64) {
  492. std::tie(shared_memory_u64, shared_u64, std::ignore) = make(U64, 8);
  493. }
  494. std::tie(shared_memory_u32, shared_u32, shared_memory_u32_type) = make(U32[1], 4);
  495. std::tie(shared_memory_u32x2, shared_u32x2, std::ignore) = make(U32[2], 8);
  496. std::tie(shared_memory_u32x4, shared_u32x4, std::ignore) = make(U32[4], 16);
  497. return;
  498. }
  499. const u32 num_elements{Common::DivCeil(program.shared_memory_size, 4U)};
  500. const Id type{TypeArray(U32[1], Constant(U32[1], num_elements))};
  501. shared_memory_u32_type = TypePointer(spv::StorageClass::Workgroup, type);
  502. shared_u32 = TypePointer(spv::StorageClass::Workgroup, U32[1]);
  503. shared_memory_u32 = AddGlobalVariable(shared_memory_u32_type, spv::StorageClass::Workgroup);
  504. interfaces.push_back(shared_memory_u32);
  505. const Id func_type{TypeFunction(void_id, U32[1], U32[1])};
  506. const auto make_function{[&](u32 mask, u32 size) {
  507. const Id loop_header{OpLabel()};
  508. const Id continue_block{OpLabel()};
  509. const Id merge_block{OpLabel()};
  510. const Id func{OpFunction(void_id, spv::FunctionControlMask::MaskNone, func_type)};
  511. const Id offset{OpFunctionParameter(U32[1])};
  512. const Id insert_value{OpFunctionParameter(U32[1])};
  513. AddLabel();
  514. OpBranch(loop_header);
  515. AddLabel(loop_header);
  516. const Id word_offset{OpShiftRightArithmetic(U32[1], offset, Constant(U32[1], 2U))};
  517. const Id shift_offset{OpShiftLeftLogical(U32[1], offset, Constant(U32[1], 3U))};
  518. const Id bit_offset{OpBitwiseAnd(U32[1], shift_offset, Constant(U32[1], mask))};
  519. const Id count{Constant(U32[1], size)};
  520. OpLoopMerge(merge_block, continue_block, spv::LoopControlMask::MaskNone);
  521. OpBranch(continue_block);
  522. AddLabel(continue_block);
  523. const Id word_pointer{OpAccessChain(shared_u32, shared_memory_u32, word_offset)};
  524. const Id old_value{OpLoad(U32[1], word_pointer)};
  525. const Id new_value{OpBitFieldInsert(U32[1], old_value, insert_value, bit_offset, count)};
  526. const Id atomic_res{OpAtomicCompareExchange(U32[1], word_pointer, Constant(U32[1], 1U),
  527. u32_zero_value, u32_zero_value, new_value,
  528. old_value)};
  529. const Id success{OpIEqual(U1, atomic_res, old_value)};
  530. OpBranchConditional(success, merge_block, loop_header);
  531. AddLabel(merge_block);
  532. OpReturn();
  533. OpFunctionEnd();
  534. return func;
  535. }};
  536. if (program.info.uses_int8) {
  537. shared_store_u8_func = make_function(24, 8);
  538. }
  539. if (program.info.uses_int16) {
  540. shared_store_u16_func = make_function(16, 16);
  541. }
  542. }
  543. void EmitContext::DefineSharedMemoryFunctions(const IR::Program& program) {
  544. if (program.info.uses_shared_increment) {
  545. increment_cas_shared = CasLoop(*this, Operation::Increment, shared_memory_u32_type,
  546. shared_u32, U32[1], U32[1], spv::Scope::Workgroup);
  547. }
  548. if (program.info.uses_shared_decrement) {
  549. decrement_cas_shared = CasLoop(*this, Operation::Decrement, shared_memory_u32_type,
  550. shared_u32, U32[1], U32[1], spv::Scope::Workgroup);
  551. }
  552. }
  553. void EmitContext::DefineAttributeMemAccess(const Info& info) {
  554. const auto make_load{[&] {
  555. const bool is_array{stage == Stage::Geometry};
  556. const Id end_block{OpLabel()};
  557. const Id default_label{OpLabel()};
  558. const Id func_type_load{is_array ? TypeFunction(F32[1], U32[1], U32[1])
  559. : TypeFunction(F32[1], U32[1])};
  560. const Id func{OpFunction(F32[1], spv::FunctionControlMask::MaskNone, func_type_load)};
  561. const Id offset{OpFunctionParameter(U32[1])};
  562. const Id vertex{is_array ? OpFunctionParameter(U32[1]) : Id{}};
  563. AddLabel();
  564. const Id base_index{OpShiftRightArithmetic(U32[1], offset, Constant(U32[1], 2U))};
  565. const Id masked_index{OpBitwiseAnd(U32[1], base_index, Constant(U32[1], 3U))};
  566. const Id compare_index{OpShiftRightArithmetic(U32[1], base_index, Constant(U32[1], 2U))};
  567. std::vector<Sirit::Literal> literals;
  568. std::vector<Id> labels;
  569. if (info.loads_position) {
  570. literals.push_back(static_cast<u32>(IR::Attribute::PositionX) >> 2);
  571. labels.push_back(OpLabel());
  572. }
  573. const u32 base_attribute_value = static_cast<u32>(IR::Attribute::Generic0X) >> 2;
  574. for (u32 i = 0; i < info.input_generics.size(); ++i) {
  575. if (!info.input_generics[i].used) {
  576. continue;
  577. }
  578. literals.push_back(base_attribute_value + i);
  579. labels.push_back(OpLabel());
  580. }
  581. OpSelectionMerge(end_block, spv::SelectionControlMask::MaskNone);
  582. OpSwitch(compare_index, default_label, literals, labels);
  583. AddLabel(default_label);
  584. OpReturnValue(Constant(F32[1], 0.0f));
  585. size_t label_index{0};
  586. if (info.loads_position) {
  587. AddLabel(labels[label_index]);
  588. const Id pointer{is_array
  589. ? OpAccessChain(input_f32, input_position, vertex, masked_index)
  590. : OpAccessChain(input_f32, input_position, masked_index)};
  591. const Id result{OpLoad(F32[1], pointer)};
  592. OpReturnValue(result);
  593. ++label_index;
  594. }
  595. for (size_t i = 0; i < info.input_generics.size(); i++) {
  596. if (!info.input_generics[i].used) {
  597. continue;
  598. }
  599. AddLabel(labels[label_index]);
  600. const auto type{AttrTypes(*this, static_cast<u32>(i))};
  601. if (!type) {
  602. OpReturnValue(Constant(F32[1], 0.0f));
  603. ++label_index;
  604. continue;
  605. }
  606. const Id generic_id{input_generics.at(i)};
  607. const Id pointer{is_array
  608. ? OpAccessChain(type->pointer, generic_id, vertex, masked_index)
  609. : OpAccessChain(type->pointer, generic_id, masked_index)};
  610. const Id value{OpLoad(type->id, pointer)};
  611. const Id result{type->needs_cast ? OpBitcast(F32[1], value) : value};
  612. OpReturnValue(result);
  613. ++label_index;
  614. }
  615. AddLabel(end_block);
  616. OpUnreachable();
  617. OpFunctionEnd();
  618. return func;
  619. }};
  620. const auto make_store{[&] {
  621. const Id end_block{OpLabel()};
  622. const Id default_label{OpLabel()};
  623. const Id func_type_store{TypeFunction(void_id, U32[1], F32[1])};
  624. const Id func{OpFunction(void_id, spv::FunctionControlMask::MaskNone, func_type_store)};
  625. const Id offset{OpFunctionParameter(U32[1])};
  626. const Id store_value{OpFunctionParameter(F32[1])};
  627. AddLabel();
  628. const Id base_index{OpShiftRightArithmetic(U32[1], offset, Constant(U32[1], 2U))};
  629. const Id masked_index{OpBitwiseAnd(U32[1], base_index, Constant(U32[1], 3U))};
  630. const Id compare_index{OpShiftRightArithmetic(U32[1], base_index, Constant(U32[1], 2U))};
  631. std::vector<Sirit::Literal> literals;
  632. std::vector<Id> labels;
  633. if (info.stores_position) {
  634. literals.push_back(static_cast<u32>(IR::Attribute::PositionX) >> 2);
  635. labels.push_back(OpLabel());
  636. }
  637. const u32 base_attribute_value = static_cast<u32>(IR::Attribute::Generic0X) >> 2;
  638. for (size_t i = 0; i < info.stores_generics.size(); i++) {
  639. if (!info.stores_generics[i]) {
  640. continue;
  641. }
  642. literals.push_back(base_attribute_value + static_cast<u32>(i));
  643. labels.push_back(OpLabel());
  644. }
  645. if (info.stores_clip_distance) {
  646. literals.push_back(static_cast<u32>(IR::Attribute::ClipDistance0) >> 2);
  647. labels.push_back(OpLabel());
  648. literals.push_back(static_cast<u32>(IR::Attribute::ClipDistance4) >> 2);
  649. labels.push_back(OpLabel());
  650. }
  651. OpSelectionMerge(end_block, spv::SelectionControlMask::MaskNone);
  652. OpSwitch(compare_index, default_label, literals, labels);
  653. AddLabel(default_label);
  654. OpReturn();
  655. size_t label_index{0};
  656. if (info.stores_position) {
  657. AddLabel(labels[label_index]);
  658. const Id pointer{OpAccessChain(output_f32, output_position, masked_index)};
  659. OpStore(pointer, store_value);
  660. OpReturn();
  661. ++label_index;
  662. }
  663. for (size_t i = 0; i < info.stores_generics.size(); ++i) {
  664. if (!info.stores_generics[i]) {
  665. continue;
  666. }
  667. if (output_generics[i][0].num_components != 4) {
  668. throw NotImplementedException("Physical stores and transform feedbacks");
  669. }
  670. AddLabel(labels[label_index]);
  671. const Id generic_id{output_generics[i][0].id};
  672. const Id pointer{OpAccessChain(output_f32, generic_id, masked_index)};
  673. OpStore(pointer, store_value);
  674. OpReturn();
  675. ++label_index;
  676. }
  677. if (info.stores_clip_distance) {
  678. AddLabel(labels[label_index]);
  679. const Id pointer{OpAccessChain(output_f32, clip_distances, masked_index)};
  680. OpStore(pointer, store_value);
  681. OpReturn();
  682. ++label_index;
  683. AddLabel(labels[label_index]);
  684. const Id fixed_index{OpIAdd(U32[1], masked_index, Constant(U32[1], 4))};
  685. const Id pointer2{OpAccessChain(output_f32, clip_distances, fixed_index)};
  686. OpStore(pointer2, store_value);
  687. OpReturn();
  688. ++label_index;
  689. }
  690. AddLabel(end_block);
  691. OpUnreachable();
  692. OpFunctionEnd();
  693. return func;
  694. }};
  695. if (info.loads_indexed_attributes) {
  696. indexed_load_func = make_load();
  697. }
  698. if (info.stores_indexed_attributes) {
  699. indexed_store_func = make_store();
  700. }
  701. }
  702. void EmitContext::DefineConstantBuffers(const Info& info, u32& binding) {
  703. if (info.constant_buffer_descriptors.empty()) {
  704. return;
  705. }
  706. if (True(info.used_constant_buffer_types & IR::Type::U8)) {
  707. DefineConstBuffers(*this, info, &UniformDefinitions::U8, binding, U8, 'u', sizeof(u8));
  708. DefineConstBuffers(*this, info, &UniformDefinitions::S8, binding, S8, 's', sizeof(s8));
  709. }
  710. if (True(info.used_constant_buffer_types & IR::Type::U16)) {
  711. DefineConstBuffers(*this, info, &UniformDefinitions::U16, binding, U16, 'u', sizeof(u16));
  712. DefineConstBuffers(*this, info, &UniformDefinitions::S16, binding, S16, 's', sizeof(s16));
  713. }
  714. if (True(info.used_constant_buffer_types & IR::Type::U32)) {
  715. DefineConstBuffers(*this, info, &UniformDefinitions::U32, binding, U32[1], 'u',
  716. sizeof(u32));
  717. }
  718. if (True(info.used_constant_buffer_types & IR::Type::F32)) {
  719. DefineConstBuffers(*this, info, &UniformDefinitions::F32, binding, F32[1], 'f',
  720. sizeof(f32));
  721. }
  722. if (True(info.used_constant_buffer_types & IR::Type::U32x2)) {
  723. DefineConstBuffers(*this, info, &UniformDefinitions::U32x2, binding, U32[2], 'u',
  724. sizeof(u32[2]));
  725. }
  726. for (const ConstantBufferDescriptor& desc : info.constant_buffer_descriptors) {
  727. binding += desc.count;
  728. }
  729. }
  730. void EmitContext::DefineStorageBuffers(const Info& info, u32& binding) {
  731. if (info.storage_buffers_descriptors.empty()) {
  732. return;
  733. }
  734. AddExtension("SPV_KHR_storage_buffer_storage_class");
  735. if (True(info.used_storage_buffer_types & IR::Type::U8)) {
  736. DefineSsbos(*this, storage_types.U8, &StorageDefinitions::U8, info, binding, U8,
  737. sizeof(u8));
  738. DefineSsbos(*this, storage_types.S8, &StorageDefinitions::S8, info, binding, S8,
  739. sizeof(u8));
  740. }
  741. if (True(info.used_storage_buffer_types & IR::Type::U16)) {
  742. DefineSsbos(*this, storage_types.U16, &StorageDefinitions::U16, info, binding, U16,
  743. sizeof(u16));
  744. DefineSsbos(*this, storage_types.S16, &StorageDefinitions::S16, info, binding, S16,
  745. sizeof(u16));
  746. }
  747. if (True(info.used_storage_buffer_types & IR::Type::U32)) {
  748. DefineSsbos(*this, storage_types.U32, &StorageDefinitions::U32, info, binding, U32[1],
  749. sizeof(u32));
  750. }
  751. if (True(info.used_storage_buffer_types & IR::Type::F32)) {
  752. DefineSsbos(*this, storage_types.F32, &StorageDefinitions::F32, info, binding, F32[1],
  753. sizeof(f32));
  754. }
  755. if (True(info.used_storage_buffer_types & IR::Type::U64)) {
  756. DefineSsbos(*this, storage_types.U64, &StorageDefinitions::U64, info, binding, U64,
  757. sizeof(u64));
  758. }
  759. if (True(info.used_storage_buffer_types & IR::Type::U32x2)) {
  760. DefineSsbos(*this, storage_types.U32x2, &StorageDefinitions::U32x2, info, binding, U32[2],
  761. sizeof(u32[2]));
  762. }
  763. if (True(info.used_storage_buffer_types & IR::Type::U32x4)) {
  764. DefineSsbos(*this, storage_types.U32x4, &StorageDefinitions::U32x4, info, binding, U32[4],
  765. sizeof(u32[4]));
  766. }
  767. for (const StorageBufferDescriptor& desc : info.storage_buffers_descriptors) {
  768. binding += desc.count;
  769. }
  770. const bool needs_function{
  771. info.uses_global_increment || info.uses_global_decrement || info.uses_atomic_f32_add ||
  772. info.uses_atomic_f16x2_add || info.uses_atomic_f16x2_min || info.uses_atomic_f16x2_max ||
  773. info.uses_atomic_f32x2_add || info.uses_atomic_f32x2_min || info.uses_atomic_f32x2_max};
  774. if (needs_function) {
  775. AddCapability(spv::Capability::VariablePointersStorageBuffer);
  776. }
  777. if (info.uses_global_increment) {
  778. increment_cas_ssbo = CasLoop(*this, Operation::Increment, storage_types.U32.array,
  779. storage_types.U32.element, U32[1], U32[1], spv::Scope::Device);
  780. }
  781. if (info.uses_global_decrement) {
  782. decrement_cas_ssbo = CasLoop(*this, Operation::Decrement, storage_types.U32.array,
  783. storage_types.U32.element, U32[1], U32[1], spv::Scope::Device);
  784. }
  785. if (info.uses_atomic_f32_add) {
  786. f32_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  787. storage_types.U32.element, F32[1], U32[1], spv::Scope::Device);
  788. }
  789. if (info.uses_atomic_f16x2_add) {
  790. f16x2_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  791. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  792. }
  793. if (info.uses_atomic_f16x2_min) {
  794. f16x2_min_cas = CasLoop(*this, Operation::FPMin, storage_types.U32.array,
  795. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  796. }
  797. if (info.uses_atomic_f16x2_max) {
  798. f16x2_max_cas = CasLoop(*this, Operation::FPMax, storage_types.U32.array,
  799. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  800. }
  801. if (info.uses_atomic_f32x2_add) {
  802. f32x2_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  803. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  804. }
  805. if (info.uses_atomic_f32x2_min) {
  806. f32x2_min_cas = CasLoop(*this, Operation::FPMin, storage_types.U32.array,
  807. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  808. }
  809. if (info.uses_atomic_f32x2_max) {
  810. f32x2_max_cas = CasLoop(*this, Operation::FPMax, storage_types.U32.array,
  811. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  812. }
  813. }
  814. void EmitContext::DefineTextureBuffers(const Info& info, u32& binding) {
  815. if (info.texture_buffer_descriptors.empty()) {
  816. return;
  817. }
  818. const spv::ImageFormat format{spv::ImageFormat::Unknown};
  819. image_buffer_type = TypeImage(F32[1], spv::Dim::Buffer, 0U, false, false, 1, format);
  820. sampled_texture_buffer_type = TypeSampledImage(image_buffer_type);
  821. const Id type{TypePointer(spv::StorageClass::UniformConstant, sampled_texture_buffer_type)};
  822. texture_buffers.reserve(info.texture_buffer_descriptors.size());
  823. for (const TextureBufferDescriptor& desc : info.texture_buffer_descriptors) {
  824. if (desc.count != 1) {
  825. throw NotImplementedException("Array of texture buffers");
  826. }
  827. const Id id{AddGlobalVariable(type, spv::StorageClass::UniformConstant)};
  828. Decorate(id, spv::Decoration::Binding, binding);
  829. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  830. Name(id, fmt::format("texbuf{}_{:02x}", desc.cbuf_index, desc.cbuf_offset));
  831. texture_buffers.insert(texture_buffers.end(), desc.count, id);
  832. if (profile.supported_spirv >= 0x00010400) {
  833. interfaces.push_back(id);
  834. }
  835. binding += desc.count;
  836. }
  837. }
  838. void EmitContext::DefineImageBuffers(const Info& info, u32& binding) {
  839. image_buffers.reserve(info.image_buffer_descriptors.size());
  840. for (const ImageBufferDescriptor& desc : info.image_buffer_descriptors) {
  841. if (desc.count != 1) {
  842. throw NotImplementedException("Array of image buffers");
  843. }
  844. const spv::ImageFormat format{GetImageFormat(desc.format)};
  845. const Id image_type{TypeImage(U32[4], spv::Dim::Buffer, false, false, false, 2, format)};
  846. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
  847. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  848. Decorate(id, spv::Decoration::Binding, binding);
  849. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  850. Name(id, fmt::format("imgbuf{}_{:02x}", desc.cbuf_index, desc.cbuf_offset));
  851. const ImageBufferDefinition def{
  852. .id = id,
  853. .image_type = image_type,
  854. };
  855. image_buffers.insert(image_buffers.end(), desc.count, def);
  856. if (profile.supported_spirv >= 0x00010400) {
  857. interfaces.push_back(id);
  858. }
  859. binding += desc.count;
  860. }
  861. }
  862. void EmitContext::DefineTextures(const Info& info, u32& binding) {
  863. textures.reserve(info.texture_descriptors.size());
  864. for (const TextureDescriptor& desc : info.texture_descriptors) {
  865. if (desc.count != 1) {
  866. throw NotImplementedException("Array of textures");
  867. }
  868. const Id image_type{ImageType(*this, desc)};
  869. const Id sampled_type{TypeSampledImage(image_type)};
  870. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, sampled_type)};
  871. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  872. Decorate(id, spv::Decoration::Binding, binding);
  873. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  874. Name(id, fmt::format("tex{}_{:02x}", desc.cbuf_index, desc.cbuf_offset));
  875. for (u32 index = 0; index < desc.count; ++index) {
  876. // TODO: Pass count info
  877. textures.push_back(TextureDefinition{
  878. .id{id},
  879. .sampled_type{sampled_type},
  880. .image_type{image_type},
  881. });
  882. }
  883. if (profile.supported_spirv >= 0x00010400) {
  884. interfaces.push_back(id);
  885. }
  886. binding += desc.count;
  887. }
  888. }
  889. void EmitContext::DefineImages(const Info& info, u32& binding) {
  890. images.reserve(info.image_descriptors.size());
  891. for (const ImageDescriptor& desc : info.image_descriptors) {
  892. if (desc.count != 1) {
  893. throw NotImplementedException("Array of textures");
  894. }
  895. const Id image_type{ImageType(*this, desc)};
  896. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
  897. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  898. Decorate(id, spv::Decoration::Binding, binding);
  899. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  900. Name(id, fmt::format("img{}_{:02x}", desc.cbuf_index, desc.cbuf_offset));
  901. for (u32 index = 0; index < desc.count; ++index) {
  902. images.push_back(ImageDefinition{
  903. .id{id},
  904. .image_type{image_type},
  905. });
  906. }
  907. if (profile.supported_spirv >= 0x00010400) {
  908. interfaces.push_back(id);
  909. }
  910. binding += desc.count;
  911. }
  912. }
  913. void EmitContext::DefineLabels(IR::Program& program) {
  914. for (IR::Block* const block : program.blocks) {
  915. block->SetDefinition(OpLabel());
  916. }
  917. }
  918. void EmitContext::DefineInputs(const Info& info) {
  919. if (info.uses_workgroup_id) {
  920. workgroup_id = DefineInput(*this, U32[3], false, spv::BuiltIn::WorkgroupId);
  921. }
  922. if (info.uses_local_invocation_id) {
  923. local_invocation_id = DefineInput(*this, U32[3], false, spv::BuiltIn::LocalInvocationId);
  924. }
  925. if (info.uses_invocation_id) {
  926. invocation_id = DefineInput(*this, U32[1], false, spv::BuiltIn::InvocationId);
  927. }
  928. if (info.uses_is_helper_invocation) {
  929. is_helper_invocation = DefineInput(*this, U1, false, spv::BuiltIn::HelperInvocation);
  930. }
  931. if (info.uses_subgroup_mask) {
  932. subgroup_mask_eq = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupEqMaskKHR);
  933. subgroup_mask_lt = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLtMaskKHR);
  934. subgroup_mask_le = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLeMaskKHR);
  935. subgroup_mask_gt = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupGtMaskKHR);
  936. subgroup_mask_ge = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupGeMaskKHR);
  937. }
  938. if (info.uses_subgroup_invocation_id ||
  939. (profile.warp_size_potentially_larger_than_guest &&
  940. (info.uses_subgroup_vote || info.uses_subgroup_mask))) {
  941. subgroup_local_invocation_id =
  942. DefineInput(*this, U32[1], false, spv::BuiltIn::SubgroupLocalInvocationId);
  943. }
  944. if (info.uses_fswzadd) {
  945. const Id f32_one{Constant(F32[1], 1.0f)};
  946. const Id f32_minus_one{Constant(F32[1], -1.0f)};
  947. const Id f32_zero{Constant(F32[1], 0.0f)};
  948. fswzadd_lut_a = ConstantComposite(F32[4], f32_minus_one, f32_one, f32_minus_one, f32_zero);
  949. fswzadd_lut_b =
  950. ConstantComposite(F32[4], f32_minus_one, f32_minus_one, f32_one, f32_minus_one);
  951. }
  952. if (info.loads_position) {
  953. const bool is_fragment{stage != Stage::Fragment};
  954. const spv::BuiltIn built_in{is_fragment ? spv::BuiltIn::Position : spv::BuiltIn::FragCoord};
  955. input_position = DefineInput(*this, F32[4], true, built_in);
  956. }
  957. if (info.loads_instance_id) {
  958. if (profile.support_vertex_instance_id) {
  959. instance_id = DefineInput(*this, U32[1], true, spv::BuiltIn::InstanceId);
  960. } else {
  961. instance_index = DefineInput(*this, U32[1], true, spv::BuiltIn::InstanceIndex);
  962. base_instance = DefineInput(*this, U32[1], true, spv::BuiltIn::BaseInstance);
  963. }
  964. }
  965. if (info.loads_vertex_id) {
  966. if (profile.support_vertex_instance_id) {
  967. vertex_id = DefineInput(*this, U32[1], true, spv::BuiltIn::VertexId);
  968. } else {
  969. vertex_index = DefineInput(*this, U32[1], true, spv::BuiltIn::VertexIndex);
  970. base_vertex = DefineInput(*this, U32[1], true, spv::BuiltIn::BaseVertex);
  971. }
  972. }
  973. if (info.loads_front_face) {
  974. front_face = DefineInput(*this, U1, true, spv::BuiltIn::FrontFacing);
  975. }
  976. if (info.loads_point_coord) {
  977. point_coord = DefineInput(*this, F32[2], true, spv::BuiltIn::PointCoord);
  978. }
  979. if (info.loads_tess_coord) {
  980. tess_coord = DefineInput(*this, F32[3], false, spv::BuiltIn::TessCoord);
  981. }
  982. for (size_t index = 0; index < info.input_generics.size(); ++index) {
  983. const InputVarying generic{info.input_generics[index]};
  984. if (!generic.used) {
  985. continue;
  986. }
  987. const AttributeType input_type{profile.generic_input_types[index]};
  988. if (input_type == AttributeType::Disabled) {
  989. continue;
  990. }
  991. const Id type{GetAttributeType(*this, input_type)};
  992. const Id id{DefineInput(*this, type, true)};
  993. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  994. Name(id, fmt::format("in_attr{}", index));
  995. input_generics[index] = id;
  996. if (stage != Stage::Fragment) {
  997. continue;
  998. }
  999. switch (generic.interpolation) {
  1000. case Interpolation::Smooth:
  1001. // Default
  1002. // Decorate(id, spv::Decoration::Smooth);
  1003. break;
  1004. case Interpolation::NoPerspective:
  1005. Decorate(id, spv::Decoration::NoPerspective);
  1006. break;
  1007. case Interpolation::Flat:
  1008. Decorate(id, spv::Decoration::Flat);
  1009. break;
  1010. }
  1011. }
  1012. if (stage == Stage::TessellationEval) {
  1013. for (size_t index = 0; index < info.uses_patches.size(); ++index) {
  1014. if (!info.uses_patches[index]) {
  1015. continue;
  1016. }
  1017. const Id id{DefineInput(*this, F32[4], false)};
  1018. Decorate(id, spv::Decoration::Patch);
  1019. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1020. patches[index] = id;
  1021. }
  1022. }
  1023. }
  1024. void EmitContext::DefineOutputs(const IR::Program& program) {
  1025. const Info& info{program.info};
  1026. const std::optional<u32> invocations{program.invocations};
  1027. if (info.stores_position || stage == Stage::VertexB) {
  1028. output_position = DefineOutput(*this, F32[4], invocations, spv::BuiltIn::Position);
  1029. }
  1030. if (info.stores_point_size || profile.fixed_state_point_size) {
  1031. if (stage == Stage::Fragment) {
  1032. throw NotImplementedException("Storing PointSize in fragment stage");
  1033. }
  1034. output_point_size = DefineOutput(*this, F32[1], invocations, spv::BuiltIn::PointSize);
  1035. }
  1036. if (info.stores_clip_distance) {
  1037. if (stage == Stage::Fragment) {
  1038. throw NotImplementedException("Storing ClipDistance in fragment stage");
  1039. }
  1040. const Id type{TypeArray(F32[1], Constant(U32[1], 8U))};
  1041. clip_distances = DefineOutput(*this, type, invocations, spv::BuiltIn::ClipDistance);
  1042. }
  1043. if (info.stores_layer &&
  1044. (profile.support_viewport_index_layer_non_geometry || stage == Stage::Geometry)) {
  1045. if (stage == Stage::Fragment) {
  1046. throw NotImplementedException("Storing Layer in fragment stage");
  1047. }
  1048. layer = DefineOutput(*this, U32[1], invocations, spv::BuiltIn::Layer);
  1049. }
  1050. if (info.stores_viewport_index &&
  1051. (profile.support_viewport_index_layer_non_geometry || stage == Stage::Geometry)) {
  1052. if (stage == Stage::Fragment) {
  1053. throw NotImplementedException("Storing ViewportIndex in fragment stage");
  1054. }
  1055. viewport_index = DefineOutput(*this, U32[1], invocations, spv::BuiltIn::ViewportIndex);
  1056. }
  1057. for (size_t index = 0; index < info.stores_generics.size(); ++index) {
  1058. if (info.stores_generics[index]) {
  1059. DefineGenericOutput(*this, index, invocations);
  1060. }
  1061. }
  1062. switch (stage) {
  1063. case Stage::TessellationControl:
  1064. if (info.stores_tess_level_outer) {
  1065. const Id type{TypeArray(F32[1], Constant(U32[1], 4))};
  1066. output_tess_level_outer =
  1067. DefineOutput(*this, type, std::nullopt, spv::BuiltIn::TessLevelOuter);
  1068. Decorate(output_tess_level_outer, spv::Decoration::Patch);
  1069. }
  1070. if (info.stores_tess_level_inner) {
  1071. const Id type{TypeArray(F32[1], Constant(U32[1], 2))};
  1072. output_tess_level_inner =
  1073. DefineOutput(*this, type, std::nullopt, spv::BuiltIn::TessLevelInner);
  1074. Decorate(output_tess_level_inner, spv::Decoration::Patch);
  1075. }
  1076. for (size_t index = 0; index < info.uses_patches.size(); ++index) {
  1077. if (!info.uses_patches[index]) {
  1078. continue;
  1079. }
  1080. const Id id{DefineOutput(*this, F32[4], std::nullopt)};
  1081. Decorate(id, spv::Decoration::Patch);
  1082. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1083. patches[index] = id;
  1084. }
  1085. break;
  1086. case Stage::Fragment:
  1087. for (u32 index = 0; index < 8; ++index) {
  1088. if (!info.stores_frag_color[index]) {
  1089. continue;
  1090. }
  1091. frag_color[index] = DefineOutput(*this, F32[4], std::nullopt);
  1092. Decorate(frag_color[index], spv::Decoration::Location, index);
  1093. Name(frag_color[index], fmt::format("frag_color{}", index));
  1094. }
  1095. if (info.stores_frag_depth) {
  1096. frag_depth = DefineOutput(*this, F32[1], std::nullopt);
  1097. Decorate(frag_depth, spv::Decoration::BuiltIn, spv::BuiltIn::FragDepth);
  1098. Name(frag_depth, "frag_depth");
  1099. }
  1100. break;
  1101. default:
  1102. break;
  1103. }
  1104. }
  1105. } // namespace Shader::Backend::SPIRV