spirv_emit_context.cpp 67 KB

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