spirv_emit_context.cpp 68 KB

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