emit_context.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  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.Const(32u));
  124. }
  125. break;
  126. case Stage::Geometry:
  127. if (per_invocation) {
  128. const u32 num_vertices{NumVertices(ctx.runtime_info.input_topology)};
  129. type = ctx.TypeArray(type, ctx.Const(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.Const(*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.runtime_info.xfb_varyings.empty()) {
  152. xfb_varying = &ctx.runtime_info.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() + element, 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.runtime_info.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. std::string_view StageName(Stage stage) {
  209. switch (stage) {
  210. case Stage::VertexA:
  211. return "vs_a";
  212. case Stage::VertexB:
  213. return "vs";
  214. case Stage::TessellationControl:
  215. return "tcs";
  216. case Stage::TessellationEval:
  217. return "tes";
  218. case Stage::Geometry:
  219. return "gs";
  220. case Stage::Fragment:
  221. return "fs";
  222. case Stage::Compute:
  223. return "cs";
  224. }
  225. throw InvalidArgument("Invalid stage {}", stage);
  226. }
  227. template <typename... Args>
  228. void Name(EmitContext& ctx, Id object, std::string_view format_str, Args&&... args) {
  229. ctx.Name(object, fmt::format(fmt::runtime(format_str), StageName(ctx.stage),
  230. std::forward<Args>(args)...)
  231. .c_str());
  232. }
  233. void DefineConstBuffers(EmitContext& ctx, const Info& info, Id UniformDefinitions::*member_type,
  234. u32 binding, Id type, char type_char, u32 element_size) {
  235. const Id array_type{ctx.TypeArray(type, ctx.Const(65536U / element_size))};
  236. ctx.Decorate(array_type, spv::Decoration::ArrayStride, element_size);
  237. const Id struct_type{ctx.TypeStruct(array_type)};
  238. Name(ctx, struct_type, "{}_cbuf_block_{}{}", ctx.stage, type_char, element_size * CHAR_BIT);
  239. ctx.Decorate(struct_type, spv::Decoration::Block);
  240. ctx.MemberName(struct_type, 0, "data");
  241. ctx.MemberDecorate(struct_type, 0, spv::Decoration::Offset, 0U);
  242. const Id struct_pointer_type{ctx.TypePointer(spv::StorageClass::Uniform, struct_type)};
  243. const Id uniform_type{ctx.TypePointer(spv::StorageClass::Uniform, type)};
  244. ctx.uniform_types.*member_type = uniform_type;
  245. for (const ConstantBufferDescriptor& desc : info.constant_buffer_descriptors) {
  246. const Id id{ctx.AddGlobalVariable(struct_pointer_type, spv::StorageClass::Uniform)};
  247. ctx.Decorate(id, spv::Decoration::Binding, binding);
  248. ctx.Decorate(id, spv::Decoration::DescriptorSet, 0U);
  249. ctx.Name(id, fmt::format("c{}", desc.index));
  250. for (size_t i = 0; i < desc.count; ++i) {
  251. ctx.cbufs[desc.index + i].*member_type = id;
  252. }
  253. if (ctx.profile.supported_spirv >= 0x00010400) {
  254. ctx.interfaces.push_back(id);
  255. }
  256. binding += desc.count;
  257. }
  258. }
  259. void DefineSsbos(EmitContext& ctx, StorageTypeDefinition& type_def,
  260. Id StorageDefinitions::*member_type, const Info& info, u32 binding, Id type,
  261. u32 stride) {
  262. const Id array_type{ctx.TypeRuntimeArray(type)};
  263. ctx.Decorate(array_type, spv::Decoration::ArrayStride, stride);
  264. const Id struct_type{ctx.TypeStruct(array_type)};
  265. ctx.Decorate(struct_type, spv::Decoration::Block);
  266. ctx.MemberDecorate(struct_type, 0, spv::Decoration::Offset, 0U);
  267. const Id struct_pointer{ctx.TypePointer(spv::StorageClass::StorageBuffer, struct_type)};
  268. type_def.array = struct_pointer;
  269. type_def.element = ctx.TypePointer(spv::StorageClass::StorageBuffer, type);
  270. u32 index{};
  271. for (const StorageBufferDescriptor& desc : info.storage_buffers_descriptors) {
  272. const Id id{ctx.AddGlobalVariable(struct_pointer, spv::StorageClass::StorageBuffer)};
  273. ctx.Decorate(id, spv::Decoration::Binding, binding);
  274. ctx.Decorate(id, spv::Decoration::DescriptorSet, 0U);
  275. ctx.Name(id, fmt::format("ssbo{}", index));
  276. if (ctx.profile.supported_spirv >= 0x00010400) {
  277. ctx.interfaces.push_back(id);
  278. }
  279. for (size_t i = 0; i < desc.count; ++i) {
  280. ctx.ssbos[index + i].*member_type = id;
  281. }
  282. index += desc.count;
  283. binding += desc.count;
  284. }
  285. }
  286. Id CasFunction(EmitContext& ctx, Operation operation, Id value_type) {
  287. const Id func_type{ctx.TypeFunction(value_type, value_type, value_type)};
  288. const Id func{ctx.OpFunction(value_type, spv::FunctionControlMask::MaskNone, func_type)};
  289. const Id op_a{ctx.OpFunctionParameter(value_type)};
  290. const Id op_b{ctx.OpFunctionParameter(value_type)};
  291. ctx.AddLabel();
  292. Id result{};
  293. switch (operation) {
  294. case Operation::Increment: {
  295. const Id pred{ctx.OpUGreaterThanEqual(ctx.U1, op_a, op_b)};
  296. const Id incr{ctx.OpIAdd(value_type, op_a, ctx.Constant(value_type, 1))};
  297. result = ctx.OpSelect(value_type, pred, ctx.u32_zero_value, incr);
  298. break;
  299. }
  300. case Operation::Decrement: {
  301. const Id lhs{ctx.OpIEqual(ctx.U1, op_a, ctx.Constant(value_type, 0u))};
  302. const Id rhs{ctx.OpUGreaterThan(ctx.U1, op_a, op_b)};
  303. const Id pred{ctx.OpLogicalOr(ctx.U1, lhs, rhs)};
  304. const Id decr{ctx.OpISub(value_type, op_a, ctx.Constant(value_type, 1))};
  305. result = ctx.OpSelect(value_type, pred, op_b, decr);
  306. break;
  307. }
  308. case Operation::FPAdd:
  309. result = ctx.OpFAdd(value_type, op_a, op_b);
  310. break;
  311. case Operation::FPMin:
  312. result = ctx.OpFMin(value_type, op_a, op_b);
  313. break;
  314. case Operation::FPMax:
  315. result = ctx.OpFMax(value_type, op_a, op_b);
  316. break;
  317. default:
  318. break;
  319. }
  320. ctx.OpReturnValue(result);
  321. ctx.OpFunctionEnd();
  322. return func;
  323. }
  324. Id CasLoop(EmitContext& ctx, Operation operation, Id array_pointer, Id element_pointer,
  325. Id value_type, Id memory_type, spv::Scope scope) {
  326. const bool is_shared{scope == spv::Scope::Workgroup};
  327. const bool is_struct{!is_shared || ctx.profile.support_explicit_workgroup_layout};
  328. const Id cas_func{CasFunction(ctx, operation, value_type)};
  329. const Id zero{ctx.u32_zero_value};
  330. const Id scope_id{ctx.Const(static_cast<u32>(scope))};
  331. const Id loop_header{ctx.OpLabel()};
  332. const Id continue_block{ctx.OpLabel()};
  333. const Id merge_block{ctx.OpLabel()};
  334. const Id func_type{is_shared
  335. ? ctx.TypeFunction(value_type, ctx.U32[1], value_type)
  336. : ctx.TypeFunction(value_type, ctx.U32[1], value_type, array_pointer)};
  337. const Id func{ctx.OpFunction(value_type, spv::FunctionControlMask::MaskNone, func_type)};
  338. const Id index{ctx.OpFunctionParameter(ctx.U32[1])};
  339. const Id op_b{ctx.OpFunctionParameter(value_type)};
  340. const Id base{is_shared ? ctx.shared_memory_u32 : ctx.OpFunctionParameter(array_pointer)};
  341. ctx.AddLabel();
  342. ctx.OpBranch(loop_header);
  343. ctx.AddLabel(loop_header);
  344. ctx.OpLoopMerge(merge_block, continue_block, spv::LoopControlMask::MaskNone);
  345. ctx.OpBranch(continue_block);
  346. ctx.AddLabel(continue_block);
  347. const Id word_pointer{is_struct ? ctx.OpAccessChain(element_pointer, base, zero, index)
  348. : ctx.OpAccessChain(element_pointer, base, index)};
  349. if (value_type.value == ctx.F32[2].value) {
  350. const Id u32_value{ctx.OpLoad(ctx.U32[1], word_pointer)};
  351. const Id value{ctx.OpUnpackHalf2x16(ctx.F32[2], u32_value)};
  352. const Id new_value{ctx.OpFunctionCall(value_type, cas_func, value, op_b)};
  353. const Id u32_new_value{ctx.OpPackHalf2x16(ctx.U32[1], new_value)};
  354. const Id atomic_res{ctx.OpAtomicCompareExchange(ctx.U32[1], word_pointer, scope_id, zero,
  355. zero, u32_new_value, u32_value)};
  356. const Id success{ctx.OpIEqual(ctx.U1, atomic_res, u32_value)};
  357. ctx.OpBranchConditional(success, merge_block, loop_header);
  358. ctx.AddLabel(merge_block);
  359. ctx.OpReturnValue(ctx.OpUnpackHalf2x16(ctx.F32[2], atomic_res));
  360. } else {
  361. const Id value{ctx.OpLoad(memory_type, word_pointer)};
  362. const bool matching_type{value_type.value == memory_type.value};
  363. const Id bitcast_value{matching_type ? value : ctx.OpBitcast(value_type, value)};
  364. const Id cal_res{ctx.OpFunctionCall(value_type, cas_func, bitcast_value, op_b)};
  365. const Id new_value{matching_type ? cal_res : ctx.OpBitcast(memory_type, cal_res)};
  366. const Id atomic_res{ctx.OpAtomicCompareExchange(ctx.U32[1], word_pointer, scope_id, zero,
  367. zero, new_value, value)};
  368. const Id success{ctx.OpIEqual(ctx.U1, atomic_res, value)};
  369. ctx.OpBranchConditional(success, merge_block, loop_header);
  370. ctx.AddLabel(merge_block);
  371. ctx.OpReturnValue(ctx.OpBitcast(value_type, atomic_res));
  372. }
  373. ctx.OpFunctionEnd();
  374. return func;
  375. }
  376. template <typename Desc>
  377. std::string NameOf(Stage stage, const Desc& desc, std::string_view prefix) {
  378. if (desc.count > 1) {
  379. return fmt::format("{}_{}{}_{:02x}x{}", StageName(stage), prefix, desc.cbuf_index,
  380. desc.cbuf_offset, desc.count);
  381. } else {
  382. return fmt::format("{}_{}{}_{:02x}", StageName(stage), prefix, desc.cbuf_index,
  383. desc.cbuf_offset);
  384. }
  385. }
  386. Id DescType(EmitContext& ctx, Id sampled_type, Id pointer_type, u32 count) {
  387. if (count > 1) {
  388. const Id array_type{ctx.TypeArray(sampled_type, ctx.Const(count))};
  389. return ctx.TypePointer(spv::StorageClass::UniformConstant, array_type);
  390. } else {
  391. return pointer_type;
  392. }
  393. }
  394. } // Anonymous namespace
  395. void VectorTypes::Define(Sirit::Module& sirit_ctx, Id base_type, std::string_view name) {
  396. defs[0] = sirit_ctx.Name(base_type, name);
  397. std::array<char, 6> def_name;
  398. for (int i = 1; i < 4; ++i) {
  399. const std::string_view def_name_view(
  400. def_name.data(),
  401. fmt::format_to_n(def_name.data(), def_name.size(), "{}x{}", name, i + 1).size);
  402. defs[static_cast<size_t>(i)] =
  403. sirit_ctx.Name(sirit_ctx.TypeVector(base_type, i + 1), def_name_view);
  404. }
  405. }
  406. EmitContext::EmitContext(const Profile& profile_, const RuntimeInfo& runtime_info_,
  407. IR::Program& program, Bindings& bindings)
  408. : Sirit::Module(profile_.supported_spirv), profile{profile_},
  409. runtime_info{runtime_info_}, stage{program.stage} {
  410. const bool is_unified{profile.unified_descriptor_binding};
  411. u32& uniform_binding{is_unified ? bindings.unified : bindings.uniform_buffer};
  412. u32& storage_binding{is_unified ? bindings.unified : bindings.storage_buffer};
  413. u32& texture_binding{is_unified ? bindings.unified : bindings.texture};
  414. u32& image_binding{is_unified ? bindings.unified : bindings.image};
  415. AddCapability(spv::Capability::Shader);
  416. DefineCommonTypes(program.info);
  417. DefineCommonConstants();
  418. DefineInterfaces(program);
  419. DefineLocalMemory(program);
  420. DefineSharedMemory(program);
  421. DefineSharedMemoryFunctions(program);
  422. DefineConstantBuffers(program.info, uniform_binding);
  423. DefineStorageBuffers(program.info, storage_binding);
  424. DefineTextureBuffers(program.info, texture_binding);
  425. DefineImageBuffers(program.info, image_binding);
  426. DefineTextures(program.info, texture_binding);
  427. DefineImages(program.info, image_binding);
  428. DefineAttributeMemAccess(program.info);
  429. DefineGlobalMemoryFunctions(program.info);
  430. }
  431. EmitContext::~EmitContext() = default;
  432. Id EmitContext::Def(const IR::Value& value) {
  433. if (!value.IsImmediate()) {
  434. return value.InstRecursive()->Definition<Id>();
  435. }
  436. switch (value.Type()) {
  437. case IR::Type::Void:
  438. // Void instructions are used for optional arguments (e.g. texture offsets)
  439. // They are not meant to be used in the SPIR-V module
  440. return Id{};
  441. case IR::Type::U1:
  442. return value.U1() ? true_value : false_value;
  443. case IR::Type::U32:
  444. return Const(value.U32());
  445. case IR::Type::U64:
  446. return Constant(U64, value.U64());
  447. case IR::Type::F32:
  448. return Const(value.F32());
  449. case IR::Type::F64:
  450. return Constant(F64[1], value.F64());
  451. default:
  452. throw NotImplementedException("Immediate type {}", value.Type());
  453. }
  454. }
  455. Id EmitContext::BitOffset8(const IR::Value& offset) {
  456. if (offset.IsImmediate()) {
  457. return Const((offset.U32() % 4) * 8);
  458. }
  459. return OpBitwiseAnd(U32[1], OpShiftLeftLogical(U32[1], Def(offset), Const(3u)), Const(24u));
  460. }
  461. Id EmitContext::BitOffset16(const IR::Value& offset) {
  462. if (offset.IsImmediate()) {
  463. return Const(((offset.U32() / 2) % 2) * 16);
  464. }
  465. return OpBitwiseAnd(U32[1], OpShiftLeftLogical(U32[1], Def(offset), Const(3u)), Const(16u));
  466. }
  467. void EmitContext::DefineCommonTypes(const Info& info) {
  468. void_id = TypeVoid();
  469. U1 = Name(TypeBool(), "u1");
  470. F32.Define(*this, TypeFloat(32), "f32");
  471. U32.Define(*this, TypeInt(32, false), "u32");
  472. S32.Define(*this, TypeInt(32, true), "s32");
  473. private_u32 = Name(TypePointer(spv::StorageClass::Private, U32[1]), "private_u32");
  474. input_f32 = Name(TypePointer(spv::StorageClass::Input, F32[1]), "input_f32");
  475. input_u32 = Name(TypePointer(spv::StorageClass::Input, U32[1]), "input_u32");
  476. input_s32 = Name(TypePointer(spv::StorageClass::Input, TypeInt(32, true)), "input_s32");
  477. output_f32 = Name(TypePointer(spv::StorageClass::Output, F32[1]), "output_f32");
  478. output_u32 = Name(TypePointer(spv::StorageClass::Output, U32[1]), "output_u32");
  479. if (info.uses_int8 && profile.support_int8) {
  480. AddCapability(spv::Capability::Int8);
  481. U8 = Name(TypeInt(8, false), "u8");
  482. S8 = Name(TypeInt(8, true), "s8");
  483. }
  484. if (info.uses_int16 && profile.support_int16) {
  485. AddCapability(spv::Capability::Int16);
  486. U16 = Name(TypeInt(16, false), "u16");
  487. S16 = Name(TypeInt(16, true), "s16");
  488. }
  489. if (info.uses_int64) {
  490. AddCapability(spv::Capability::Int64);
  491. U64 = Name(TypeInt(64, false), "u64");
  492. }
  493. if (info.uses_fp16) {
  494. AddCapability(spv::Capability::Float16);
  495. F16.Define(*this, TypeFloat(16), "f16");
  496. }
  497. if (info.uses_fp64) {
  498. AddCapability(spv::Capability::Float64);
  499. F64.Define(*this, TypeFloat(64), "f64");
  500. }
  501. }
  502. void EmitContext::DefineCommonConstants() {
  503. true_value = ConstantTrue(U1);
  504. false_value = ConstantFalse(U1);
  505. u32_zero_value = Const(0U);
  506. f32_zero_value = Const(0.0f);
  507. }
  508. void EmitContext::DefineInterfaces(const IR::Program& program) {
  509. DefineInputs(program);
  510. DefineOutputs(program);
  511. }
  512. void EmitContext::DefineLocalMemory(const IR::Program& program) {
  513. if (program.local_memory_size == 0) {
  514. return;
  515. }
  516. const u32 num_elements{Common::DivCeil(program.local_memory_size, 4U)};
  517. const Id type{TypeArray(U32[1], Const(num_elements))};
  518. const Id pointer{TypePointer(spv::StorageClass::Private, type)};
  519. local_memory = AddGlobalVariable(pointer, spv::StorageClass::Private);
  520. if (profile.supported_spirv >= 0x00010400) {
  521. interfaces.push_back(local_memory);
  522. }
  523. }
  524. void EmitContext::DefineSharedMemory(const IR::Program& program) {
  525. if (program.shared_memory_size == 0) {
  526. return;
  527. }
  528. const auto make{[&](Id element_type, u32 element_size) {
  529. const u32 num_elements{Common::DivCeil(program.shared_memory_size, element_size)};
  530. const Id array_type{TypeArray(element_type, Const(num_elements))};
  531. Decorate(array_type, spv::Decoration::ArrayStride, element_size);
  532. const Id struct_type{TypeStruct(array_type)};
  533. MemberDecorate(struct_type, 0U, spv::Decoration::Offset, 0U);
  534. Decorate(struct_type, spv::Decoration::Block);
  535. const Id pointer{TypePointer(spv::StorageClass::Workgroup, struct_type)};
  536. const Id element_pointer{TypePointer(spv::StorageClass::Workgroup, element_type)};
  537. const Id variable{AddGlobalVariable(pointer, spv::StorageClass::Workgroup)};
  538. Decorate(variable, spv::Decoration::Aliased);
  539. interfaces.push_back(variable);
  540. return std::make_tuple(variable, element_pointer, pointer);
  541. }};
  542. if (profile.support_explicit_workgroup_layout) {
  543. AddExtension("SPV_KHR_workgroup_memory_explicit_layout");
  544. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayoutKHR);
  545. if (program.info.uses_int8) {
  546. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayout8BitAccessKHR);
  547. std::tie(shared_memory_u8, shared_u8, std::ignore) = make(U8, 1);
  548. }
  549. if (program.info.uses_int16) {
  550. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayout16BitAccessKHR);
  551. std::tie(shared_memory_u16, shared_u16, std::ignore) = make(U16, 2);
  552. }
  553. if (program.info.uses_int64) {
  554. std::tie(shared_memory_u64, shared_u64, std::ignore) = make(U64, 8);
  555. }
  556. std::tie(shared_memory_u32, shared_u32, shared_memory_u32_type) = make(U32[1], 4);
  557. std::tie(shared_memory_u32x2, shared_u32x2, std::ignore) = make(U32[2], 8);
  558. std::tie(shared_memory_u32x4, shared_u32x4, std::ignore) = make(U32[4], 16);
  559. return;
  560. }
  561. const u32 num_elements{Common::DivCeil(program.shared_memory_size, 4U)};
  562. const Id type{TypeArray(U32[1], Const(num_elements))};
  563. shared_memory_u32_type = TypePointer(spv::StorageClass::Workgroup, type);
  564. shared_u32 = TypePointer(spv::StorageClass::Workgroup, U32[1]);
  565. shared_memory_u32 = AddGlobalVariable(shared_memory_u32_type, spv::StorageClass::Workgroup);
  566. interfaces.push_back(shared_memory_u32);
  567. const Id func_type{TypeFunction(void_id, U32[1], U32[1])};
  568. const auto make_function{[&](u32 mask, u32 size) {
  569. const Id loop_header{OpLabel()};
  570. const Id continue_block{OpLabel()};
  571. const Id merge_block{OpLabel()};
  572. const Id func{OpFunction(void_id, spv::FunctionControlMask::MaskNone, func_type)};
  573. const Id offset{OpFunctionParameter(U32[1])};
  574. const Id insert_value{OpFunctionParameter(U32[1])};
  575. AddLabel();
  576. OpBranch(loop_header);
  577. AddLabel(loop_header);
  578. const Id word_offset{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  579. const Id shift_offset{OpShiftLeftLogical(U32[1], offset, Const(3U))};
  580. const Id bit_offset{OpBitwiseAnd(U32[1], shift_offset, Const(mask))};
  581. const Id count{Const(size)};
  582. OpLoopMerge(merge_block, continue_block, spv::LoopControlMask::MaskNone);
  583. OpBranch(continue_block);
  584. AddLabel(continue_block);
  585. const Id word_pointer{OpAccessChain(shared_u32, shared_memory_u32, word_offset)};
  586. const Id old_value{OpLoad(U32[1], word_pointer)};
  587. const Id new_value{OpBitFieldInsert(U32[1], old_value, insert_value, bit_offset, count)};
  588. const Id atomic_res{OpAtomicCompareExchange(U32[1], word_pointer, Const(1U), u32_zero_value,
  589. u32_zero_value, new_value, old_value)};
  590. const Id success{OpIEqual(U1, atomic_res, old_value)};
  591. OpBranchConditional(success, merge_block, loop_header);
  592. AddLabel(merge_block);
  593. OpReturn();
  594. OpFunctionEnd();
  595. return func;
  596. }};
  597. if (program.info.uses_int8) {
  598. shared_store_u8_func = make_function(24, 8);
  599. }
  600. if (program.info.uses_int16) {
  601. shared_store_u16_func = make_function(16, 16);
  602. }
  603. }
  604. void EmitContext::DefineSharedMemoryFunctions(const IR::Program& program) {
  605. if (program.info.uses_shared_increment) {
  606. increment_cas_shared = CasLoop(*this, Operation::Increment, shared_memory_u32_type,
  607. shared_u32, U32[1], U32[1], spv::Scope::Workgroup);
  608. }
  609. if (program.info.uses_shared_decrement) {
  610. decrement_cas_shared = CasLoop(*this, Operation::Decrement, shared_memory_u32_type,
  611. shared_u32, U32[1], U32[1], spv::Scope::Workgroup);
  612. }
  613. }
  614. void EmitContext::DefineAttributeMemAccess(const Info& info) {
  615. const auto make_load{[&] {
  616. const bool is_array{stage == Stage::Geometry};
  617. const Id end_block{OpLabel()};
  618. const Id default_label{OpLabel()};
  619. const Id func_type_load{is_array ? TypeFunction(F32[1], U32[1], U32[1])
  620. : TypeFunction(F32[1], U32[1])};
  621. const Id func{OpFunction(F32[1], spv::FunctionControlMask::MaskNone, func_type_load)};
  622. const Id offset{OpFunctionParameter(U32[1])};
  623. const Id vertex{is_array ? OpFunctionParameter(U32[1]) : Id{}};
  624. AddLabel();
  625. const Id base_index{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  626. const Id masked_index{OpBitwiseAnd(U32[1], base_index, Const(3U))};
  627. const Id compare_index{OpShiftRightArithmetic(U32[1], base_index, Const(2U))};
  628. std::vector<Sirit::Literal> literals;
  629. std::vector<Id> labels;
  630. if (info.loads.AnyComponent(IR::Attribute::PositionX)) {
  631. literals.push_back(static_cast<u32>(IR::Attribute::PositionX) >> 2);
  632. labels.push_back(OpLabel());
  633. }
  634. const u32 base_attribute_value = static_cast<u32>(IR::Attribute::Generic0X) >> 2;
  635. for (u32 index = 0; index < static_cast<u32>(IR::NUM_GENERICS); ++index) {
  636. if (!info.loads.Generic(index)) {
  637. continue;
  638. }
  639. literals.push_back(base_attribute_value + index);
  640. labels.push_back(OpLabel());
  641. }
  642. OpSelectionMerge(end_block, spv::SelectionControlMask::MaskNone);
  643. OpSwitch(compare_index, default_label, literals, labels);
  644. AddLabel(default_label);
  645. OpReturnValue(Const(0.0f));
  646. size_t label_index{0};
  647. if (info.loads.AnyComponent(IR::Attribute::PositionX)) {
  648. AddLabel(labels[label_index]);
  649. const Id pointer{is_array
  650. ? OpAccessChain(input_f32, input_position, vertex, masked_index)
  651. : OpAccessChain(input_f32, input_position, masked_index)};
  652. const Id result{OpLoad(F32[1], pointer)};
  653. OpReturnValue(result);
  654. ++label_index;
  655. }
  656. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  657. if (!info.loads.Generic(index)) {
  658. continue;
  659. }
  660. AddLabel(labels[label_index]);
  661. const auto type{AttrTypes(*this, static_cast<u32>(index))};
  662. if (!type) {
  663. OpReturnValue(Const(0.0f));
  664. ++label_index;
  665. continue;
  666. }
  667. const Id generic_id{input_generics.at(index)};
  668. const Id pointer{is_array
  669. ? OpAccessChain(type->pointer, generic_id, vertex, masked_index)
  670. : OpAccessChain(type->pointer, generic_id, masked_index)};
  671. const Id value{OpLoad(type->id, pointer)};
  672. const Id result{type->needs_cast ? OpBitcast(F32[1], value) : value};
  673. OpReturnValue(result);
  674. ++label_index;
  675. }
  676. AddLabel(end_block);
  677. OpUnreachable();
  678. OpFunctionEnd();
  679. return func;
  680. }};
  681. const auto make_store{[&] {
  682. const Id end_block{OpLabel()};
  683. const Id default_label{OpLabel()};
  684. const Id func_type_store{TypeFunction(void_id, U32[1], F32[1])};
  685. const Id func{OpFunction(void_id, spv::FunctionControlMask::MaskNone, func_type_store)};
  686. const Id offset{OpFunctionParameter(U32[1])};
  687. const Id store_value{OpFunctionParameter(F32[1])};
  688. AddLabel();
  689. const Id base_index{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  690. const Id masked_index{OpBitwiseAnd(U32[1], base_index, Const(3U))};
  691. const Id compare_index{OpShiftRightArithmetic(U32[1], base_index, Const(2U))};
  692. std::vector<Sirit::Literal> literals;
  693. std::vector<Id> labels;
  694. if (info.stores.AnyComponent(IR::Attribute::PositionX)) {
  695. literals.push_back(static_cast<u32>(IR::Attribute::PositionX) >> 2);
  696. labels.push_back(OpLabel());
  697. }
  698. const u32 base_attribute_value = static_cast<u32>(IR::Attribute::Generic0X) >> 2;
  699. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  700. if (!info.stores.Generic(index)) {
  701. continue;
  702. }
  703. literals.push_back(base_attribute_value + static_cast<u32>(index));
  704. labels.push_back(OpLabel());
  705. }
  706. if (info.stores.ClipDistances()) {
  707. literals.push_back(static_cast<u32>(IR::Attribute::ClipDistance0) >> 2);
  708. labels.push_back(OpLabel());
  709. literals.push_back(static_cast<u32>(IR::Attribute::ClipDistance4) >> 2);
  710. labels.push_back(OpLabel());
  711. }
  712. OpSelectionMerge(end_block, spv::SelectionControlMask::MaskNone);
  713. OpSwitch(compare_index, default_label, literals, labels);
  714. AddLabel(default_label);
  715. OpReturn();
  716. size_t label_index{0};
  717. if (info.stores.AnyComponent(IR::Attribute::PositionX)) {
  718. AddLabel(labels[label_index]);
  719. const Id pointer{OpAccessChain(output_f32, output_position, masked_index)};
  720. OpStore(pointer, store_value);
  721. OpReturn();
  722. ++label_index;
  723. }
  724. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  725. if (!info.stores.Generic(index)) {
  726. continue;
  727. }
  728. if (output_generics[index][0].num_components != 4) {
  729. throw NotImplementedException("Physical stores and transform feedbacks");
  730. }
  731. AddLabel(labels[label_index]);
  732. const Id generic_id{output_generics[index][0].id};
  733. const Id pointer{OpAccessChain(output_f32, generic_id, masked_index)};
  734. OpStore(pointer, store_value);
  735. OpReturn();
  736. ++label_index;
  737. }
  738. if (info.stores.ClipDistances()) {
  739. AddLabel(labels[label_index]);
  740. const Id pointer{OpAccessChain(output_f32, clip_distances, masked_index)};
  741. OpStore(pointer, store_value);
  742. OpReturn();
  743. ++label_index;
  744. AddLabel(labels[label_index]);
  745. const Id fixed_index{OpIAdd(U32[1], masked_index, Const(4U))};
  746. const Id pointer2{OpAccessChain(output_f32, clip_distances, fixed_index)};
  747. OpStore(pointer2, store_value);
  748. OpReturn();
  749. ++label_index;
  750. }
  751. AddLabel(end_block);
  752. OpUnreachable();
  753. OpFunctionEnd();
  754. return func;
  755. }};
  756. if (info.loads_indexed_attributes) {
  757. indexed_load_func = make_load();
  758. }
  759. if (info.stores_indexed_attributes) {
  760. indexed_store_func = make_store();
  761. }
  762. }
  763. void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
  764. if (!info.uses_global_memory || !profile.support_int64) {
  765. return;
  766. }
  767. using DefPtr = Id StorageDefinitions::*;
  768. const Id zero{u32_zero_value};
  769. const auto define_body{[&](DefPtr ssbo_member, Id addr, Id element_pointer, u32 shift,
  770. auto&& callback) {
  771. AddLabel();
  772. const size_t num_buffers{info.storage_buffers_descriptors.size()};
  773. for (size_t index = 0; index < num_buffers; ++index) {
  774. if (!info.nvn_buffer_used[index]) {
  775. continue;
  776. }
  777. const auto& ssbo{info.storage_buffers_descriptors[index]};
  778. const Id ssbo_addr_cbuf_offset{Const(ssbo.cbuf_offset / 8)};
  779. const Id ssbo_size_cbuf_offset{Const(ssbo.cbuf_offset / 4 + 2)};
  780. const Id ssbo_addr_pointer{OpAccessChain(
  781. uniform_types.U32x2, cbufs[ssbo.cbuf_index].U32x2, zero, ssbo_addr_cbuf_offset)};
  782. const Id ssbo_size_pointer{OpAccessChain(uniform_types.U32, cbufs[ssbo.cbuf_index].U32,
  783. zero, ssbo_size_cbuf_offset)};
  784. const Id ssbo_addr{OpBitcast(U64, OpLoad(U32[2], ssbo_addr_pointer))};
  785. const Id ssbo_size{OpUConvert(U64, OpLoad(U32[1], ssbo_size_pointer))};
  786. const Id ssbo_end{OpIAdd(U64, ssbo_addr, ssbo_size)};
  787. const Id cond{OpLogicalAnd(U1, OpUGreaterThanEqual(U1, addr, ssbo_addr),
  788. OpULessThan(U1, addr, ssbo_end))};
  789. const Id then_label{OpLabel()};
  790. const Id else_label{OpLabel()};
  791. OpSelectionMerge(else_label, spv::SelectionControlMask::MaskNone);
  792. OpBranchConditional(cond, then_label, else_label);
  793. AddLabel(then_label);
  794. const Id ssbo_id{ssbos[index].*ssbo_member};
  795. const Id ssbo_offset{OpUConvert(U32[1], OpISub(U64, addr, ssbo_addr))};
  796. const Id ssbo_index{OpShiftRightLogical(U32[1], ssbo_offset, Const(shift))};
  797. const Id ssbo_pointer{OpAccessChain(element_pointer, ssbo_id, zero, ssbo_index)};
  798. callback(ssbo_pointer);
  799. AddLabel(else_label);
  800. }
  801. }};
  802. const auto define_load{[&](DefPtr ssbo_member, Id element_pointer, Id type, u32 shift) {
  803. const Id function_type{TypeFunction(type, U64)};
  804. const Id func_id{OpFunction(type, spv::FunctionControlMask::MaskNone, function_type)};
  805. const Id addr{OpFunctionParameter(U64)};
  806. define_body(ssbo_member, addr, element_pointer, shift,
  807. [&](Id ssbo_pointer) { OpReturnValue(OpLoad(type, ssbo_pointer)); });
  808. OpReturnValue(ConstantNull(type));
  809. OpFunctionEnd();
  810. return func_id;
  811. }};
  812. const auto define_write{[&](DefPtr ssbo_member, Id element_pointer, Id type, u32 shift) {
  813. const Id function_type{TypeFunction(void_id, U64, type)};
  814. const Id func_id{OpFunction(void_id, spv::FunctionControlMask::MaskNone, function_type)};
  815. const Id addr{OpFunctionParameter(U64)};
  816. const Id data{OpFunctionParameter(type)};
  817. define_body(ssbo_member, addr, element_pointer, shift, [&](Id ssbo_pointer) {
  818. OpStore(ssbo_pointer, data);
  819. OpReturn();
  820. });
  821. OpReturn();
  822. OpFunctionEnd();
  823. return func_id;
  824. }};
  825. const auto define{
  826. [&](DefPtr ssbo_member, const StorageTypeDefinition& type_def, Id type, size_t size) {
  827. const Id element_type{type_def.element};
  828. const u32 shift{static_cast<u32>(std::countr_zero(size))};
  829. const Id load_func{define_load(ssbo_member, element_type, type, shift)};
  830. const Id write_func{define_write(ssbo_member, element_type, type, shift)};
  831. return std::make_pair(load_func, write_func);
  832. }};
  833. std::tie(load_global_func_u32, write_global_func_u32) =
  834. define(&StorageDefinitions::U32, storage_types.U32, U32[1], sizeof(u32));
  835. std::tie(load_global_func_u32x2, write_global_func_u32x2) =
  836. define(&StorageDefinitions::U32x2, storage_types.U32x2, U32[2], sizeof(u32[2]));
  837. std::tie(load_global_func_u32x4, write_global_func_u32x4) =
  838. define(&StorageDefinitions::U32x4, storage_types.U32x4, U32[4], sizeof(u32[4]));
  839. }
  840. void EmitContext::DefineConstantBuffers(const Info& info, u32& binding) {
  841. if (info.constant_buffer_descriptors.empty()) {
  842. return;
  843. }
  844. if (!profile.support_descriptor_aliasing) {
  845. DefineConstBuffers(*this, info, &UniformDefinitions::U32x4, binding, U32[4], 'u',
  846. sizeof(u32[4]));
  847. for (const ConstantBufferDescriptor& desc : info.constant_buffer_descriptors) {
  848. binding += desc.count;
  849. }
  850. return;
  851. }
  852. IR::Type types{info.used_constant_buffer_types};
  853. if (True(types & IR::Type::U8)) {
  854. if (profile.support_int8) {
  855. DefineConstBuffers(*this, info, &UniformDefinitions::U8, binding, U8, 'u', sizeof(u8));
  856. DefineConstBuffers(*this, info, &UniformDefinitions::S8, binding, S8, 's', sizeof(s8));
  857. } else {
  858. types |= IR::Type::U32;
  859. }
  860. }
  861. if (True(types & IR::Type::U16)) {
  862. if (profile.support_int16) {
  863. DefineConstBuffers(*this, info, &UniformDefinitions::U16, binding, U16, 'u',
  864. sizeof(u16));
  865. DefineConstBuffers(*this, info, &UniformDefinitions::S16, binding, S16, 's',
  866. sizeof(s16));
  867. } else {
  868. types |= IR::Type::U32;
  869. }
  870. }
  871. if (True(types & IR::Type::U32)) {
  872. DefineConstBuffers(*this, info, &UniformDefinitions::U32, binding, U32[1], 'u',
  873. sizeof(u32));
  874. }
  875. if (True(types & IR::Type::F32)) {
  876. DefineConstBuffers(*this, info, &UniformDefinitions::F32, binding, F32[1], 'f',
  877. sizeof(f32));
  878. }
  879. if (True(types & IR::Type::U32x2)) {
  880. DefineConstBuffers(*this, info, &UniformDefinitions::U32x2, binding, U32[2], 'u',
  881. sizeof(u32[2]));
  882. }
  883. binding += static_cast<u32>(info.constant_buffer_descriptors.size());
  884. }
  885. void EmitContext::DefineStorageBuffers(const Info& info, u32& binding) {
  886. if (info.storage_buffers_descriptors.empty()) {
  887. return;
  888. }
  889. AddExtension("SPV_KHR_storage_buffer_storage_class");
  890. const IR::Type used_types{profile.support_descriptor_aliasing ? info.used_storage_buffer_types
  891. : IR::Type::U32};
  892. if (profile.support_int8 && True(used_types & IR::Type::U8)) {
  893. DefineSsbos(*this, storage_types.U8, &StorageDefinitions::U8, info, binding, U8,
  894. sizeof(u8));
  895. DefineSsbos(*this, storage_types.S8, &StorageDefinitions::S8, info, binding, S8,
  896. sizeof(u8));
  897. }
  898. if (profile.support_int16 && True(used_types & IR::Type::U16)) {
  899. DefineSsbos(*this, storage_types.U16, &StorageDefinitions::U16, info, binding, U16,
  900. sizeof(u16));
  901. DefineSsbos(*this, storage_types.S16, &StorageDefinitions::S16, info, binding, S16,
  902. sizeof(u16));
  903. }
  904. if (True(used_types & IR::Type::U32)) {
  905. DefineSsbos(*this, storage_types.U32, &StorageDefinitions::U32, info, binding, U32[1],
  906. sizeof(u32));
  907. }
  908. if (True(used_types & IR::Type::F32)) {
  909. DefineSsbos(*this, storage_types.F32, &StorageDefinitions::F32, info, binding, F32[1],
  910. sizeof(f32));
  911. }
  912. if (True(used_types & IR::Type::U64)) {
  913. DefineSsbos(*this, storage_types.U64, &StorageDefinitions::U64, info, binding, U64,
  914. sizeof(u64));
  915. }
  916. if (True(used_types & IR::Type::U32x2)) {
  917. DefineSsbos(*this, storage_types.U32x2, &StorageDefinitions::U32x2, info, binding, U32[2],
  918. sizeof(u32[2]));
  919. }
  920. if (True(used_types & IR::Type::U32x4)) {
  921. DefineSsbos(*this, storage_types.U32x4, &StorageDefinitions::U32x4, info, binding, U32[4],
  922. sizeof(u32[4]));
  923. }
  924. for (const StorageBufferDescriptor& desc : info.storage_buffers_descriptors) {
  925. binding += desc.count;
  926. }
  927. const bool needs_function{
  928. info.uses_global_increment || info.uses_global_decrement || info.uses_atomic_f32_add ||
  929. info.uses_atomic_f16x2_add || info.uses_atomic_f16x2_min || info.uses_atomic_f16x2_max ||
  930. info.uses_atomic_f32x2_add || info.uses_atomic_f32x2_min || info.uses_atomic_f32x2_max};
  931. if (needs_function) {
  932. AddCapability(spv::Capability::VariablePointersStorageBuffer);
  933. }
  934. if (info.uses_global_increment) {
  935. increment_cas_ssbo = CasLoop(*this, Operation::Increment, storage_types.U32.array,
  936. storage_types.U32.element, U32[1], U32[1], spv::Scope::Device);
  937. }
  938. if (info.uses_global_decrement) {
  939. decrement_cas_ssbo = CasLoop(*this, Operation::Decrement, storage_types.U32.array,
  940. storage_types.U32.element, U32[1], U32[1], spv::Scope::Device);
  941. }
  942. if (info.uses_atomic_f32_add) {
  943. f32_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  944. storage_types.U32.element, F32[1], U32[1], spv::Scope::Device);
  945. }
  946. if (info.uses_atomic_f16x2_add) {
  947. f16x2_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  948. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  949. }
  950. if (info.uses_atomic_f16x2_min) {
  951. f16x2_min_cas = CasLoop(*this, Operation::FPMin, storage_types.U32.array,
  952. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  953. }
  954. if (info.uses_atomic_f16x2_max) {
  955. f16x2_max_cas = CasLoop(*this, Operation::FPMax, storage_types.U32.array,
  956. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  957. }
  958. if (info.uses_atomic_f32x2_add) {
  959. f32x2_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  960. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  961. }
  962. if (info.uses_atomic_f32x2_min) {
  963. f32x2_min_cas = CasLoop(*this, Operation::FPMin, storage_types.U32.array,
  964. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  965. }
  966. if (info.uses_atomic_f32x2_max) {
  967. f32x2_max_cas = CasLoop(*this, Operation::FPMax, storage_types.U32.array,
  968. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  969. }
  970. }
  971. void EmitContext::DefineTextureBuffers(const Info& info, u32& binding) {
  972. if (info.texture_buffer_descriptors.empty()) {
  973. return;
  974. }
  975. const spv::ImageFormat format{spv::ImageFormat::Unknown};
  976. image_buffer_type = TypeImage(F32[1], spv::Dim::Buffer, 0U, false, false, 1, format);
  977. sampled_texture_buffer_type = TypeSampledImage(image_buffer_type);
  978. const Id type{TypePointer(spv::StorageClass::UniformConstant, sampled_texture_buffer_type)};
  979. texture_buffers.reserve(info.texture_buffer_descriptors.size());
  980. for (const TextureBufferDescriptor& desc : info.texture_buffer_descriptors) {
  981. if (desc.count != 1) {
  982. throw NotImplementedException("Array of texture buffers");
  983. }
  984. const Id id{AddGlobalVariable(type, spv::StorageClass::UniformConstant)};
  985. Decorate(id, spv::Decoration::Binding, binding);
  986. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  987. Name(id, NameOf(stage, desc, "texbuf"));
  988. texture_buffers.push_back({
  989. .id = id,
  990. .count = desc.count,
  991. });
  992. if (profile.supported_spirv >= 0x00010400) {
  993. interfaces.push_back(id);
  994. }
  995. ++binding;
  996. }
  997. }
  998. void EmitContext::DefineImageBuffers(const Info& info, u32& binding) {
  999. image_buffers.reserve(info.image_buffer_descriptors.size());
  1000. for (const ImageBufferDescriptor& desc : info.image_buffer_descriptors) {
  1001. if (desc.count != 1) {
  1002. throw NotImplementedException("Array of image buffers");
  1003. }
  1004. const spv::ImageFormat format{GetImageFormat(desc.format)};
  1005. const Id image_type{TypeImage(U32[1], spv::Dim::Buffer, false, false, false, 2, format)};
  1006. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
  1007. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  1008. Decorate(id, spv::Decoration::Binding, binding);
  1009. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1010. Name(id, NameOf(stage, desc, "imgbuf"));
  1011. image_buffers.push_back({
  1012. .id = id,
  1013. .image_type = image_type,
  1014. .count = desc.count,
  1015. });
  1016. if (profile.supported_spirv >= 0x00010400) {
  1017. interfaces.push_back(id);
  1018. }
  1019. ++binding;
  1020. }
  1021. }
  1022. void EmitContext::DefineTextures(const Info& info, u32& binding) {
  1023. textures.reserve(info.texture_descriptors.size());
  1024. for (const TextureDescriptor& desc : info.texture_descriptors) {
  1025. const Id image_type{ImageType(*this, desc)};
  1026. const Id sampled_type{TypeSampledImage(image_type)};
  1027. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, sampled_type)};
  1028. const Id desc_type{DescType(*this, sampled_type, pointer_type, desc.count)};
  1029. const Id id{AddGlobalVariable(desc_type, spv::StorageClass::UniformConstant)};
  1030. Decorate(id, spv::Decoration::Binding, binding);
  1031. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1032. Name(id, NameOf(stage, desc, "tex"));
  1033. textures.push_back({
  1034. .id = id,
  1035. .sampled_type = sampled_type,
  1036. .pointer_type = pointer_type,
  1037. .image_type = image_type,
  1038. .count = desc.count,
  1039. });
  1040. if (profile.supported_spirv >= 0x00010400) {
  1041. interfaces.push_back(id);
  1042. }
  1043. ++binding;
  1044. }
  1045. if (info.uses_atomic_image_u32) {
  1046. image_u32 = TypePointer(spv::StorageClass::Image, U32[1]);
  1047. }
  1048. }
  1049. void EmitContext::DefineImages(const Info& info, u32& binding) {
  1050. images.reserve(info.image_descriptors.size());
  1051. for (const ImageDescriptor& desc : info.image_descriptors) {
  1052. if (desc.count != 1) {
  1053. throw NotImplementedException("Array of images");
  1054. }
  1055. const Id image_type{ImageType(*this, desc)};
  1056. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
  1057. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  1058. Decorate(id, spv::Decoration::Binding, binding);
  1059. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1060. Name(id, NameOf(stage, desc, "img"));
  1061. images.push_back({
  1062. .id = id,
  1063. .image_type = image_type,
  1064. .count = desc.count,
  1065. });
  1066. if (profile.supported_spirv >= 0x00010400) {
  1067. interfaces.push_back(id);
  1068. }
  1069. ++binding;
  1070. }
  1071. }
  1072. void EmitContext::DefineInputs(const IR::Program& program) {
  1073. const Info& info{program.info};
  1074. const VaryingState loads{info.loads.mask | info.passthrough.mask};
  1075. if (info.uses_workgroup_id) {
  1076. workgroup_id = DefineInput(*this, U32[3], false, spv::BuiltIn::WorkgroupId);
  1077. }
  1078. if (info.uses_local_invocation_id) {
  1079. local_invocation_id = DefineInput(*this, U32[3], false, spv::BuiltIn::LocalInvocationId);
  1080. }
  1081. if (info.uses_invocation_id) {
  1082. invocation_id = DefineInput(*this, U32[1], false, spv::BuiltIn::InvocationId);
  1083. }
  1084. if (info.uses_sample_id) {
  1085. sample_id = DefineInput(*this, U32[1], false, spv::BuiltIn::SampleId);
  1086. }
  1087. if (info.uses_is_helper_invocation) {
  1088. is_helper_invocation = DefineInput(*this, U1, false, spv::BuiltIn::HelperInvocation);
  1089. }
  1090. if (info.uses_subgroup_mask) {
  1091. subgroup_mask_eq = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupEqMaskKHR);
  1092. subgroup_mask_lt = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLtMaskKHR);
  1093. subgroup_mask_le = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLeMaskKHR);
  1094. subgroup_mask_gt = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupGtMaskKHR);
  1095. subgroup_mask_ge = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupGeMaskKHR);
  1096. }
  1097. if (info.uses_subgroup_invocation_id || info.uses_subgroup_shuffles ||
  1098. (profile.warp_size_potentially_larger_than_guest &&
  1099. (info.uses_subgroup_vote || info.uses_subgroup_mask))) {
  1100. subgroup_local_invocation_id =
  1101. DefineInput(*this, U32[1], false, spv::BuiltIn::SubgroupLocalInvocationId);
  1102. }
  1103. if (info.uses_fswzadd) {
  1104. const Id f32_one{Const(1.0f)};
  1105. const Id f32_minus_one{Const(-1.0f)};
  1106. const Id f32_zero{Const(0.0f)};
  1107. fswzadd_lut_a = ConstantComposite(F32[4], f32_minus_one, f32_one, f32_minus_one, f32_zero);
  1108. fswzadd_lut_b =
  1109. ConstantComposite(F32[4], f32_minus_one, f32_minus_one, f32_one, f32_minus_one);
  1110. }
  1111. if (loads[IR::Attribute::PrimitiveId]) {
  1112. primitive_id = DefineInput(*this, U32[1], false, spv::BuiltIn::PrimitiveId);
  1113. }
  1114. if (loads.AnyComponent(IR::Attribute::PositionX)) {
  1115. const bool is_fragment{stage != Stage::Fragment};
  1116. const spv::BuiltIn built_in{is_fragment ? spv::BuiltIn::Position : spv::BuiltIn::FragCoord};
  1117. input_position = DefineInput(*this, F32[4], true, built_in);
  1118. if (profile.support_geometry_shader_passthrough) {
  1119. if (info.passthrough.AnyComponent(IR::Attribute::PositionX)) {
  1120. Decorate(input_position, spv::Decoration::PassthroughNV);
  1121. }
  1122. }
  1123. }
  1124. if (loads.AnyComponent(IR::Attribute::ColorFrontDiffuseR)) {
  1125. const Id id{DefineInput(*this, F32[4], true)};
  1126. Decorate(id, spv::Decoration::Location, static_cast<u32>(11));
  1127. input_front_color = id;
  1128. }
  1129. if (loads.AnyComponent(IR::Attribute::FixedFncTexture0S)) {
  1130. const Id id{DefineInput(*this, F32[4], true)};
  1131. Decorate(id, spv::Decoration::Location, static_cast<u32>(12));
  1132. input_txt_coord = id;
  1133. }
  1134. if (loads[IR::Attribute::InstanceId]) {
  1135. if (profile.support_vertex_instance_id) {
  1136. instance_id = DefineInput(*this, U32[1], true, spv::BuiltIn::InstanceId);
  1137. } else {
  1138. instance_index = DefineInput(*this, U32[1], true, spv::BuiltIn::InstanceIndex);
  1139. base_instance = DefineInput(*this, U32[1], true, spv::BuiltIn::BaseInstance);
  1140. }
  1141. }
  1142. if (loads[IR::Attribute::VertexId]) {
  1143. if (profile.support_vertex_instance_id) {
  1144. vertex_id = DefineInput(*this, U32[1], true, spv::BuiltIn::VertexId);
  1145. } else {
  1146. vertex_index = DefineInput(*this, U32[1], true, spv::BuiltIn::VertexIndex);
  1147. base_vertex = DefineInput(*this, U32[1], true, spv::BuiltIn::BaseVertex);
  1148. }
  1149. }
  1150. if (loads[IR::Attribute::FrontFace]) {
  1151. front_face = DefineInput(*this, U1, true, spv::BuiltIn::FrontFacing);
  1152. }
  1153. if (loads[IR::Attribute::PointSpriteS] || loads[IR::Attribute::PointSpriteT]) {
  1154. point_coord = DefineInput(*this, F32[2], true, spv::BuiltIn::PointCoord);
  1155. }
  1156. if (loads[IR::Attribute::TessellationEvaluationPointU] ||
  1157. loads[IR::Attribute::TessellationEvaluationPointV]) {
  1158. tess_coord = DefineInput(*this, F32[3], false, spv::BuiltIn::TessCoord);
  1159. }
  1160. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  1161. const AttributeType input_type{runtime_info.generic_input_types[index]};
  1162. if (!runtime_info.previous_stage_stores.Generic(index)) {
  1163. continue;
  1164. }
  1165. if (!loads.Generic(index)) {
  1166. continue;
  1167. }
  1168. if (input_type == AttributeType::Disabled) {
  1169. continue;
  1170. }
  1171. const Id type{GetAttributeType(*this, input_type)};
  1172. const Id id{DefineInput(*this, type, true)};
  1173. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1174. Name(id, fmt::format("in_attr{}", index));
  1175. input_generics[index] = id;
  1176. if (info.passthrough.Generic(index) && profile.support_geometry_shader_passthrough) {
  1177. Decorate(id, spv::Decoration::PassthroughNV);
  1178. }
  1179. if (stage != Stage::Fragment) {
  1180. continue;
  1181. }
  1182. switch (info.interpolation[index]) {
  1183. case Interpolation::Smooth:
  1184. // Default
  1185. // Decorate(id, spv::Decoration::Smooth);
  1186. break;
  1187. case Interpolation::NoPerspective:
  1188. Decorate(id, spv::Decoration::NoPerspective);
  1189. break;
  1190. case Interpolation::Flat:
  1191. Decorate(id, spv::Decoration::Flat);
  1192. break;
  1193. }
  1194. }
  1195. if (stage == Stage::TessellationEval) {
  1196. for (size_t index = 0; index < info.uses_patches.size(); ++index) {
  1197. if (!info.uses_patches[index]) {
  1198. continue;
  1199. }
  1200. const Id id{DefineInput(*this, F32[4], false)};
  1201. Decorate(id, spv::Decoration::Patch);
  1202. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1203. patches[index] = id;
  1204. }
  1205. }
  1206. }
  1207. void EmitContext::DefineOutputs(const IR::Program& program) {
  1208. const Info& info{program.info};
  1209. const std::optional<u32> invocations{program.invocations};
  1210. if (info.stores.AnyComponent(IR::Attribute::PositionX) || stage == Stage::VertexB) {
  1211. output_position = DefineOutput(*this, F32[4], invocations, spv::BuiltIn::Position);
  1212. }
  1213. if (info.stores.AnyComponent(IR::Attribute::ColorFrontDiffuseR) || stage == Stage::VertexB) {
  1214. const Id id{DefineOutput(*this, F32[4], invocations)};
  1215. Decorate(id, spv::Decoration::Location, static_cast<u32>(11));
  1216. output_front_color = id;
  1217. }
  1218. if (info.stores[IR::Attribute::PointSize] || runtime_info.fixed_state_point_size) {
  1219. if (stage == Stage::Fragment) {
  1220. throw NotImplementedException("Storing PointSize in fragment stage");
  1221. }
  1222. output_point_size = DefineOutput(*this, F32[1], invocations, spv::BuiltIn::PointSize);
  1223. }
  1224. if (info.stores.ClipDistances()) {
  1225. if (stage == Stage::Fragment) {
  1226. throw NotImplementedException("Storing ClipDistance in fragment stage");
  1227. }
  1228. const Id type{TypeArray(F32[1], Const(8U))};
  1229. clip_distances = DefineOutput(*this, type, invocations, spv::BuiltIn::ClipDistance);
  1230. }
  1231. if (info.stores[IR::Attribute::Layer] &&
  1232. (profile.support_viewport_index_layer_non_geometry || stage == Stage::Geometry)) {
  1233. if (stage == Stage::Fragment) {
  1234. throw NotImplementedException("Storing Layer in fragment stage");
  1235. }
  1236. layer = DefineOutput(*this, U32[1], invocations, spv::BuiltIn::Layer);
  1237. }
  1238. if (info.stores[IR::Attribute::ViewportIndex] &&
  1239. (profile.support_viewport_index_layer_non_geometry || stage == Stage::Geometry)) {
  1240. if (stage == Stage::Fragment) {
  1241. throw NotImplementedException("Storing ViewportIndex in fragment stage");
  1242. }
  1243. viewport_index = DefineOutput(*this, U32[1], invocations, spv::BuiltIn::ViewportIndex);
  1244. }
  1245. if (info.stores[IR::Attribute::ViewportMask] && profile.support_viewport_mask) {
  1246. viewport_mask = DefineOutput(*this, TypeArray(U32[1], Const(1u)), std::nullopt,
  1247. spv::BuiltIn::ViewportMaskNV);
  1248. }
  1249. if (info.stores.AnyComponent(IR::Attribute::FixedFncTexture0S)) {
  1250. const Id id{DefineOutput(*this, F32[4], invocations)};
  1251. Decorate(id, spv::Decoration::Location, static_cast<u32>(12));
  1252. output_txt_coord = id;
  1253. }
  1254. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  1255. if (info.stores.Generic(index)) {
  1256. DefineGenericOutput(*this, index, invocations);
  1257. }
  1258. }
  1259. switch (stage) {
  1260. case Stage::TessellationControl:
  1261. if (info.stores_tess_level_outer) {
  1262. const Id type{TypeArray(F32[1], Const(4U))};
  1263. output_tess_level_outer =
  1264. DefineOutput(*this, type, std::nullopt, spv::BuiltIn::TessLevelOuter);
  1265. Decorate(output_tess_level_outer, spv::Decoration::Patch);
  1266. }
  1267. if (info.stores_tess_level_inner) {
  1268. const Id type{TypeArray(F32[1], Const(2U))};
  1269. output_tess_level_inner =
  1270. DefineOutput(*this, type, std::nullopt, spv::BuiltIn::TessLevelInner);
  1271. Decorate(output_tess_level_inner, spv::Decoration::Patch);
  1272. }
  1273. for (size_t index = 0; index < info.uses_patches.size(); ++index) {
  1274. if (!info.uses_patches[index]) {
  1275. continue;
  1276. }
  1277. const Id id{DefineOutput(*this, F32[4], std::nullopt)};
  1278. Decorate(id, spv::Decoration::Patch);
  1279. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1280. patches[index] = id;
  1281. }
  1282. break;
  1283. case Stage::Fragment:
  1284. for (u32 index = 0; index < 8; ++index) {
  1285. if (!info.stores_frag_color[index] && !profile.need_declared_frag_colors) {
  1286. continue;
  1287. }
  1288. frag_color[index] = DefineOutput(*this, F32[4], std::nullopt);
  1289. Decorate(frag_color[index], spv::Decoration::Location, index);
  1290. Name(frag_color[index], fmt::format("frag_color{}", index));
  1291. }
  1292. if (info.stores_frag_depth) {
  1293. frag_depth = DefineOutput(*this, F32[1], std::nullopt);
  1294. Decorate(frag_depth, spv::Decoration::BuiltIn, spv::BuiltIn::FragDepth);
  1295. }
  1296. if (info.stores_sample_mask) {
  1297. sample_mask = DefineOutput(*this, U32[1], std::nullopt);
  1298. Decorate(sample_mask, spv::Decoration::BuiltIn, spv::BuiltIn::SampleMask);
  1299. }
  1300. break;
  1301. default:
  1302. break;
  1303. }
  1304. }
  1305. } // namespace Shader::Backend::SPIRV