spirv_cpp.cpp 15 KB

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