spirv_cpp.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /*
  2. * Copyright 2015-2021 Arm Limited
  3. * SPDX-License-Identifier: Apache-2.0 OR MIT
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*
  18. * At your option, you may choose to accept this material under either:
  19. * 1. The Apache License, Version 2.0, found at <http://www.apache.org/licenses/LICENSE-2.0>, or
  20. * 2. The MIT License, found at <http://opensource.org/licenses/MIT>.
  21. */
  22. #include "spirv_cpp.hpp"
  23. using namespace spv;
  24. using namespace SPIRV_CROSS_NAMESPACE;
  25. using namespace std;
  26. void CompilerCPP::emit_buffer_block(const SPIRVariable &var)
  27. {
  28. add_resource_name(var.self);
  29. auto &type = get<SPIRType>(var.basetype);
  30. auto instance_name = to_name(var.self);
  31. uint32_t descriptor_set = ir.meta[var.self].decoration.set;
  32. uint32_t binding = ir.meta[var.self].decoration.binding;
  33. emit_block_struct(type);
  34. auto buffer_name = to_name(type.self);
  35. statement("internal::Resource<", buffer_name, type_to_array_glsl(type), "> ", instance_name, "__;");
  36. statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()");
  37. resource_registrations.push_back(
  38. join("s.register_resource(", instance_name, "__", ", ", descriptor_set, ", ", binding, ");"));
  39. statement("");
  40. }
  41. void CompilerCPP::emit_interface_block(const SPIRVariable &var)
  42. {
  43. add_resource_name(var.self);
  44. auto &type = get<SPIRType>(var.basetype);
  45. const char *qual = var.storage == StorageClassInput ? "StageInput" : "StageOutput";
  46. const char *lowerqual = var.storage == StorageClassInput ? "stage_input" : "stage_output";
  47. auto instance_name = to_name(var.self);
  48. uint32_t location = ir.meta[var.self].decoration.location;
  49. string buffer_name;
  50. auto flags = ir.meta[type.self].decoration.decoration_flags;
  51. if (flags.get(DecorationBlock))
  52. {
  53. emit_block_struct(type);
  54. buffer_name = to_name(type.self);
  55. }
  56. else
  57. buffer_name = type_to_glsl(type);
  58. statement("internal::", qual, "<", buffer_name, type_to_array_glsl(type), "> ", instance_name, "__;");
  59. statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()");
  60. resource_registrations.push_back(join("s.register_", lowerqual, "(", instance_name, "__", ", ", location, ");"));
  61. statement("");
  62. }
  63. void CompilerCPP::emit_shared(const SPIRVariable &var)
  64. {
  65. add_resource_name(var.self);
  66. auto instance_name = to_name(var.self);
  67. statement(CompilerGLSL::variable_decl(var), ";");
  68. statement_no_indent("#define ", instance_name, " __res->", instance_name);
  69. }
  70. void CompilerCPP::emit_uniform(const SPIRVariable &var)
  71. {
  72. add_resource_name(var.self);
  73. auto &type = get<SPIRType>(var.basetype);
  74. auto instance_name = to_name(var.self);
  75. uint32_t descriptor_set = ir.meta[var.self].decoration.set;
  76. uint32_t binding = ir.meta[var.self].decoration.binding;
  77. uint32_t location = ir.meta[var.self].decoration.location;
  78. string type_name = type_to_glsl(type);
  79. remap_variable_type_name(type, instance_name, type_name);
  80. if (type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage ||
  81. type.basetype == SPIRType::AtomicCounter)
  82. {
  83. statement("internal::Resource<", type_name, type_to_array_glsl(type), "> ", instance_name, "__;");
  84. statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()");
  85. resource_registrations.push_back(
  86. join("s.register_resource(", instance_name, "__", ", ", descriptor_set, ", ", binding, ");"));
  87. }
  88. else
  89. {
  90. statement("internal::UniformConstant<", type_name, type_to_array_glsl(type), "> ", instance_name, "__;");
  91. statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()");
  92. resource_registrations.push_back(
  93. join("s.register_uniform_constant(", instance_name, "__", ", ", location, ");"));
  94. }
  95. statement("");
  96. }
  97. void CompilerCPP::emit_push_constant_block(const SPIRVariable &var)
  98. {
  99. add_resource_name(var.self);
  100. auto &type = get<SPIRType>(var.basetype);
  101. auto &flags = ir.meta[var.self].decoration.decoration_flags;
  102. if (flags.get(DecorationBinding) || flags.get(DecorationDescriptorSet))
  103. SPIRV_CROSS_THROW("Push constant blocks cannot be compiled to GLSL with Binding or Set syntax. "
  104. "Remap to location with reflection API first or disable these decorations.");
  105. emit_block_struct(type);
  106. auto buffer_name = to_name(type.self);
  107. auto instance_name = to_name(var.self);
  108. statement("internal::PushConstant<", buffer_name, type_to_array_glsl(type), "> ", instance_name, ";");
  109. statement_no_indent("#define ", instance_name, " __res->", instance_name, ".get()");
  110. resource_registrations.push_back(join("s.register_push_constant(", instance_name, "__", ");"));
  111. statement("");
  112. }
  113. void CompilerCPP::emit_block_struct(SPIRType &type)
  114. {
  115. // C++ can't do interface blocks, so we fake it by emitting a separate struct.
  116. // However, these structs are not allowed to alias anything, so remove it before
  117. // emitting the struct.
  118. //
  119. // The type we have here needs to be resolved to the non-pointer type so we can remove aliases.
  120. auto &self = get<SPIRType>(type.self);
  121. self.type_alias = 0;
  122. emit_struct(self);
  123. }
  124. void CompilerCPP::emit_resources()
  125. {
  126. for (auto &id : ir.ids)
  127. {
  128. if (id.get_type() == TypeConstant)
  129. {
  130. auto &c = id.get<SPIRConstant>();
  131. bool needs_declaration = c.specialization || c.is_used_as_lut;
  132. if (needs_declaration)
  133. {
  134. if (!options.vulkan_semantics && c.specialization)
  135. {
  136. c.specialization_constant_macro_name =
  137. constant_value_macro_name(get_decoration(c.self, DecorationSpecId));
  138. }
  139. emit_constant(c);
  140. }
  141. }
  142. else if (id.get_type() == TypeConstantOp)
  143. {
  144. emit_specialization_constant_op(id.get<SPIRConstantOp>());
  145. }
  146. }
  147. // Output all basic struct types which are not Block or BufferBlock as these are declared inplace
  148. // when such variables are instantiated.
  149. for (auto &id : ir.ids)
  150. {
  151. if (id.get_type() == TypeType)
  152. {
  153. auto &type = id.get<SPIRType>();
  154. if (type.basetype == SPIRType::Struct && type.array.empty() && !type.pointer &&
  155. (!ir.meta[type.self].decoration.decoration_flags.get(DecorationBlock) &&
  156. !ir.meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock)))
  157. {
  158. emit_struct(type);
  159. }
  160. }
  161. }
  162. statement("struct Resources : ", resource_type);
  163. begin_scope();
  164. // Output UBOs and SSBOs
  165. for (auto &id : ir.ids)
  166. {
  167. if (id.get_type() == TypeVariable)
  168. {
  169. auto &var = id.get<SPIRVariable>();
  170. auto &type = get<SPIRType>(var.basetype);
  171. if (var.storage != StorageClassFunction && type.pointer && type.storage == StorageClassUniform &&
  172. !is_hidden_variable(var) &&
  173. (ir.meta[type.self].decoration.decoration_flags.get(DecorationBlock) ||
  174. ir.meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock)))
  175. {
  176. emit_buffer_block(var);
  177. }
  178. }
  179. }
  180. // Output push constant blocks
  181. for (auto &id : ir.ids)
  182. {
  183. if (id.get_type() == TypeVariable)
  184. {
  185. auto &var = id.get<SPIRVariable>();
  186. auto &type = get<SPIRType>(var.basetype);
  187. if (!is_hidden_variable(var) && var.storage != StorageClassFunction && type.pointer &&
  188. type.storage == StorageClassPushConstant)
  189. {
  190. emit_push_constant_block(var);
  191. }
  192. }
  193. }
  194. // Output in/out interfaces.
  195. for (auto &id : ir.ids)
  196. {
  197. if (id.get_type() == TypeVariable)
  198. {
  199. auto &var = id.get<SPIRVariable>();
  200. auto &type = get<SPIRType>(var.basetype);
  201. if (var.storage != StorageClassFunction && !is_hidden_variable(var) && type.pointer &&
  202. (var.storage == StorageClassInput || var.storage == StorageClassOutput) &&
  203. interface_variable_exists_in_entry_point(var.self))
  204. {
  205. emit_interface_block(var);
  206. }
  207. }
  208. }
  209. // Output Uniform Constants (values, samplers, images, etc).
  210. for (auto &id : ir.ids)
  211. {
  212. if (id.get_type() == TypeVariable)
  213. {
  214. auto &var = id.get<SPIRVariable>();
  215. auto &type = get<SPIRType>(var.basetype);
  216. if (var.storage != StorageClassFunction && !is_hidden_variable(var) && type.pointer &&
  217. (type.storage == StorageClassUniformConstant || type.storage == StorageClassAtomicCounter))
  218. {
  219. emit_uniform(var);
  220. }
  221. }
  222. }
  223. // Global variables.
  224. bool emitted = false;
  225. for (auto global : global_variables)
  226. {
  227. auto &var = get<SPIRVariable>(global);
  228. if (var.storage == StorageClassWorkgroup)
  229. {
  230. emit_shared(var);
  231. emitted = true;
  232. }
  233. }
  234. if (emitted)
  235. statement("");
  236. declare_undefined_values();
  237. statement("inline void init(spirv_cross_shader& s)");
  238. begin_scope();
  239. statement(resource_type, "::init(s);");
  240. for (auto &reg : resource_registrations)
  241. statement(reg);
  242. end_scope();
  243. resource_registrations.clear();
  244. end_scope_decl();
  245. statement("");
  246. statement("Resources* __res;");
  247. if (get_entry_point().model == ExecutionModelGLCompute)
  248. statement("ComputePrivateResources __priv_res;");
  249. statement("");
  250. // Emit regular globals which are allocated per invocation.
  251. emitted = false;
  252. for (auto global : global_variables)
  253. {
  254. auto &var = get<SPIRVariable>(global);
  255. if (var.storage == StorageClassPrivate)
  256. {
  257. if (var.storage == StorageClassWorkgroup)
  258. emit_shared(var);
  259. else
  260. statement(CompilerGLSL::variable_decl(var), ";");
  261. emitted = true;
  262. }
  263. }
  264. if (emitted)
  265. statement("");
  266. }
  267. string CompilerCPP::compile()
  268. {
  269. ir.fixup_reserved_names();
  270. // Do not deal with ES-isms like precision, older extensions and such.
  271. options.es = false;
  272. options.version = 450;
  273. backend.float_literal_suffix = true;
  274. backend.double_literal_suffix = false;
  275. backend.long_long_literal_suffix = true;
  276. backend.uint32_t_literal_suffix = true;
  277. backend.basic_int_type = "int32_t";
  278. backend.basic_uint_type = "uint32_t";
  279. backend.swizzle_is_function = true;
  280. backend.shared_is_implied = true;
  281. backend.unsized_array_supported = false;
  282. backend.explicit_struct_type = true;
  283. backend.use_initializer_list = true;
  284. fixup_type_alias();
  285. reorder_type_alias();
  286. build_function_control_flow_graphs_and_analyze();
  287. update_active_builtins();
  288. uint32_t pass_count = 0;
  289. do
  290. {
  291. resource_registrations.clear();
  292. reset(pass_count);
  293. // Move constructor for this type is broken on GCC 4.9 ...
  294. buffer.reset();
  295. emit_header();
  296. emit_resources();
  297. emit_function(get<SPIRFunction>(ir.default_entry_point), Bitset());
  298. pass_count++;
  299. } while (is_forcing_recompilation());
  300. // Match opening scope of emit_header().
  301. end_scope_decl();
  302. // namespace
  303. end_scope();
  304. // Emit C entry points
  305. emit_c_linkage();
  306. // Entry point in CPP is always main() for the time being.
  307. get_entry_point().name = "main";
  308. return buffer.str();
  309. }
  310. void CompilerCPP::emit_c_linkage()
  311. {
  312. statement("");
  313. statement("spirv_cross_shader_t *spirv_cross_construct(void)");
  314. begin_scope();
  315. statement("return new ", impl_type, "();");
  316. end_scope();
  317. statement("");
  318. statement("void spirv_cross_destruct(spirv_cross_shader_t *shader)");
  319. begin_scope();
  320. statement("delete static_cast<", impl_type, "*>(shader);");
  321. end_scope();
  322. statement("");
  323. statement("void spirv_cross_invoke(spirv_cross_shader_t *shader)");
  324. begin_scope();
  325. statement("static_cast<", impl_type, "*>(shader)->invoke();");
  326. end_scope();
  327. statement("");
  328. statement("static const struct spirv_cross_interface vtable =");
  329. begin_scope();
  330. statement("spirv_cross_construct,");
  331. statement("spirv_cross_destruct,");
  332. statement("spirv_cross_invoke,");
  333. end_scope_decl();
  334. statement("");
  335. statement("const struct spirv_cross_interface *",
  336. interface_name.empty() ? string("spirv_cross_get_interface") : interface_name, "(void)");
  337. begin_scope();
  338. statement("return &vtable;");
  339. end_scope();
  340. }
  341. void CompilerCPP::emit_function_prototype(SPIRFunction &func, const Bitset &)
  342. {
  343. if (func.self != ir.default_entry_point)
  344. add_function_overload(func);
  345. local_variable_names = resource_names;
  346. string decl;
  347. auto &type = get<SPIRType>(func.return_type);
  348. decl += "inline ";
  349. decl += type_to_glsl(type);
  350. decl += " ";
  351. if (func.self == ir.default_entry_point)
  352. {
  353. decl += "main";
  354. processing_entry_point = true;
  355. }
  356. else
  357. decl += to_name(func.self);
  358. decl += "(";
  359. for (auto &arg : func.arguments)
  360. {
  361. add_local_variable_name(arg.id);
  362. decl += argument_decl(arg);
  363. if (&arg != &func.arguments.back())
  364. decl += ", ";
  365. // Hold a pointer to the parameter so we can invalidate the readonly field if needed.
  366. auto *var = maybe_get<SPIRVariable>(arg.id);
  367. if (var)
  368. var->parameter = &arg;
  369. }
  370. decl += ")";
  371. statement(decl);
  372. }
  373. string CompilerCPP::argument_decl(const SPIRFunction::Parameter &arg)
  374. {
  375. auto &type = expression_type(arg.id);
  376. bool constref = !type.pointer || arg.write_count == 0;
  377. auto &var = get<SPIRVariable>(arg.id);
  378. string base = type_to_glsl(type);
  379. string variable_name = to_name(var.self);
  380. remap_variable_type_name(type, variable_name, base);
  381. for (uint32_t i = 0; i < type.array.size(); i++)
  382. base = join("std::array<", base, ", ", to_array_size(type, i), ">");
  383. return join(constref ? "const " : "", base, " &", variable_name);
  384. }
  385. string CompilerCPP::variable_decl(const SPIRType &type, const string &name, uint32_t /* id */)
  386. {
  387. string base = type_to_glsl(type);
  388. remap_variable_type_name(type, name, base);
  389. bool runtime = false;
  390. for (uint32_t i = 0; i < type.array.size(); i++)
  391. {
  392. auto &array = type.array[i];
  393. if (!array && type.array_size_literal[i])
  394. {
  395. // Avoid using runtime arrays with std::array since this is undefined.
  396. // Runtime arrays cannot be passed around as values, so this is fine.
  397. runtime = true;
  398. }
  399. else
  400. base = join("std::array<", base, ", ", to_array_size(type, i), ">");
  401. }
  402. base += ' ';
  403. return base + name + (runtime ? "[1]" : "");
  404. }
  405. void CompilerCPP::emit_header()
  406. {
  407. auto &execution = get_entry_point();
  408. statement("// This C++ shader is autogenerated by spirv-cross.");
  409. statement("#include \"spirv_cross/internal_interface.hpp\"");
  410. statement("#include \"spirv_cross/external_interface.h\"");
  411. // Needed to properly implement GLSL-style arrays.
  412. statement("#include <array>");
  413. statement("#include <stdint.h>");
  414. statement("");
  415. statement("using namespace spirv_cross;");
  416. statement("using namespace glm;");
  417. statement("");
  418. statement("namespace Impl");
  419. begin_scope();
  420. switch (execution.model)
  421. {
  422. case ExecutionModelGeometry:
  423. case ExecutionModelTessellationControl:
  424. case ExecutionModelTessellationEvaluation:
  425. case ExecutionModelGLCompute:
  426. case ExecutionModelFragment:
  427. case ExecutionModelVertex:
  428. statement("struct Shader");
  429. begin_scope();
  430. break;
  431. default:
  432. SPIRV_CROSS_THROW("Unsupported execution model.");
  433. }
  434. switch (execution.model)
  435. {
  436. case ExecutionModelGeometry:
  437. impl_type = "GeometryShader<Impl::Shader, Impl::Shader::Resources>";
  438. resource_type = "GeometryResources";
  439. break;
  440. case ExecutionModelVertex:
  441. impl_type = "VertexShader<Impl::Shader, Impl::Shader::Resources>";
  442. resource_type = "VertexResources";
  443. break;
  444. case ExecutionModelFragment:
  445. impl_type = "FragmentShader<Impl::Shader, Impl::Shader::Resources>";
  446. resource_type = "FragmentResources";
  447. break;
  448. case ExecutionModelGLCompute:
  449. impl_type = join("ComputeShader<Impl::Shader, Impl::Shader::Resources, ", execution.workgroup_size.x, ", ",
  450. execution.workgroup_size.y, ", ", execution.workgroup_size.z, ">");
  451. resource_type = "ComputeResources";
  452. break;
  453. case ExecutionModelTessellationControl:
  454. impl_type = "TessControlShader<Impl::Shader, Impl::Shader::Resources>";
  455. resource_type = "TessControlResources";
  456. break;
  457. case ExecutionModelTessellationEvaluation:
  458. impl_type = "TessEvaluationShader<Impl::Shader, Impl::Shader::Resources>";
  459. resource_type = "TessEvaluationResources";
  460. break;
  461. default:
  462. SPIRV_CROSS_THROW("Unsupported execution model.");
  463. }
  464. }