emit_context.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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 <boost/container/static_vector.hpp>
  9. #include <fmt/format.h>
  10. #include "common/common_types.h"
  11. #include "common/div_ceil.h"
  12. #include "shader_recompiler/backend/spirv/emit_context.h"
  13. #include "shader_recompiler/backend/spirv/emit_spirv.h"
  14. namespace Shader::Backend::SPIRV {
  15. namespace {
  16. constexpr size_t NUM_FIXEDFNCTEXTURE = 10;
  17. enum class Operation {
  18. Increment,
  19. Decrement,
  20. FPAdd,
  21. FPMin,
  22. FPMax,
  23. };
  24. struct AttrInfo {
  25. Id pointer;
  26. Id id;
  27. bool needs_cast;
  28. };
  29. Id ImageType(EmitContext& ctx, const TextureDescriptor& desc) {
  30. const spv::ImageFormat format{spv::ImageFormat::Unknown};
  31. const Id type{ctx.F32[1]};
  32. const bool depth{desc.is_depth};
  33. switch (desc.type) {
  34. case TextureType::Color1D:
  35. return ctx.TypeImage(type, spv::Dim::Dim1D, depth, false, false, 1, format);
  36. case TextureType::ColorArray1D:
  37. return ctx.TypeImage(type, spv::Dim::Dim1D, depth, true, false, 1, format);
  38. case TextureType::Color2D:
  39. return ctx.TypeImage(type, spv::Dim::Dim2D, depth, false, false, 1, format);
  40. case TextureType::ColorArray2D:
  41. return ctx.TypeImage(type, spv::Dim::Dim2D, depth, true, false, 1, format);
  42. case TextureType::Color3D:
  43. return ctx.TypeImage(type, spv::Dim::Dim3D, depth, false, false, 1, format);
  44. case TextureType::ColorCube:
  45. return ctx.TypeImage(type, spv::Dim::Cube, depth, false, false, 1, format);
  46. case TextureType::ColorArrayCube:
  47. return ctx.TypeImage(type, spv::Dim::Cube, depth, true, false, 1, format);
  48. case TextureType::Buffer:
  49. break;
  50. }
  51. throw InvalidArgument("Invalid texture type {}", desc.type);
  52. }
  53. spv::ImageFormat GetImageFormat(ImageFormat format) {
  54. switch (format) {
  55. case ImageFormat::Typeless:
  56. return spv::ImageFormat::Unknown;
  57. case ImageFormat::R8_UINT:
  58. return spv::ImageFormat::R8ui;
  59. case ImageFormat::R8_SINT:
  60. return spv::ImageFormat::R8i;
  61. case ImageFormat::R16_UINT:
  62. return spv::ImageFormat::R16ui;
  63. case ImageFormat::R16_SINT:
  64. return spv::ImageFormat::R16i;
  65. case ImageFormat::R32_UINT:
  66. return spv::ImageFormat::R32ui;
  67. case ImageFormat::R32G32_UINT:
  68. return spv::ImageFormat::Rg32ui;
  69. case ImageFormat::R32G32B32A32_UINT:
  70. return spv::ImageFormat::Rgba32ui;
  71. }
  72. throw InvalidArgument("Invalid image format {}", format);
  73. }
  74. Id ImageType(EmitContext& ctx, const ImageDescriptor& desc) {
  75. const spv::ImageFormat format{GetImageFormat(desc.format)};
  76. const Id type{ctx.U32[1]};
  77. switch (desc.type) {
  78. case TextureType::Color1D:
  79. return ctx.TypeImage(type, spv::Dim::Dim1D, false, false, false, 2, format);
  80. case TextureType::ColorArray1D:
  81. return ctx.TypeImage(type, spv::Dim::Dim1D, false, true, false, 2, format);
  82. case TextureType::Color2D:
  83. return ctx.TypeImage(type, spv::Dim::Dim2D, false, false, false, 2, format);
  84. case TextureType::ColorArray2D:
  85. return ctx.TypeImage(type, spv::Dim::Dim2D, false, true, false, 2, format);
  86. case TextureType::Color3D:
  87. return ctx.TypeImage(type, spv::Dim::Dim3D, false, false, false, 2, format);
  88. case TextureType::Buffer:
  89. throw NotImplementedException("Image buffer");
  90. default:
  91. break;
  92. }
  93. throw InvalidArgument("Invalid texture type {}", desc.type);
  94. }
  95. Id DefineVariable(EmitContext& ctx, Id type, std::optional<spv::BuiltIn> builtin,
  96. spv::StorageClass storage_class) {
  97. const Id pointer_type{ctx.TypePointer(storage_class, type)};
  98. const Id id{ctx.AddGlobalVariable(pointer_type, storage_class)};
  99. if (builtin) {
  100. ctx.Decorate(id, spv::Decoration::BuiltIn, *builtin);
  101. }
  102. ctx.interfaces.push_back(id);
  103. return id;
  104. }
  105. u32 NumVertices(InputTopology input_topology) {
  106. switch (input_topology) {
  107. case InputTopology::Points:
  108. return 1;
  109. case InputTopology::Lines:
  110. return 2;
  111. case InputTopology::LinesAdjacency:
  112. return 4;
  113. case InputTopology::Triangles:
  114. return 3;
  115. case InputTopology::TrianglesAdjacency:
  116. return 6;
  117. }
  118. throw InvalidArgument("Invalid input topology {}", input_topology);
  119. }
  120. Id DefineInput(EmitContext& ctx, Id type, bool per_invocation,
  121. std::optional<spv::BuiltIn> builtin = std::nullopt) {
  122. switch (ctx.stage) {
  123. case Stage::TessellationControl:
  124. case Stage::TessellationEval:
  125. if (per_invocation) {
  126. type = ctx.TypeArray(type, ctx.Const(32u));
  127. }
  128. break;
  129. case Stage::Geometry:
  130. if (per_invocation) {
  131. const u32 num_vertices{NumVertices(ctx.runtime_info.input_topology)};
  132. type = ctx.TypeArray(type, ctx.Const(num_vertices));
  133. }
  134. break;
  135. default:
  136. break;
  137. }
  138. return DefineVariable(ctx, type, builtin, spv::StorageClass::Input);
  139. }
  140. Id DefineOutput(EmitContext& ctx, Id type, std::optional<u32> invocations,
  141. std::optional<spv::BuiltIn> builtin = std::nullopt) {
  142. if (invocations && ctx.stage == Stage::TessellationControl) {
  143. type = ctx.TypeArray(type, ctx.Const(*invocations));
  144. }
  145. return DefineVariable(ctx, type, builtin, spv::StorageClass::Output);
  146. }
  147. void DefineGenericOutput(EmitContext& ctx, size_t index, std::optional<u32> invocations) {
  148. static constexpr std::string_view swizzle{"xyzw"};
  149. const size_t base_attr_index{static_cast<size_t>(IR::Attribute::Generic0X) + index * 4};
  150. u32 element{0};
  151. while (element < 4) {
  152. const u32 remainder{4 - element};
  153. const TransformFeedbackVarying* xfb_varying{};
  154. if (!ctx.runtime_info.xfb_varyings.empty()) {
  155. xfb_varying = &ctx.runtime_info.xfb_varyings[base_attr_index + element];
  156. xfb_varying = xfb_varying && xfb_varying->components > 0 ? xfb_varying : nullptr;
  157. }
  158. const u32 num_components{xfb_varying ? xfb_varying->components : remainder};
  159. const Id id{DefineOutput(ctx, ctx.F32[num_components], invocations)};
  160. ctx.Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  161. if (element > 0) {
  162. ctx.Decorate(id, spv::Decoration::Component, element);
  163. }
  164. if (xfb_varying) {
  165. ctx.Decorate(id, spv::Decoration::XfbBuffer, xfb_varying->buffer);
  166. ctx.Decorate(id, spv::Decoration::XfbStride, xfb_varying->stride);
  167. ctx.Decorate(id, spv::Decoration::Offset, xfb_varying->offset);
  168. }
  169. if (num_components < 4 || element > 0) {
  170. const std::string_view subswizzle{swizzle.substr(element, num_components)};
  171. ctx.Name(id, fmt::format("out_attr{}_{}", index, subswizzle));
  172. } else {
  173. ctx.Name(id, fmt::format("out_attr{}", index));
  174. }
  175. const GenericElementInfo info{
  176. .id = id,
  177. .first_element = element,
  178. .num_components = num_components,
  179. };
  180. std::fill_n(ctx.output_generics[index].begin() + element, num_components, info);
  181. element += num_components;
  182. }
  183. }
  184. Id GetAttributeType(EmitContext& ctx, AttributeType type) {
  185. switch (type) {
  186. case AttributeType::Float:
  187. return ctx.F32[4];
  188. case AttributeType::SignedInt:
  189. return ctx.TypeVector(ctx.TypeInt(32, true), 4);
  190. case AttributeType::UnsignedInt:
  191. return ctx.U32[4];
  192. case AttributeType::Disabled:
  193. break;
  194. }
  195. throw InvalidArgument("Invalid attribute type {}", type);
  196. }
  197. std::optional<AttrInfo> AttrTypes(EmitContext& ctx, u32 index) {
  198. const AttributeType type{ctx.runtime_info.generic_input_types.at(index)};
  199. switch (type) {
  200. case AttributeType::Float:
  201. return AttrInfo{ctx.input_f32, ctx.F32[1], false};
  202. case AttributeType::UnsignedInt:
  203. return AttrInfo{ctx.input_u32, ctx.U32[1], true};
  204. case AttributeType::SignedInt:
  205. return AttrInfo{ctx.input_s32, ctx.TypeInt(32, true), true};
  206. case AttributeType::Disabled:
  207. return std::nullopt;
  208. }
  209. throw InvalidArgument("Invalid attribute type {}", type);
  210. }
  211. std::string_view StageName(Stage stage) {
  212. switch (stage) {
  213. case Stage::VertexA:
  214. return "vs_a";
  215. case Stage::VertexB:
  216. return "vs";
  217. case Stage::TessellationControl:
  218. return "tcs";
  219. case Stage::TessellationEval:
  220. return "tes";
  221. case Stage::Geometry:
  222. return "gs";
  223. case Stage::Fragment:
  224. return "fs";
  225. case Stage::Compute:
  226. return "cs";
  227. }
  228. throw InvalidArgument("Invalid stage {}", stage);
  229. }
  230. template <typename... Args>
  231. void Name(EmitContext& ctx, Id object, std::string_view format_str, Args&&... args) {
  232. ctx.Name(object, fmt::format(fmt::runtime(format_str), StageName(ctx.stage),
  233. std::forward<Args>(args)...)
  234. .c_str());
  235. }
  236. void DefineConstBuffers(EmitContext& ctx, const Info& info, Id UniformDefinitions::*member_type,
  237. u32 binding, Id type, char type_char, u32 element_size) {
  238. const Id array_type{ctx.TypeArray(type, ctx.Const(65536U / element_size))};
  239. ctx.Decorate(array_type, spv::Decoration::ArrayStride, element_size);
  240. const Id struct_type{ctx.TypeStruct(array_type)};
  241. Name(ctx, struct_type, "{}_cbuf_block_{}{}", ctx.stage, type_char, element_size * CHAR_BIT);
  242. ctx.Decorate(struct_type, spv::Decoration::Block);
  243. ctx.MemberName(struct_type, 0, "data");
  244. ctx.MemberDecorate(struct_type, 0, spv::Decoration::Offset, 0U);
  245. const Id struct_pointer_type{ctx.TypePointer(spv::StorageClass::Uniform, struct_type)};
  246. const Id uniform_type{ctx.TypePointer(spv::StorageClass::Uniform, type)};
  247. ctx.uniform_types.*member_type = uniform_type;
  248. for (const ConstantBufferDescriptor& desc : info.constant_buffer_descriptors) {
  249. const Id id{ctx.AddGlobalVariable(struct_pointer_type, spv::StorageClass::Uniform)};
  250. ctx.Decorate(id, spv::Decoration::Binding, binding);
  251. ctx.Decorate(id, spv::Decoration::DescriptorSet, 0U);
  252. ctx.Name(id, fmt::format("c{}", desc.index));
  253. for (size_t i = 0; i < desc.count; ++i) {
  254. ctx.cbufs[desc.index + i].*member_type = id;
  255. }
  256. if (ctx.profile.supported_spirv >= 0x00010400) {
  257. ctx.interfaces.push_back(id);
  258. }
  259. binding += desc.count;
  260. }
  261. }
  262. void DefineSsbos(EmitContext& ctx, StorageTypeDefinition& type_def,
  263. Id StorageDefinitions::*member_type, const Info& info, u32 binding, Id type,
  264. u32 stride) {
  265. const Id array_type{ctx.TypeRuntimeArray(type)};
  266. ctx.Decorate(array_type, spv::Decoration::ArrayStride, stride);
  267. const Id struct_type{ctx.TypeStruct(array_type)};
  268. ctx.Decorate(struct_type, spv::Decoration::Block);
  269. ctx.MemberDecorate(struct_type, 0, spv::Decoration::Offset, 0U);
  270. const Id struct_pointer{ctx.TypePointer(spv::StorageClass::StorageBuffer, struct_type)};
  271. type_def.array = struct_pointer;
  272. type_def.element = ctx.TypePointer(spv::StorageClass::StorageBuffer, type);
  273. u32 index{};
  274. for (const StorageBufferDescriptor& desc : info.storage_buffers_descriptors) {
  275. const Id id{ctx.AddGlobalVariable(struct_pointer, spv::StorageClass::StorageBuffer)};
  276. ctx.Decorate(id, spv::Decoration::Binding, binding);
  277. ctx.Decorate(id, spv::Decoration::DescriptorSet, 0U);
  278. ctx.Name(id, fmt::format("ssbo{}", index));
  279. if (ctx.profile.supported_spirv >= 0x00010400) {
  280. ctx.interfaces.push_back(id);
  281. }
  282. for (size_t i = 0; i < desc.count; ++i) {
  283. ctx.ssbos[index + i].*member_type = id;
  284. }
  285. index += desc.count;
  286. binding += desc.count;
  287. }
  288. }
  289. Id CasFunction(EmitContext& ctx, Operation operation, Id value_type) {
  290. const Id func_type{ctx.TypeFunction(value_type, value_type, value_type)};
  291. const Id func{ctx.OpFunction(value_type, spv::FunctionControlMask::MaskNone, func_type)};
  292. const Id op_a{ctx.OpFunctionParameter(value_type)};
  293. const Id op_b{ctx.OpFunctionParameter(value_type)};
  294. ctx.AddLabel();
  295. Id result{};
  296. switch (operation) {
  297. case Operation::Increment: {
  298. const Id pred{ctx.OpUGreaterThanEqual(ctx.U1, op_a, op_b)};
  299. const Id incr{ctx.OpIAdd(value_type, op_a, ctx.Constant(value_type, 1))};
  300. result = ctx.OpSelect(value_type, pred, ctx.u32_zero_value, incr);
  301. break;
  302. }
  303. case Operation::Decrement: {
  304. const Id lhs{ctx.OpIEqual(ctx.U1, op_a, ctx.Constant(value_type, 0u))};
  305. const Id rhs{ctx.OpUGreaterThan(ctx.U1, op_a, op_b)};
  306. const Id pred{ctx.OpLogicalOr(ctx.U1, lhs, rhs)};
  307. const Id decr{ctx.OpISub(value_type, op_a, ctx.Constant(value_type, 1))};
  308. result = ctx.OpSelect(value_type, pred, op_b, decr);
  309. break;
  310. }
  311. case Operation::FPAdd:
  312. result = ctx.OpFAdd(value_type, op_a, op_b);
  313. break;
  314. case Operation::FPMin:
  315. result = ctx.OpFMin(value_type, op_a, op_b);
  316. break;
  317. case Operation::FPMax:
  318. result = ctx.OpFMax(value_type, op_a, op_b);
  319. break;
  320. default:
  321. break;
  322. }
  323. ctx.OpReturnValue(result);
  324. ctx.OpFunctionEnd();
  325. return func;
  326. }
  327. Id CasLoop(EmitContext& ctx, Operation operation, Id array_pointer, Id element_pointer,
  328. Id value_type, Id memory_type, spv::Scope scope) {
  329. const bool is_shared{scope == spv::Scope::Workgroup};
  330. const bool is_struct{!is_shared || ctx.profile.support_explicit_workgroup_layout};
  331. const Id cas_func{CasFunction(ctx, operation, value_type)};
  332. const Id zero{ctx.u32_zero_value};
  333. const Id scope_id{ctx.Const(static_cast<u32>(scope))};
  334. const Id loop_header{ctx.OpLabel()};
  335. const Id continue_block{ctx.OpLabel()};
  336. const Id merge_block{ctx.OpLabel()};
  337. const Id func_type{is_shared
  338. ? ctx.TypeFunction(value_type, ctx.U32[1], value_type)
  339. : ctx.TypeFunction(value_type, ctx.U32[1], value_type, array_pointer)};
  340. const Id func{ctx.OpFunction(value_type, spv::FunctionControlMask::MaskNone, func_type)};
  341. const Id index{ctx.OpFunctionParameter(ctx.U32[1])};
  342. const Id op_b{ctx.OpFunctionParameter(value_type)};
  343. const Id base{is_shared ? ctx.shared_memory_u32 : ctx.OpFunctionParameter(array_pointer)};
  344. ctx.AddLabel();
  345. ctx.OpBranch(loop_header);
  346. ctx.AddLabel(loop_header);
  347. ctx.OpLoopMerge(merge_block, continue_block, spv::LoopControlMask::MaskNone);
  348. ctx.OpBranch(continue_block);
  349. ctx.AddLabel(continue_block);
  350. const Id word_pointer{is_struct ? ctx.OpAccessChain(element_pointer, base, zero, index)
  351. : ctx.OpAccessChain(element_pointer, base, index)};
  352. if (value_type.value == ctx.F32[2].value) {
  353. const Id u32_value{ctx.OpLoad(ctx.U32[1], word_pointer)};
  354. const Id value{ctx.OpUnpackHalf2x16(ctx.F32[2], u32_value)};
  355. const Id new_value{ctx.OpFunctionCall(value_type, cas_func, value, op_b)};
  356. const Id u32_new_value{ctx.OpPackHalf2x16(ctx.U32[1], new_value)};
  357. const Id atomic_res{ctx.OpAtomicCompareExchange(ctx.U32[1], word_pointer, scope_id, zero,
  358. zero, u32_new_value, u32_value)};
  359. const Id success{ctx.OpIEqual(ctx.U1, atomic_res, u32_value)};
  360. ctx.OpBranchConditional(success, merge_block, loop_header);
  361. ctx.AddLabel(merge_block);
  362. ctx.OpReturnValue(ctx.OpUnpackHalf2x16(ctx.F32[2], atomic_res));
  363. } else {
  364. const Id value{ctx.OpLoad(memory_type, word_pointer)};
  365. const bool matching_type{value_type.value == memory_type.value};
  366. const Id bitcast_value{matching_type ? value : ctx.OpBitcast(value_type, value)};
  367. const Id cal_res{ctx.OpFunctionCall(value_type, cas_func, bitcast_value, op_b)};
  368. const Id new_value{matching_type ? cal_res : ctx.OpBitcast(memory_type, cal_res)};
  369. const Id atomic_res{ctx.OpAtomicCompareExchange(ctx.U32[1], word_pointer, scope_id, zero,
  370. zero, new_value, value)};
  371. const Id success{ctx.OpIEqual(ctx.U1, atomic_res, value)};
  372. ctx.OpBranchConditional(success, merge_block, loop_header);
  373. ctx.AddLabel(merge_block);
  374. ctx.OpReturnValue(ctx.OpBitcast(value_type, atomic_res));
  375. }
  376. ctx.OpFunctionEnd();
  377. return func;
  378. }
  379. template <typename Desc>
  380. std::string NameOf(Stage stage, const Desc& desc, std::string_view prefix) {
  381. if (desc.count > 1) {
  382. return fmt::format("{}_{}{}_{:02x}x{}", StageName(stage), prefix, desc.cbuf_index,
  383. desc.cbuf_offset, desc.count);
  384. } else {
  385. return fmt::format("{}_{}{}_{:02x}", StageName(stage), prefix, desc.cbuf_index,
  386. desc.cbuf_offset);
  387. }
  388. }
  389. Id DescType(EmitContext& ctx, Id sampled_type, Id pointer_type, u32 count) {
  390. if (count > 1) {
  391. const Id array_type{ctx.TypeArray(sampled_type, ctx.Const(count))};
  392. return ctx.TypePointer(spv::StorageClass::UniformConstant, array_type);
  393. } else {
  394. return pointer_type;
  395. }
  396. }
  397. size_t FindAndSetNextUnusedLocation(std::bitset<IR::NUM_GENERICS>& used_locations,
  398. size_t& start_offset) {
  399. for (size_t location = start_offset; location < used_locations.size(); ++location) {
  400. if (!used_locations.test(location)) {
  401. start_offset = location;
  402. used_locations.set(location);
  403. return location;
  404. }
  405. }
  406. throw RuntimeError("Unable to get an unused location for legacy attribute");
  407. }
  408. Id DefineLegacyInput(EmitContext& ctx, std::bitset<IR::NUM_GENERICS>& used_locations,
  409. size_t& start_offset) {
  410. const Id id{DefineInput(ctx, ctx.F32[4], true)};
  411. const size_t location = FindAndSetNextUnusedLocation(used_locations, start_offset);
  412. ctx.Decorate(id, spv::Decoration::Location, location);
  413. return id;
  414. }
  415. Id DefineLegacyOutput(EmitContext& ctx, std::bitset<IR::NUM_GENERICS>& used_locations,
  416. size_t& start_offset, std::optional<u32> invocations) {
  417. const Id id{DefineOutput(ctx, ctx.F32[4], invocations)};
  418. const size_t location = FindAndSetNextUnusedLocation(used_locations, start_offset);
  419. ctx.Decorate(id, spv::Decoration::Location, location);
  420. return id;
  421. }
  422. } // Anonymous namespace
  423. void VectorTypes::Define(Sirit::Module& sirit_ctx, Id base_type, std::string_view name) {
  424. defs[0] = sirit_ctx.Name(base_type, name);
  425. std::array<char, 6> def_name;
  426. for (int i = 1; i < 4; ++i) {
  427. const std::string_view def_name_view(
  428. def_name.data(),
  429. fmt::format_to_n(def_name.data(), def_name.size(), "{}x{}", name, i + 1).size);
  430. defs[static_cast<size_t>(i)] =
  431. sirit_ctx.Name(sirit_ctx.TypeVector(base_type, i + 1), def_name_view);
  432. }
  433. }
  434. EmitContext::EmitContext(const Profile& profile_, const RuntimeInfo& runtime_info_,
  435. IR::Program& program, Bindings& bindings)
  436. : Sirit::Module(profile_.supported_spirv), profile{profile_}, runtime_info{runtime_info_},
  437. stage{program.stage}, texture_rescaling_index{bindings.texture_scaling_index},
  438. image_rescaling_index{bindings.image_scaling_index} {
  439. const bool is_unified{profile.unified_descriptor_binding};
  440. u32& uniform_binding{is_unified ? bindings.unified : bindings.uniform_buffer};
  441. u32& storage_binding{is_unified ? bindings.unified : bindings.storage_buffer};
  442. u32& texture_binding{is_unified ? bindings.unified : bindings.texture};
  443. u32& image_binding{is_unified ? bindings.unified : bindings.image};
  444. AddCapability(spv::Capability::Shader);
  445. DefineCommonTypes(program.info);
  446. DefineCommonConstants();
  447. DefineInterfaces(program);
  448. DefineLocalMemory(program);
  449. DefineSharedMemory(program);
  450. DefineSharedMemoryFunctions(program);
  451. DefineConstantBuffers(program.info, uniform_binding);
  452. DefineStorageBuffers(program.info, storage_binding);
  453. DefineTextureBuffers(program.info, texture_binding);
  454. DefineImageBuffers(program.info, image_binding);
  455. DefineTextures(program.info, texture_binding, bindings.texture_scaling_index);
  456. DefineImages(program.info, image_binding, bindings.image_scaling_index);
  457. DefineAttributeMemAccess(program.info);
  458. DefineGlobalMemoryFunctions(program.info);
  459. DefineRescalingInput(program.info);
  460. }
  461. EmitContext::~EmitContext() = default;
  462. Id EmitContext::Def(const IR::Value& value) {
  463. if (!value.IsImmediate()) {
  464. return value.InstRecursive()->Definition<Id>();
  465. }
  466. switch (value.Type()) {
  467. case IR::Type::Void:
  468. // Void instructions are used for optional arguments (e.g. texture offsets)
  469. // They are not meant to be used in the SPIR-V module
  470. return Id{};
  471. case IR::Type::U1:
  472. return value.U1() ? true_value : false_value;
  473. case IR::Type::U32:
  474. return Const(value.U32());
  475. case IR::Type::U64:
  476. return Constant(U64, value.U64());
  477. case IR::Type::F32:
  478. return Const(value.F32());
  479. case IR::Type::F64:
  480. return Constant(F64[1], value.F64());
  481. default:
  482. throw NotImplementedException("Immediate type {}", value.Type());
  483. }
  484. }
  485. Id EmitContext::BitOffset8(const IR::Value& offset) {
  486. if (offset.IsImmediate()) {
  487. return Const((offset.U32() % 4) * 8);
  488. }
  489. return OpBitwiseAnd(U32[1], OpShiftLeftLogical(U32[1], Def(offset), Const(3u)), Const(24u));
  490. }
  491. Id EmitContext::BitOffset16(const IR::Value& offset) {
  492. if (offset.IsImmediate()) {
  493. return Const(((offset.U32() / 2) % 2) * 16);
  494. }
  495. return OpBitwiseAnd(U32[1], OpShiftLeftLogical(U32[1], Def(offset), Const(3u)), Const(16u));
  496. }
  497. Id EmitContext::InputLegacyAttribute(IR::Attribute attribute) {
  498. if (attribute >= IR::Attribute::ColorFrontDiffuseR &&
  499. attribute <= IR::Attribute::ColorFrontDiffuseA) {
  500. return input_front_color;
  501. }
  502. if (attribute >= IR::Attribute::ColorFrontSpecularR &&
  503. attribute <= IR::Attribute::ColorFrontSpecularA) {
  504. return input_front_secondary_color;
  505. }
  506. if (attribute >= IR::Attribute::ColorBackDiffuseR &&
  507. attribute <= IR::Attribute::ColorBackDiffuseA) {
  508. return input_back_color;
  509. }
  510. if (attribute >= IR::Attribute::ColorBackSpecularR &&
  511. attribute <= IR::Attribute::ColorBackSpecularA) {
  512. return input_back_secondary_color;
  513. }
  514. if (attribute == IR::Attribute::FogCoordinate) {
  515. return input_fog_frag_coord;
  516. }
  517. if (attribute >= IR::Attribute::FixedFncTexture0S &&
  518. attribute <= IR::Attribute::FixedFncTexture9Q) {
  519. u32 index =
  520. (static_cast<u32>(attribute) - static_cast<u32>(IR::Attribute::FixedFncTexture0S)) / 4;
  521. return input_fixed_fnc_textures[index];
  522. }
  523. throw InvalidArgument("Attribute is not legacy attribute {}", attribute);
  524. }
  525. Id EmitContext::OutputLegacyAttribute(IR::Attribute attribute) {
  526. if (attribute >= IR::Attribute::ColorFrontDiffuseR &&
  527. attribute <= IR::Attribute::ColorFrontDiffuseA) {
  528. return output_front_color;
  529. }
  530. if (attribute >= IR::Attribute::ColorFrontSpecularR &&
  531. attribute <= IR::Attribute::ColorFrontSpecularA) {
  532. return output_front_secondary_color;
  533. }
  534. if (attribute >= IR::Attribute::ColorBackDiffuseR &&
  535. attribute <= IR::Attribute::ColorBackDiffuseA) {
  536. return output_back_color;
  537. }
  538. if (attribute >= IR::Attribute::ColorBackSpecularR &&
  539. attribute <= IR::Attribute::ColorBackSpecularA) {
  540. return output_back_secondary_color;
  541. }
  542. if (attribute == IR::Attribute::FogCoordinate) {
  543. return output_fog_frag_coord;
  544. }
  545. if (attribute >= IR::Attribute::FixedFncTexture0S &&
  546. attribute <= IR::Attribute::FixedFncTexture9Q) {
  547. u32 index =
  548. (static_cast<u32>(attribute) - static_cast<u32>(IR::Attribute::FixedFncTexture0S)) / 4;
  549. return output_fixed_fnc_textures[index];
  550. }
  551. throw InvalidArgument("Attribute is not legacy attribute {}", attribute);
  552. }
  553. void EmitContext::DefineCommonTypes(const Info& info) {
  554. void_id = TypeVoid();
  555. U1 = Name(TypeBool(), "u1");
  556. F32.Define(*this, TypeFloat(32), "f32");
  557. U32.Define(*this, TypeInt(32, false), "u32");
  558. S32.Define(*this, TypeInt(32, true), "s32");
  559. private_u32 = Name(TypePointer(spv::StorageClass::Private, U32[1]), "private_u32");
  560. input_f32 = Name(TypePointer(spv::StorageClass::Input, F32[1]), "input_f32");
  561. input_u32 = Name(TypePointer(spv::StorageClass::Input, U32[1]), "input_u32");
  562. input_s32 = Name(TypePointer(spv::StorageClass::Input, TypeInt(32, true)), "input_s32");
  563. output_f32 = Name(TypePointer(spv::StorageClass::Output, F32[1]), "output_f32");
  564. output_u32 = Name(TypePointer(spv::StorageClass::Output, U32[1]), "output_u32");
  565. if (info.uses_int8 && profile.support_int8) {
  566. AddCapability(spv::Capability::Int8);
  567. U8 = Name(TypeInt(8, false), "u8");
  568. S8 = Name(TypeInt(8, true), "s8");
  569. }
  570. if (info.uses_int16 && profile.support_int16) {
  571. AddCapability(spv::Capability::Int16);
  572. U16 = Name(TypeInt(16, false), "u16");
  573. S16 = Name(TypeInt(16, true), "s16");
  574. }
  575. if (info.uses_int64) {
  576. AddCapability(spv::Capability::Int64);
  577. U64 = Name(TypeInt(64, false), "u64");
  578. }
  579. if (info.uses_fp16) {
  580. AddCapability(spv::Capability::Float16);
  581. F16.Define(*this, TypeFloat(16), "f16");
  582. }
  583. if (info.uses_fp64) {
  584. AddCapability(spv::Capability::Float64);
  585. F64.Define(*this, TypeFloat(64), "f64");
  586. }
  587. }
  588. void EmitContext::DefineCommonConstants() {
  589. true_value = ConstantTrue(U1);
  590. false_value = ConstantFalse(U1);
  591. u32_zero_value = Const(0U);
  592. f32_zero_value = Const(0.0f);
  593. }
  594. void EmitContext::DefineInterfaces(const IR::Program& program) {
  595. DefineInputs(program);
  596. DefineOutputs(program);
  597. }
  598. void EmitContext::DefineLocalMemory(const IR::Program& program) {
  599. if (program.local_memory_size == 0) {
  600. return;
  601. }
  602. const u32 num_elements{Common::DivCeil(program.local_memory_size, 4U)};
  603. const Id type{TypeArray(U32[1], Const(num_elements))};
  604. const Id pointer{TypePointer(spv::StorageClass::Private, type)};
  605. local_memory = AddGlobalVariable(pointer, spv::StorageClass::Private);
  606. if (profile.supported_spirv >= 0x00010400) {
  607. interfaces.push_back(local_memory);
  608. }
  609. }
  610. void EmitContext::DefineSharedMemory(const IR::Program& program) {
  611. if (program.shared_memory_size == 0) {
  612. return;
  613. }
  614. const auto make{[&](Id element_type, u32 element_size) {
  615. const u32 num_elements{Common::DivCeil(program.shared_memory_size, element_size)};
  616. const Id array_type{TypeArray(element_type, Const(num_elements))};
  617. Decorate(array_type, spv::Decoration::ArrayStride, element_size);
  618. const Id struct_type{TypeStruct(array_type)};
  619. MemberDecorate(struct_type, 0U, spv::Decoration::Offset, 0U);
  620. Decorate(struct_type, spv::Decoration::Block);
  621. const Id pointer{TypePointer(spv::StorageClass::Workgroup, struct_type)};
  622. const Id element_pointer{TypePointer(spv::StorageClass::Workgroup, element_type)};
  623. const Id variable{AddGlobalVariable(pointer, spv::StorageClass::Workgroup)};
  624. Decorate(variable, spv::Decoration::Aliased);
  625. interfaces.push_back(variable);
  626. return std::make_tuple(variable, element_pointer, pointer);
  627. }};
  628. if (profile.support_explicit_workgroup_layout) {
  629. AddExtension("SPV_KHR_workgroup_memory_explicit_layout");
  630. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayoutKHR);
  631. if (program.info.uses_int8) {
  632. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayout8BitAccessKHR);
  633. std::tie(shared_memory_u8, shared_u8, std::ignore) = make(U8, 1);
  634. }
  635. if (program.info.uses_int16) {
  636. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayout16BitAccessKHR);
  637. std::tie(shared_memory_u16, shared_u16, std::ignore) = make(U16, 2);
  638. }
  639. if (program.info.uses_int64) {
  640. std::tie(shared_memory_u64, shared_u64, std::ignore) = make(U64, 8);
  641. }
  642. std::tie(shared_memory_u32, shared_u32, shared_memory_u32_type) = make(U32[1], 4);
  643. std::tie(shared_memory_u32x2, shared_u32x2, std::ignore) = make(U32[2], 8);
  644. std::tie(shared_memory_u32x4, shared_u32x4, std::ignore) = make(U32[4], 16);
  645. return;
  646. }
  647. const u32 num_elements{Common::DivCeil(program.shared_memory_size, 4U)};
  648. const Id type{TypeArray(U32[1], Const(num_elements))};
  649. shared_memory_u32_type = TypePointer(spv::StorageClass::Workgroup, type);
  650. shared_u32 = TypePointer(spv::StorageClass::Workgroup, U32[1]);
  651. shared_memory_u32 = AddGlobalVariable(shared_memory_u32_type, spv::StorageClass::Workgroup);
  652. interfaces.push_back(shared_memory_u32);
  653. const Id func_type{TypeFunction(void_id, U32[1], U32[1])};
  654. const auto make_function{[&](u32 mask, u32 size) {
  655. const Id loop_header{OpLabel()};
  656. const Id continue_block{OpLabel()};
  657. const Id merge_block{OpLabel()};
  658. const Id func{OpFunction(void_id, spv::FunctionControlMask::MaskNone, func_type)};
  659. const Id offset{OpFunctionParameter(U32[1])};
  660. const Id insert_value{OpFunctionParameter(U32[1])};
  661. AddLabel();
  662. OpBranch(loop_header);
  663. AddLabel(loop_header);
  664. const Id word_offset{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  665. const Id shift_offset{OpShiftLeftLogical(U32[1], offset, Const(3U))};
  666. const Id bit_offset{OpBitwiseAnd(U32[1], shift_offset, Const(mask))};
  667. const Id count{Const(size)};
  668. OpLoopMerge(merge_block, continue_block, spv::LoopControlMask::MaskNone);
  669. OpBranch(continue_block);
  670. AddLabel(continue_block);
  671. const Id word_pointer{OpAccessChain(shared_u32, shared_memory_u32, word_offset)};
  672. const Id old_value{OpLoad(U32[1], word_pointer)};
  673. const Id new_value{OpBitFieldInsert(U32[1], old_value, insert_value, bit_offset, count)};
  674. const Id atomic_res{OpAtomicCompareExchange(U32[1], word_pointer, Const(1U), u32_zero_value,
  675. u32_zero_value, new_value, old_value)};
  676. const Id success{OpIEqual(U1, atomic_res, old_value)};
  677. OpBranchConditional(success, merge_block, loop_header);
  678. AddLabel(merge_block);
  679. OpReturn();
  680. OpFunctionEnd();
  681. return func;
  682. }};
  683. if (program.info.uses_int8) {
  684. shared_store_u8_func = make_function(24, 8);
  685. }
  686. if (program.info.uses_int16) {
  687. shared_store_u16_func = make_function(16, 16);
  688. }
  689. }
  690. void EmitContext::DefineSharedMemoryFunctions(const IR::Program& program) {
  691. if (program.info.uses_shared_increment) {
  692. increment_cas_shared = CasLoop(*this, Operation::Increment, shared_memory_u32_type,
  693. shared_u32, U32[1], U32[1], spv::Scope::Workgroup);
  694. }
  695. if (program.info.uses_shared_decrement) {
  696. decrement_cas_shared = CasLoop(*this, Operation::Decrement, shared_memory_u32_type,
  697. shared_u32, U32[1], U32[1], spv::Scope::Workgroup);
  698. }
  699. }
  700. void EmitContext::DefineAttributeMemAccess(const Info& info) {
  701. const auto make_load{[&] {
  702. const bool is_array{stage == Stage::Geometry};
  703. const Id end_block{OpLabel()};
  704. const Id default_label{OpLabel()};
  705. const Id func_type_load{is_array ? TypeFunction(F32[1], U32[1], U32[1])
  706. : TypeFunction(F32[1], U32[1])};
  707. const Id func{OpFunction(F32[1], spv::FunctionControlMask::MaskNone, func_type_load)};
  708. const Id offset{OpFunctionParameter(U32[1])};
  709. const Id vertex{is_array ? OpFunctionParameter(U32[1]) : Id{}};
  710. AddLabel();
  711. const Id base_index{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  712. const Id masked_index{OpBitwiseAnd(U32[1], base_index, Const(3U))};
  713. const Id compare_index{OpShiftRightArithmetic(U32[1], base_index, Const(2U))};
  714. std::vector<Sirit::Literal> literals;
  715. std::vector<Id> labels;
  716. if (info.loads.AnyComponent(IR::Attribute::PositionX)) {
  717. literals.push_back(static_cast<u32>(IR::Attribute::PositionX) >> 2);
  718. labels.push_back(OpLabel());
  719. }
  720. const u32 base_attribute_value = static_cast<u32>(IR::Attribute::Generic0X) >> 2;
  721. for (u32 index = 0; index < static_cast<u32>(IR::NUM_GENERICS); ++index) {
  722. if (!info.loads.Generic(index)) {
  723. continue;
  724. }
  725. literals.push_back(base_attribute_value + index);
  726. labels.push_back(OpLabel());
  727. }
  728. OpSelectionMerge(end_block, spv::SelectionControlMask::MaskNone);
  729. OpSwitch(compare_index, default_label, literals, labels);
  730. AddLabel(default_label);
  731. OpReturnValue(Const(0.0f));
  732. size_t label_index{0};
  733. if (info.loads.AnyComponent(IR::Attribute::PositionX)) {
  734. AddLabel(labels[label_index]);
  735. const Id pointer{is_array
  736. ? OpAccessChain(input_f32, input_position, vertex, masked_index)
  737. : OpAccessChain(input_f32, input_position, masked_index)};
  738. const Id result{OpLoad(F32[1], pointer)};
  739. OpReturnValue(result);
  740. ++label_index;
  741. }
  742. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  743. if (!info.loads.Generic(index)) {
  744. continue;
  745. }
  746. AddLabel(labels[label_index]);
  747. const auto type{AttrTypes(*this, static_cast<u32>(index))};
  748. if (!type) {
  749. OpReturnValue(Const(0.0f));
  750. ++label_index;
  751. continue;
  752. }
  753. const Id generic_id{input_generics.at(index)};
  754. const Id pointer{is_array
  755. ? OpAccessChain(type->pointer, generic_id, vertex, masked_index)
  756. : OpAccessChain(type->pointer, generic_id, masked_index)};
  757. const Id value{OpLoad(type->id, pointer)};
  758. const Id result{type->needs_cast ? OpBitcast(F32[1], value) : value};
  759. OpReturnValue(result);
  760. ++label_index;
  761. }
  762. AddLabel(end_block);
  763. OpUnreachable();
  764. OpFunctionEnd();
  765. return func;
  766. }};
  767. const auto make_store{[&] {
  768. const Id end_block{OpLabel()};
  769. const Id default_label{OpLabel()};
  770. const Id func_type_store{TypeFunction(void_id, U32[1], F32[1])};
  771. const Id func{OpFunction(void_id, spv::FunctionControlMask::MaskNone, func_type_store)};
  772. const Id offset{OpFunctionParameter(U32[1])};
  773. const Id store_value{OpFunctionParameter(F32[1])};
  774. AddLabel();
  775. const Id base_index{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  776. const Id masked_index{OpBitwiseAnd(U32[1], base_index, Const(3U))};
  777. const Id compare_index{OpShiftRightArithmetic(U32[1], base_index, Const(2U))};
  778. std::vector<Sirit::Literal> literals;
  779. std::vector<Id> labels;
  780. if (info.stores.AnyComponent(IR::Attribute::PositionX)) {
  781. literals.push_back(static_cast<u32>(IR::Attribute::PositionX) >> 2);
  782. labels.push_back(OpLabel());
  783. }
  784. const u32 base_attribute_value = static_cast<u32>(IR::Attribute::Generic0X) >> 2;
  785. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  786. if (!info.stores.Generic(index)) {
  787. continue;
  788. }
  789. literals.push_back(base_attribute_value + static_cast<u32>(index));
  790. labels.push_back(OpLabel());
  791. }
  792. if (info.stores.ClipDistances()) {
  793. literals.push_back(static_cast<u32>(IR::Attribute::ClipDistance0) >> 2);
  794. labels.push_back(OpLabel());
  795. literals.push_back(static_cast<u32>(IR::Attribute::ClipDistance4) >> 2);
  796. labels.push_back(OpLabel());
  797. }
  798. OpSelectionMerge(end_block, spv::SelectionControlMask::MaskNone);
  799. OpSwitch(compare_index, default_label, literals, labels);
  800. AddLabel(default_label);
  801. OpReturn();
  802. size_t label_index{0};
  803. if (info.stores.AnyComponent(IR::Attribute::PositionX)) {
  804. AddLabel(labels[label_index]);
  805. const Id pointer{OpAccessChain(output_f32, output_position, masked_index)};
  806. OpStore(pointer, store_value);
  807. OpReturn();
  808. ++label_index;
  809. }
  810. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  811. if (!info.stores.Generic(index)) {
  812. continue;
  813. }
  814. if (output_generics[index][0].num_components != 4) {
  815. throw NotImplementedException("Physical stores and transform feedbacks");
  816. }
  817. AddLabel(labels[label_index]);
  818. const Id generic_id{output_generics[index][0].id};
  819. const Id pointer{OpAccessChain(output_f32, generic_id, masked_index)};
  820. OpStore(pointer, store_value);
  821. OpReturn();
  822. ++label_index;
  823. }
  824. if (info.stores.ClipDistances()) {
  825. AddLabel(labels[label_index]);
  826. const Id pointer{OpAccessChain(output_f32, clip_distances, masked_index)};
  827. OpStore(pointer, store_value);
  828. OpReturn();
  829. ++label_index;
  830. AddLabel(labels[label_index]);
  831. const Id fixed_index{OpIAdd(U32[1], masked_index, Const(4U))};
  832. const Id pointer2{OpAccessChain(output_f32, clip_distances, fixed_index)};
  833. OpStore(pointer2, store_value);
  834. OpReturn();
  835. ++label_index;
  836. }
  837. AddLabel(end_block);
  838. OpUnreachable();
  839. OpFunctionEnd();
  840. return func;
  841. }};
  842. if (info.loads_indexed_attributes) {
  843. indexed_load_func = make_load();
  844. }
  845. if (info.stores_indexed_attributes) {
  846. indexed_store_func = make_store();
  847. }
  848. }
  849. void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
  850. if (!info.uses_global_memory || !profile.support_int64) {
  851. return;
  852. }
  853. using DefPtr = Id StorageDefinitions::*;
  854. const Id zero{u32_zero_value};
  855. const auto define_body{[&](DefPtr ssbo_member, Id addr, Id element_pointer, u32 shift,
  856. auto&& callback) {
  857. AddLabel();
  858. const size_t num_buffers{info.storage_buffers_descriptors.size()};
  859. for (size_t index = 0; index < num_buffers; ++index) {
  860. if (!info.nvn_buffer_used[index]) {
  861. continue;
  862. }
  863. const auto& ssbo{info.storage_buffers_descriptors[index]};
  864. const Id ssbo_addr_cbuf_offset{Const(ssbo.cbuf_offset / 8)};
  865. const Id ssbo_size_cbuf_offset{Const(ssbo.cbuf_offset / 4 + 2)};
  866. const Id ssbo_addr_pointer{OpAccessChain(
  867. uniform_types.U32x2, cbufs[ssbo.cbuf_index].U32x2, zero, ssbo_addr_cbuf_offset)};
  868. const Id ssbo_size_pointer{OpAccessChain(uniform_types.U32, cbufs[ssbo.cbuf_index].U32,
  869. zero, ssbo_size_cbuf_offset)};
  870. const Id ssbo_addr{OpBitcast(U64, OpLoad(U32[2], ssbo_addr_pointer))};
  871. const Id ssbo_size{OpUConvert(U64, OpLoad(U32[1], ssbo_size_pointer))};
  872. const Id ssbo_end{OpIAdd(U64, ssbo_addr, ssbo_size)};
  873. const Id cond{OpLogicalAnd(U1, OpUGreaterThanEqual(U1, addr, ssbo_addr),
  874. OpULessThan(U1, addr, ssbo_end))};
  875. const Id then_label{OpLabel()};
  876. const Id else_label{OpLabel()};
  877. OpSelectionMerge(else_label, spv::SelectionControlMask::MaskNone);
  878. OpBranchConditional(cond, then_label, else_label);
  879. AddLabel(then_label);
  880. const Id ssbo_id{ssbos[index].*ssbo_member};
  881. const Id ssbo_offset{OpUConvert(U32[1], OpISub(U64, addr, ssbo_addr))};
  882. const Id ssbo_index{OpShiftRightLogical(U32[1], ssbo_offset, Const(shift))};
  883. const Id ssbo_pointer{OpAccessChain(element_pointer, ssbo_id, zero, ssbo_index)};
  884. callback(ssbo_pointer);
  885. AddLabel(else_label);
  886. }
  887. }};
  888. const auto define_load{[&](DefPtr ssbo_member, Id element_pointer, Id type, u32 shift) {
  889. const Id function_type{TypeFunction(type, U64)};
  890. const Id func_id{OpFunction(type, spv::FunctionControlMask::MaskNone, function_type)};
  891. const Id addr{OpFunctionParameter(U64)};
  892. define_body(ssbo_member, addr, element_pointer, shift,
  893. [&](Id ssbo_pointer) { OpReturnValue(OpLoad(type, ssbo_pointer)); });
  894. OpReturnValue(ConstantNull(type));
  895. OpFunctionEnd();
  896. return func_id;
  897. }};
  898. const auto define_write{[&](DefPtr ssbo_member, Id element_pointer, Id type, u32 shift) {
  899. const Id function_type{TypeFunction(void_id, U64, type)};
  900. const Id func_id{OpFunction(void_id, spv::FunctionControlMask::MaskNone, function_type)};
  901. const Id addr{OpFunctionParameter(U64)};
  902. const Id data{OpFunctionParameter(type)};
  903. define_body(ssbo_member, addr, element_pointer, shift, [&](Id ssbo_pointer) {
  904. OpStore(ssbo_pointer, data);
  905. OpReturn();
  906. });
  907. OpReturn();
  908. OpFunctionEnd();
  909. return func_id;
  910. }};
  911. const auto define{
  912. [&](DefPtr ssbo_member, const StorageTypeDefinition& type_def, Id type, size_t size) {
  913. const Id element_type{type_def.element};
  914. const u32 shift{static_cast<u32>(std::countr_zero(size))};
  915. const Id load_func{define_load(ssbo_member, element_type, type, shift)};
  916. const Id write_func{define_write(ssbo_member, element_type, type, shift)};
  917. return std::make_pair(load_func, write_func);
  918. }};
  919. std::tie(load_global_func_u32, write_global_func_u32) =
  920. define(&StorageDefinitions::U32, storage_types.U32, U32[1], sizeof(u32));
  921. std::tie(load_global_func_u32x2, write_global_func_u32x2) =
  922. define(&StorageDefinitions::U32x2, storage_types.U32x2, U32[2], sizeof(u32[2]));
  923. std::tie(load_global_func_u32x4, write_global_func_u32x4) =
  924. define(&StorageDefinitions::U32x4, storage_types.U32x4, U32[4], sizeof(u32[4]));
  925. }
  926. void EmitContext::DefineRescalingInput(const Info& info) {
  927. if (!info.uses_rescaling_uniform) {
  928. return;
  929. }
  930. if (profile.unified_descriptor_binding) {
  931. DefineRescalingInputPushConstant(info);
  932. } else {
  933. DefineRescalingInputUniformConstant();
  934. }
  935. }
  936. void EmitContext::DefineRescalingInputPushConstant(const Info& info) {
  937. boost::container::static_vector<Id, 3> members{F32[1]};
  938. u32 member_index{0};
  939. if (!info.texture_descriptors.empty()) {
  940. rescaling_textures_type = TypeArray(U32[1], Const(4u));
  941. Decorate(rescaling_textures_type, spv::Decoration::ArrayStride, 4u);
  942. members.push_back(rescaling_textures_type);
  943. rescaling_textures_member_index = ++member_index;
  944. }
  945. if (!info.image_descriptors.empty()) {
  946. rescaling_images_type = TypeArray(U32[1], Const(NUM_IMAGE_SCALING_WORDS));
  947. if (rescaling_textures_type.value != rescaling_images_type.value) {
  948. Decorate(rescaling_images_type, spv::Decoration::ArrayStride, 4u);
  949. }
  950. members.push_back(rescaling_images_type);
  951. rescaling_images_member_index = ++member_index;
  952. }
  953. const Id push_constant_struct{TypeStruct(std::span(members.data(), members.size()))};
  954. Decorate(push_constant_struct, spv::Decoration::Block);
  955. Name(push_constant_struct, "ResolutionInfo");
  956. MemberDecorate(push_constant_struct, 0u, spv::Decoration::Offset, 0u);
  957. MemberName(push_constant_struct, 0u, "down_factor");
  958. const u32 offset_bias = stage == Stage::Compute ? sizeof(u32) : 0;
  959. if (!info.texture_descriptors.empty()) {
  960. MemberDecorate(
  961. push_constant_struct, rescaling_textures_member_index, spv::Decoration::Offset,
  962. static_cast<u32>(offsetof(RescalingLayout, rescaling_textures) - offset_bias));
  963. MemberName(push_constant_struct, rescaling_textures_member_index, "rescaling_textures");
  964. }
  965. if (!info.image_descriptors.empty()) {
  966. MemberDecorate(push_constant_struct, rescaling_images_member_index, spv::Decoration::Offset,
  967. static_cast<u32>(offsetof(RescalingLayout, rescaling_images) - offset_bias));
  968. MemberName(push_constant_struct, rescaling_images_member_index, "rescaling_images");
  969. }
  970. const Id pointer_type{TypePointer(spv::StorageClass::PushConstant, push_constant_struct)};
  971. rescaling_push_constants = AddGlobalVariable(pointer_type, spv::StorageClass::PushConstant);
  972. Name(rescaling_push_constants, "rescaling_push_constants");
  973. if (profile.supported_spirv >= 0x00010400) {
  974. interfaces.push_back(rescaling_push_constants);
  975. }
  976. }
  977. void EmitContext::DefineRescalingInputUniformConstant() {
  978. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, F32[4])};
  979. rescaling_uniform_constant =
  980. AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant);
  981. Decorate(rescaling_uniform_constant, spv::Decoration::Location, 0u);
  982. if (profile.supported_spirv >= 0x00010400) {
  983. interfaces.push_back(rescaling_uniform_constant);
  984. }
  985. }
  986. void EmitContext::DefineConstantBuffers(const Info& info, u32& binding) {
  987. if (info.constant_buffer_descriptors.empty()) {
  988. return;
  989. }
  990. if (!profile.support_descriptor_aliasing) {
  991. DefineConstBuffers(*this, info, &UniformDefinitions::U32x4, binding, U32[4], 'u',
  992. sizeof(u32[4]));
  993. for (const ConstantBufferDescriptor& desc : info.constant_buffer_descriptors) {
  994. binding += desc.count;
  995. }
  996. return;
  997. }
  998. IR::Type types{info.used_constant_buffer_types};
  999. if (True(types & IR::Type::U8)) {
  1000. if (profile.support_int8) {
  1001. DefineConstBuffers(*this, info, &UniformDefinitions::U8, binding, U8, 'u', sizeof(u8));
  1002. DefineConstBuffers(*this, info, &UniformDefinitions::S8, binding, S8, 's', sizeof(s8));
  1003. } else {
  1004. types |= IR::Type::U32;
  1005. }
  1006. }
  1007. if (True(types & IR::Type::U16)) {
  1008. if (profile.support_int16) {
  1009. DefineConstBuffers(*this, info, &UniformDefinitions::U16, binding, U16, 'u',
  1010. sizeof(u16));
  1011. DefineConstBuffers(*this, info, &UniformDefinitions::S16, binding, S16, 's',
  1012. sizeof(s16));
  1013. } else {
  1014. types |= IR::Type::U32;
  1015. }
  1016. }
  1017. if (True(types & IR::Type::U32)) {
  1018. DefineConstBuffers(*this, info, &UniformDefinitions::U32, binding, U32[1], 'u',
  1019. sizeof(u32));
  1020. }
  1021. if (True(types & IR::Type::F32)) {
  1022. DefineConstBuffers(*this, info, &UniformDefinitions::F32, binding, F32[1], 'f',
  1023. sizeof(f32));
  1024. }
  1025. if (True(types & IR::Type::U32x2)) {
  1026. DefineConstBuffers(*this, info, &UniformDefinitions::U32x2, binding, U32[2], 'u',
  1027. sizeof(u32[2]));
  1028. }
  1029. binding += static_cast<u32>(info.constant_buffer_descriptors.size());
  1030. }
  1031. void EmitContext::DefineStorageBuffers(const Info& info, u32& binding) {
  1032. if (info.storage_buffers_descriptors.empty()) {
  1033. return;
  1034. }
  1035. AddExtension("SPV_KHR_storage_buffer_storage_class");
  1036. const IR::Type used_types{profile.support_descriptor_aliasing ? info.used_storage_buffer_types
  1037. : IR::Type::U32};
  1038. if (profile.support_int8 && True(used_types & IR::Type::U8)) {
  1039. DefineSsbos(*this, storage_types.U8, &StorageDefinitions::U8, info, binding, U8,
  1040. sizeof(u8));
  1041. DefineSsbos(*this, storage_types.S8, &StorageDefinitions::S8, info, binding, S8,
  1042. sizeof(u8));
  1043. }
  1044. if (profile.support_int16 && True(used_types & IR::Type::U16)) {
  1045. DefineSsbos(*this, storage_types.U16, &StorageDefinitions::U16, info, binding, U16,
  1046. sizeof(u16));
  1047. DefineSsbos(*this, storage_types.S16, &StorageDefinitions::S16, info, binding, S16,
  1048. sizeof(u16));
  1049. }
  1050. if (True(used_types & IR::Type::U32)) {
  1051. DefineSsbos(*this, storage_types.U32, &StorageDefinitions::U32, info, binding, U32[1],
  1052. sizeof(u32));
  1053. }
  1054. if (True(used_types & IR::Type::F32)) {
  1055. DefineSsbos(*this, storage_types.F32, &StorageDefinitions::F32, info, binding, F32[1],
  1056. sizeof(f32));
  1057. }
  1058. if (True(used_types & IR::Type::U64)) {
  1059. DefineSsbos(*this, storage_types.U64, &StorageDefinitions::U64, info, binding, U64,
  1060. sizeof(u64));
  1061. }
  1062. if (True(used_types & IR::Type::U32x2)) {
  1063. DefineSsbos(*this, storage_types.U32x2, &StorageDefinitions::U32x2, info, binding, U32[2],
  1064. sizeof(u32[2]));
  1065. }
  1066. if (True(used_types & IR::Type::U32x4)) {
  1067. DefineSsbos(*this, storage_types.U32x4, &StorageDefinitions::U32x4, info, binding, U32[4],
  1068. sizeof(u32[4]));
  1069. }
  1070. for (const StorageBufferDescriptor& desc : info.storage_buffers_descriptors) {
  1071. binding += desc.count;
  1072. }
  1073. const bool needs_function{
  1074. info.uses_global_increment || info.uses_global_decrement || info.uses_atomic_f32_add ||
  1075. info.uses_atomic_f16x2_add || info.uses_atomic_f16x2_min || info.uses_atomic_f16x2_max ||
  1076. info.uses_atomic_f32x2_add || info.uses_atomic_f32x2_min || info.uses_atomic_f32x2_max};
  1077. if (needs_function) {
  1078. AddCapability(spv::Capability::VariablePointersStorageBuffer);
  1079. }
  1080. if (info.uses_global_increment) {
  1081. increment_cas_ssbo = CasLoop(*this, Operation::Increment, storage_types.U32.array,
  1082. storage_types.U32.element, U32[1], U32[1], spv::Scope::Device);
  1083. }
  1084. if (info.uses_global_decrement) {
  1085. decrement_cas_ssbo = CasLoop(*this, Operation::Decrement, storage_types.U32.array,
  1086. storage_types.U32.element, U32[1], U32[1], spv::Scope::Device);
  1087. }
  1088. if (info.uses_atomic_f32_add) {
  1089. f32_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  1090. storage_types.U32.element, F32[1], U32[1], spv::Scope::Device);
  1091. }
  1092. if (info.uses_atomic_f16x2_add) {
  1093. f16x2_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  1094. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  1095. }
  1096. if (info.uses_atomic_f16x2_min) {
  1097. f16x2_min_cas = CasLoop(*this, Operation::FPMin, storage_types.U32.array,
  1098. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  1099. }
  1100. if (info.uses_atomic_f16x2_max) {
  1101. f16x2_max_cas = CasLoop(*this, Operation::FPMax, storage_types.U32.array,
  1102. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  1103. }
  1104. if (info.uses_atomic_f32x2_add) {
  1105. f32x2_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  1106. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  1107. }
  1108. if (info.uses_atomic_f32x2_min) {
  1109. f32x2_min_cas = CasLoop(*this, Operation::FPMin, storage_types.U32.array,
  1110. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  1111. }
  1112. if (info.uses_atomic_f32x2_max) {
  1113. f32x2_max_cas = CasLoop(*this, Operation::FPMax, storage_types.U32.array,
  1114. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  1115. }
  1116. }
  1117. void EmitContext::DefineTextureBuffers(const Info& info, u32& binding) {
  1118. if (info.texture_buffer_descriptors.empty()) {
  1119. return;
  1120. }
  1121. const spv::ImageFormat format{spv::ImageFormat::Unknown};
  1122. image_buffer_type = TypeImage(F32[1], spv::Dim::Buffer, 0U, false, false, 1, format);
  1123. sampled_texture_buffer_type = TypeSampledImage(image_buffer_type);
  1124. const Id type{TypePointer(spv::StorageClass::UniformConstant, sampled_texture_buffer_type)};
  1125. texture_buffers.reserve(info.texture_buffer_descriptors.size());
  1126. for (const TextureBufferDescriptor& desc : info.texture_buffer_descriptors) {
  1127. if (desc.count != 1) {
  1128. throw NotImplementedException("Array of texture buffers");
  1129. }
  1130. const Id id{AddGlobalVariable(type, spv::StorageClass::UniformConstant)};
  1131. Decorate(id, spv::Decoration::Binding, binding);
  1132. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1133. Name(id, NameOf(stage, desc, "texbuf"));
  1134. texture_buffers.push_back({
  1135. .id = id,
  1136. .count = desc.count,
  1137. });
  1138. if (profile.supported_spirv >= 0x00010400) {
  1139. interfaces.push_back(id);
  1140. }
  1141. ++binding;
  1142. }
  1143. }
  1144. void EmitContext::DefineImageBuffers(const Info& info, u32& binding) {
  1145. image_buffers.reserve(info.image_buffer_descriptors.size());
  1146. for (const ImageBufferDescriptor& desc : info.image_buffer_descriptors) {
  1147. if (desc.count != 1) {
  1148. throw NotImplementedException("Array of image buffers");
  1149. }
  1150. const spv::ImageFormat format{GetImageFormat(desc.format)};
  1151. const Id image_type{TypeImage(U32[1], spv::Dim::Buffer, false, false, false, 2, format)};
  1152. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
  1153. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  1154. Decorate(id, spv::Decoration::Binding, binding);
  1155. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1156. Name(id, NameOf(stage, desc, "imgbuf"));
  1157. image_buffers.push_back({
  1158. .id = id,
  1159. .image_type = image_type,
  1160. .count = desc.count,
  1161. });
  1162. if (profile.supported_spirv >= 0x00010400) {
  1163. interfaces.push_back(id);
  1164. }
  1165. ++binding;
  1166. }
  1167. }
  1168. void EmitContext::DefineTextures(const Info& info, u32& binding, u32& scaling_index) {
  1169. textures.reserve(info.texture_descriptors.size());
  1170. for (const TextureDescriptor& desc : info.texture_descriptors) {
  1171. const Id image_type{ImageType(*this, desc)};
  1172. const Id sampled_type{TypeSampledImage(image_type)};
  1173. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, sampled_type)};
  1174. const Id desc_type{DescType(*this, sampled_type, pointer_type, desc.count)};
  1175. const Id id{AddGlobalVariable(desc_type, spv::StorageClass::UniformConstant)};
  1176. Decorate(id, spv::Decoration::Binding, binding);
  1177. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1178. Name(id, NameOf(stage, desc, "tex"));
  1179. textures.push_back({
  1180. .id = id,
  1181. .sampled_type = sampled_type,
  1182. .pointer_type = pointer_type,
  1183. .image_type = image_type,
  1184. .count = desc.count,
  1185. });
  1186. if (profile.supported_spirv >= 0x00010400) {
  1187. interfaces.push_back(id);
  1188. }
  1189. ++binding;
  1190. ++scaling_index;
  1191. }
  1192. if (info.uses_atomic_image_u32) {
  1193. image_u32 = TypePointer(spv::StorageClass::Image, U32[1]);
  1194. }
  1195. }
  1196. void EmitContext::DefineImages(const Info& info, u32& binding, u32& scaling_index) {
  1197. images.reserve(info.image_descriptors.size());
  1198. for (const ImageDescriptor& desc : info.image_descriptors) {
  1199. if (desc.count != 1) {
  1200. throw NotImplementedException("Array of images");
  1201. }
  1202. const Id image_type{ImageType(*this, desc)};
  1203. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
  1204. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  1205. Decorate(id, spv::Decoration::Binding, binding);
  1206. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1207. Name(id, NameOf(stage, desc, "img"));
  1208. images.push_back({
  1209. .id = id,
  1210. .image_type = image_type,
  1211. .count = desc.count,
  1212. });
  1213. if (profile.supported_spirv >= 0x00010400) {
  1214. interfaces.push_back(id);
  1215. }
  1216. ++binding;
  1217. ++scaling_index;
  1218. }
  1219. }
  1220. void EmitContext::DefineInputs(const IR::Program& program) {
  1221. const Info& info{program.info};
  1222. const VaryingState loads{info.loads.mask | info.passthrough.mask};
  1223. if (info.uses_workgroup_id) {
  1224. workgroup_id = DefineInput(*this, U32[3], false, spv::BuiltIn::WorkgroupId);
  1225. }
  1226. if (info.uses_local_invocation_id) {
  1227. local_invocation_id = DefineInput(*this, U32[3], false, spv::BuiltIn::LocalInvocationId);
  1228. }
  1229. if (info.uses_invocation_id) {
  1230. invocation_id = DefineInput(*this, U32[1], false, spv::BuiltIn::InvocationId);
  1231. }
  1232. if (info.uses_sample_id) {
  1233. sample_id = DefineInput(*this, U32[1], false, spv::BuiltIn::SampleId);
  1234. }
  1235. if (info.uses_is_helper_invocation) {
  1236. is_helper_invocation = DefineInput(*this, U1, false, spv::BuiltIn::HelperInvocation);
  1237. }
  1238. if (info.uses_subgroup_mask) {
  1239. subgroup_mask_eq = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupEqMaskKHR);
  1240. subgroup_mask_lt = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLtMaskKHR);
  1241. subgroup_mask_le = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLeMaskKHR);
  1242. subgroup_mask_gt = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupGtMaskKHR);
  1243. subgroup_mask_ge = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupGeMaskKHR);
  1244. }
  1245. if (info.uses_subgroup_invocation_id || info.uses_subgroup_shuffles ||
  1246. (profile.warp_size_potentially_larger_than_guest &&
  1247. (info.uses_subgroup_vote || info.uses_subgroup_mask))) {
  1248. subgroup_local_invocation_id =
  1249. DefineInput(*this, U32[1], false, spv::BuiltIn::SubgroupLocalInvocationId);
  1250. }
  1251. if (info.uses_fswzadd) {
  1252. const Id f32_one{Const(1.0f)};
  1253. const Id f32_minus_one{Const(-1.0f)};
  1254. const Id f32_zero{Const(0.0f)};
  1255. fswzadd_lut_a = ConstantComposite(F32[4], f32_minus_one, f32_one, f32_minus_one, f32_zero);
  1256. fswzadd_lut_b =
  1257. ConstantComposite(F32[4], f32_minus_one, f32_minus_one, f32_one, f32_minus_one);
  1258. }
  1259. if (loads[IR::Attribute::PrimitiveId]) {
  1260. primitive_id = DefineInput(*this, U32[1], false, spv::BuiltIn::PrimitiveId);
  1261. }
  1262. if (loads.AnyComponent(IR::Attribute::PositionX)) {
  1263. const bool is_fragment{stage != Stage::Fragment};
  1264. const spv::BuiltIn built_in{is_fragment ? spv::BuiltIn::Position : spv::BuiltIn::FragCoord};
  1265. input_position = DefineInput(*this, F32[4], true, built_in);
  1266. if (profile.support_geometry_shader_passthrough) {
  1267. if (info.passthrough.AnyComponent(IR::Attribute::PositionX)) {
  1268. Decorate(input_position, spv::Decoration::PassthroughNV);
  1269. }
  1270. }
  1271. }
  1272. if (loads[IR::Attribute::InstanceId]) {
  1273. if (profile.support_vertex_instance_id) {
  1274. instance_id = DefineInput(*this, U32[1], true, spv::BuiltIn::InstanceId);
  1275. } else {
  1276. instance_index = DefineInput(*this, U32[1], true, spv::BuiltIn::InstanceIndex);
  1277. base_instance = DefineInput(*this, U32[1], true, spv::BuiltIn::BaseInstance);
  1278. }
  1279. }
  1280. if (loads[IR::Attribute::VertexId]) {
  1281. if (profile.support_vertex_instance_id) {
  1282. vertex_id = DefineInput(*this, U32[1], true, spv::BuiltIn::VertexId);
  1283. } else {
  1284. vertex_index = DefineInput(*this, U32[1], true, spv::BuiltIn::VertexIndex);
  1285. base_vertex = DefineInput(*this, U32[1], true, spv::BuiltIn::BaseVertex);
  1286. }
  1287. }
  1288. if (loads[IR::Attribute::FrontFace]) {
  1289. front_face = DefineInput(*this, U1, true, spv::BuiltIn::FrontFacing);
  1290. }
  1291. if (loads[IR::Attribute::PointSpriteS] || loads[IR::Attribute::PointSpriteT]) {
  1292. point_coord = DefineInput(*this, F32[2], true, spv::BuiltIn::PointCoord);
  1293. }
  1294. if (loads[IR::Attribute::TessellationEvaluationPointU] ||
  1295. loads[IR::Attribute::TessellationEvaluationPointV]) {
  1296. tess_coord = DefineInput(*this, F32[3], false, spv::BuiltIn::TessCoord);
  1297. }
  1298. std::bitset<IR::NUM_GENERICS> used_locations{};
  1299. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  1300. const AttributeType input_type{runtime_info.generic_input_types[index]};
  1301. if (!runtime_info.previous_stage_stores.Generic(index)) {
  1302. continue;
  1303. }
  1304. if (!loads.Generic(index)) {
  1305. continue;
  1306. }
  1307. if (input_type == AttributeType::Disabled) {
  1308. continue;
  1309. }
  1310. used_locations.set(index);
  1311. const Id type{GetAttributeType(*this, input_type)};
  1312. const Id id{DefineInput(*this, type, true)};
  1313. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1314. Name(id, fmt::format("in_attr{}", index));
  1315. input_generics[index] = id;
  1316. if (info.passthrough.Generic(index) && profile.support_geometry_shader_passthrough) {
  1317. Decorate(id, spv::Decoration::PassthroughNV);
  1318. }
  1319. if (stage != Stage::Fragment) {
  1320. continue;
  1321. }
  1322. switch (info.interpolation[index]) {
  1323. case Interpolation::Smooth:
  1324. // Default
  1325. // Decorate(id, spv::Decoration::Smooth);
  1326. break;
  1327. case Interpolation::NoPerspective:
  1328. Decorate(id, spv::Decoration::NoPerspective);
  1329. break;
  1330. case Interpolation::Flat:
  1331. Decorate(id, spv::Decoration::Flat);
  1332. break;
  1333. }
  1334. }
  1335. size_t previous_unused_location = 0;
  1336. if (loads.AnyComponent(IR::Attribute::ColorFrontDiffuseR)) {
  1337. input_front_color = DefineLegacyInput(*this, used_locations, previous_unused_location);
  1338. }
  1339. if (loads.AnyComponent(IR::Attribute::ColorFrontSpecularR)) {
  1340. input_front_secondary_color =
  1341. DefineLegacyInput(*this, used_locations, previous_unused_location);
  1342. }
  1343. if (loads.AnyComponent(IR::Attribute::ColorBackDiffuseR)) {
  1344. input_back_color = DefineLegacyInput(*this, used_locations, previous_unused_location);
  1345. }
  1346. if (loads.AnyComponent(IR::Attribute::ColorBackSpecularR)) {
  1347. input_back_secondary_color =
  1348. DefineLegacyInput(*this, used_locations, previous_unused_location);
  1349. }
  1350. if (loads.AnyComponent(IR::Attribute::FogCoordinate)) {
  1351. input_fog_frag_coord = DefineLegacyInput(*this, used_locations, previous_unused_location);
  1352. }
  1353. for (size_t index = 0; index < NUM_FIXEDFNCTEXTURE; ++index) {
  1354. if (loads.AnyComponent(IR::Attribute::FixedFncTexture0S + index * 4)) {
  1355. input_fixed_fnc_textures[index] =
  1356. DefineLegacyInput(*this, used_locations, previous_unused_location);
  1357. }
  1358. }
  1359. if (stage == Stage::TessellationEval) {
  1360. for (size_t index = 0; index < info.uses_patches.size(); ++index) {
  1361. if (!info.uses_patches[index]) {
  1362. continue;
  1363. }
  1364. const Id id{DefineInput(*this, F32[4], false)};
  1365. Decorate(id, spv::Decoration::Patch);
  1366. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1367. patches[index] = id;
  1368. }
  1369. }
  1370. }
  1371. void EmitContext::DefineOutputs(const IR::Program& program) {
  1372. const Info& info{program.info};
  1373. const std::optional<u32> invocations{program.invocations};
  1374. if (info.stores.AnyComponent(IR::Attribute::PositionX) || stage == Stage::VertexB) {
  1375. output_position = DefineOutput(*this, F32[4], invocations, spv::BuiltIn::Position);
  1376. }
  1377. if (info.stores[IR::Attribute::PointSize] || runtime_info.fixed_state_point_size) {
  1378. if (stage == Stage::Fragment) {
  1379. throw NotImplementedException("Storing PointSize in fragment stage");
  1380. }
  1381. output_point_size = DefineOutput(*this, F32[1], invocations, spv::BuiltIn::PointSize);
  1382. }
  1383. if (info.stores.ClipDistances()) {
  1384. if (stage == Stage::Fragment) {
  1385. throw NotImplementedException("Storing ClipDistance in fragment stage");
  1386. }
  1387. const Id type{TypeArray(F32[1], Const(8U))};
  1388. clip_distances = DefineOutput(*this, type, invocations, spv::BuiltIn::ClipDistance);
  1389. }
  1390. if (info.stores[IR::Attribute::Layer] &&
  1391. (profile.support_viewport_index_layer_non_geometry || stage == Stage::Geometry)) {
  1392. if (stage == Stage::Fragment) {
  1393. throw NotImplementedException("Storing Layer in fragment stage");
  1394. }
  1395. layer = DefineOutput(*this, U32[1], invocations, spv::BuiltIn::Layer);
  1396. }
  1397. if (info.stores[IR::Attribute::ViewportIndex] &&
  1398. (profile.support_viewport_index_layer_non_geometry || stage == Stage::Geometry)) {
  1399. if (stage == Stage::Fragment) {
  1400. throw NotImplementedException("Storing ViewportIndex in fragment stage");
  1401. }
  1402. viewport_index = DefineOutput(*this, U32[1], invocations, spv::BuiltIn::ViewportIndex);
  1403. }
  1404. if (info.stores[IR::Attribute::ViewportMask] && profile.support_viewport_mask) {
  1405. viewport_mask = DefineOutput(*this, TypeArray(U32[1], Const(1u)), std::nullopt,
  1406. spv::BuiltIn::ViewportMaskNV);
  1407. }
  1408. std::bitset<IR::NUM_GENERICS> used_locations{};
  1409. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  1410. if (info.stores.Generic(index)) {
  1411. DefineGenericOutput(*this, index, invocations);
  1412. used_locations.set(index);
  1413. }
  1414. }
  1415. size_t previous_unused_location = 0;
  1416. if (info.stores.AnyComponent(IR::Attribute::ColorFrontDiffuseR)) {
  1417. output_front_color =
  1418. DefineLegacyOutput(*this, used_locations, previous_unused_location, invocations);
  1419. }
  1420. if (info.stores.AnyComponent(IR::Attribute::ColorFrontSpecularR)) {
  1421. output_front_secondary_color =
  1422. DefineLegacyOutput(*this, used_locations, previous_unused_location, invocations);
  1423. }
  1424. if (info.stores.AnyComponent(IR::Attribute::ColorBackDiffuseR)) {
  1425. output_back_color =
  1426. DefineLegacyOutput(*this, used_locations, previous_unused_location, invocations);
  1427. }
  1428. if (info.stores.AnyComponent(IR::Attribute::ColorBackSpecularR)) {
  1429. output_back_secondary_color =
  1430. DefineLegacyOutput(*this, used_locations, previous_unused_location, invocations);
  1431. }
  1432. if (info.stores.AnyComponent(IR::Attribute::FogCoordinate)) {
  1433. output_fog_frag_coord =
  1434. DefineLegacyOutput(*this, used_locations, previous_unused_location, invocations);
  1435. }
  1436. for (size_t index = 0; index < NUM_FIXEDFNCTEXTURE; ++index) {
  1437. if (info.stores.AnyComponent(IR::Attribute::FixedFncTexture0S + index * 4)) {
  1438. output_fixed_fnc_textures[index] =
  1439. DefineLegacyOutput(*this, used_locations, previous_unused_location, invocations);
  1440. }
  1441. }
  1442. switch (stage) {
  1443. case Stage::TessellationControl:
  1444. if (info.stores_tess_level_outer) {
  1445. const Id type{TypeArray(F32[1], Const(4U))};
  1446. output_tess_level_outer =
  1447. DefineOutput(*this, type, std::nullopt, spv::BuiltIn::TessLevelOuter);
  1448. Decorate(output_tess_level_outer, spv::Decoration::Patch);
  1449. }
  1450. if (info.stores_tess_level_inner) {
  1451. const Id type{TypeArray(F32[1], Const(2U))};
  1452. output_tess_level_inner =
  1453. DefineOutput(*this, type, std::nullopt, spv::BuiltIn::TessLevelInner);
  1454. Decorate(output_tess_level_inner, spv::Decoration::Patch);
  1455. }
  1456. for (size_t index = 0; index < info.uses_patches.size(); ++index) {
  1457. if (!info.uses_patches[index]) {
  1458. continue;
  1459. }
  1460. const Id id{DefineOutput(*this, F32[4], std::nullopt)};
  1461. Decorate(id, spv::Decoration::Patch);
  1462. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1463. patches[index] = id;
  1464. }
  1465. break;
  1466. case Stage::Fragment:
  1467. for (u32 index = 0; index < 8; ++index) {
  1468. if (!info.stores_frag_color[index] && !profile.need_declared_frag_colors) {
  1469. continue;
  1470. }
  1471. frag_color[index] = DefineOutput(*this, F32[4], std::nullopt);
  1472. Decorate(frag_color[index], spv::Decoration::Location, index);
  1473. Name(frag_color[index], fmt::format("frag_color{}", index));
  1474. }
  1475. if (info.stores_frag_depth) {
  1476. frag_depth = DefineOutput(*this, F32[1], std::nullopt);
  1477. Decorate(frag_depth, spv::Decoration::BuiltIn, spv::BuiltIn::FragDepth);
  1478. }
  1479. if (info.stores_sample_mask) {
  1480. sample_mask = DefineOutput(*this, U32[1], std::nullopt);
  1481. Decorate(sample_mask, spv::Decoration::BuiltIn, spv::BuiltIn::SampleMask);
  1482. }
  1483. break;
  1484. default:
  1485. break;
  1486. }
  1487. }
  1488. } // namespace Shader::Backend::SPIRV