spirv_cross.hpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  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. #ifndef SPIRV_CROSS_HPP
  23. #define SPIRV_CROSS_HPP
  24. #ifndef SPV_ENABLE_UTILITY_CODE
  25. #define SPV_ENABLE_UTILITY_CODE
  26. #endif
  27. #include "spirv.hpp"
  28. #include "spirv_cfg.hpp"
  29. #include "spirv_cross_parsed_ir.hpp"
  30. namespace SPIRV_CROSS_NAMESPACE
  31. {
  32. struct Resource
  33. {
  34. // Resources are identified with their SPIR-V ID.
  35. // This is the ID of the OpVariable.
  36. ID id;
  37. // The type ID of the variable which includes arrays and all type modifications.
  38. // This type ID is not suitable for parsing OpMemberDecoration of a struct and other decorations in general
  39. // since these modifications typically happen on the base_type_id.
  40. TypeID type_id;
  41. // The base type of the declared resource.
  42. // This type is the base type which ignores pointers and arrays of the type_id.
  43. // This is mostly useful to parse decorations of the underlying type.
  44. // base_type_id can also be obtained with get_type(get_type(type_id).self).
  45. TypeID base_type_id;
  46. // The declared name (OpName) of the resource.
  47. // For Buffer blocks, the name actually reflects the externally
  48. // visible Block name.
  49. //
  50. // This name can be retrieved again by using either
  51. // get_name(id) or get_name(base_type_id) depending if it's a buffer block or not.
  52. //
  53. // This name can be an empty string in which case get_fallback_name(id) can be
  54. // used which obtains a suitable fallback identifier for an ID.
  55. std::string name;
  56. };
  57. struct BuiltInResource
  58. {
  59. // This is mostly here to support reflection of builtins such as Position/PointSize/CullDistance/ClipDistance.
  60. // This needs to be different from Resource since we can collect builtins from blocks.
  61. // A builtin present here does not necessarily mean it's considered an active builtin,
  62. // since variable ID "activeness" is only tracked on OpVariable level, not Block members.
  63. // For that, update_active_builtins() -> has_active_builtin() can be used to further refine the reflection.
  64. spv::BuiltIn builtin;
  65. // This is the actual value type of the builtin.
  66. // Typically float4, float, array<float, N> for the gl_PerVertex builtins.
  67. // If the builtin is a control point, the control point array type will be stripped away here as appropriate.
  68. TypeID value_type_id;
  69. // This refers to the base resource which contains the builtin.
  70. // If resource is a Block, it can hold multiple builtins, or it might not be a block.
  71. // For advanced reflection scenarios, all information in builtin/value_type_id can be deduced,
  72. // it's just more convenient this way.
  73. Resource resource;
  74. };
  75. struct ShaderResources
  76. {
  77. SmallVector<Resource> uniform_buffers;
  78. SmallVector<Resource> storage_buffers;
  79. SmallVector<Resource> stage_inputs;
  80. SmallVector<Resource> stage_outputs;
  81. SmallVector<Resource> subpass_inputs;
  82. SmallVector<Resource> storage_images;
  83. SmallVector<Resource> sampled_images;
  84. SmallVector<Resource> atomic_counters;
  85. SmallVector<Resource> acceleration_structures;
  86. SmallVector<Resource> gl_plain_uniforms;
  87. // There can only be one push constant block,
  88. // but keep the vector in case this restriction is lifted in the future.
  89. SmallVector<Resource> push_constant_buffers;
  90. SmallVector<Resource> shader_record_buffers;
  91. // For Vulkan GLSL and HLSL source,
  92. // these correspond to separate texture2D and samplers respectively.
  93. SmallVector<Resource> separate_images;
  94. SmallVector<Resource> separate_samplers;
  95. SmallVector<BuiltInResource> builtin_inputs;
  96. SmallVector<BuiltInResource> builtin_outputs;
  97. };
  98. struct CombinedImageSampler
  99. {
  100. // The ID of the sampler2D variable.
  101. VariableID combined_id;
  102. // The ID of the texture2D variable.
  103. VariableID image_id;
  104. // The ID of the sampler variable.
  105. VariableID sampler_id;
  106. };
  107. struct SpecializationConstant
  108. {
  109. // The ID of the specialization constant.
  110. ConstantID id;
  111. // The constant ID of the constant, used in Vulkan during pipeline creation.
  112. uint32_t constant_id;
  113. };
  114. struct BufferRange
  115. {
  116. unsigned index;
  117. size_t offset;
  118. size_t range;
  119. };
  120. enum BufferPackingStandard
  121. {
  122. BufferPackingStd140,
  123. BufferPackingStd430,
  124. BufferPackingStd140EnhancedLayout,
  125. BufferPackingStd430EnhancedLayout,
  126. BufferPackingHLSLCbuffer,
  127. BufferPackingHLSLCbufferPackOffset,
  128. BufferPackingScalar,
  129. BufferPackingScalarEnhancedLayout
  130. };
  131. struct EntryPoint
  132. {
  133. std::string name;
  134. spv::ExecutionModel execution_model;
  135. };
  136. class Compiler
  137. {
  138. public:
  139. friend class CFG;
  140. friend class DominatorBuilder;
  141. // The constructor takes a buffer of SPIR-V words and parses it.
  142. // It will create its own parser, parse the SPIR-V and move the parsed IR
  143. // as if you had called the constructors taking ParsedIR directly.
  144. explicit Compiler(std::vector<uint32_t> ir);
  145. Compiler(const uint32_t *ir, size_t word_count);
  146. // This is more modular. We can also consume a ParsedIR structure directly, either as a move, or copy.
  147. // With copy, we can reuse the same parsed IR for multiple Compiler instances.
  148. explicit Compiler(const ParsedIR &ir);
  149. explicit Compiler(ParsedIR &&ir);
  150. virtual ~Compiler() = default;
  151. // After parsing, API users can modify the SPIR-V via reflection and call this
  152. // to disassemble the SPIR-V into the desired langauage.
  153. // Sub-classes actually implement this.
  154. virtual std::string compile();
  155. // Gets the identifier (OpName) of an ID. If not defined, an empty string will be returned.
  156. const std::string &get_name(ID id) const;
  157. // Applies a decoration to an ID. Effectively injects OpDecorate.
  158. void set_decoration(ID id, spv::Decoration decoration, uint32_t argument = 0);
  159. void set_decoration_string(ID id, spv::Decoration decoration, const std::string &argument);
  160. // Overrides the identifier OpName of an ID.
  161. // Identifiers beginning with underscores or identifiers which contain double underscores
  162. // are reserved by the implementation.
  163. void set_name(ID id, const std::string &name);
  164. // Gets a bitmask for the decorations which are applied to ID.
  165. // I.e. (1ull << spv::DecorationFoo) | (1ull << spv::DecorationBar)
  166. const Bitset &get_decoration_bitset(ID id) const;
  167. // Returns whether the decoration has been applied to the ID.
  168. bool has_decoration(ID id, spv::Decoration decoration) const;
  169. // Gets the value for decorations which take arguments.
  170. // If the decoration is a boolean (i.e. spv::DecorationNonWritable),
  171. // 1 will be returned.
  172. // If decoration doesn't exist or decoration is not recognized,
  173. // 0 will be returned.
  174. uint32_t get_decoration(ID id, spv::Decoration decoration) const;
  175. const std::string &get_decoration_string(ID id, spv::Decoration decoration) const;
  176. // Removes the decoration for an ID.
  177. void unset_decoration(ID id, spv::Decoration decoration);
  178. // Gets the SPIR-V type associated with ID.
  179. // Mostly used with Resource::type_id and Resource::base_type_id to parse the underlying type of a resource.
  180. const SPIRType &get_type(TypeID id) const;
  181. // Gets the SPIR-V type of a variable.
  182. const SPIRType &get_type_from_variable(VariableID id) const;
  183. // Gets the underlying storage class for an OpVariable.
  184. spv::StorageClass get_storage_class(VariableID id) const;
  185. // If get_name() is an empty string, get the fallback name which will be used
  186. // instead in the disassembled source.
  187. virtual const std::string get_fallback_name(ID id) const;
  188. // If get_name() of a Block struct is an empty string, get the fallback name.
  189. // This needs to be per-variable as multiple variables can use the same block type.
  190. virtual const std::string get_block_fallback_name(VariableID id) const;
  191. // Given an OpTypeStruct in ID, obtain the identifier for member number "index".
  192. // This may be an empty string.
  193. const std::string &get_member_name(TypeID id, uint32_t index) const;
  194. // Given an OpTypeStruct in ID, obtain the OpMemberDecoration for member number "index".
  195. uint32_t get_member_decoration(TypeID id, uint32_t index, spv::Decoration decoration) const;
  196. const std::string &get_member_decoration_string(TypeID id, uint32_t index, spv::Decoration decoration) const;
  197. // Sets the member identifier for OpTypeStruct ID, member number "index".
  198. void set_member_name(TypeID id, uint32_t index, const std::string &name);
  199. // Returns the qualified member identifier for OpTypeStruct ID, member number "index",
  200. // or an empty string if no qualified alias exists
  201. const std::string &get_member_qualified_name(TypeID type_id, uint32_t index) const;
  202. // Gets the decoration mask for a member of a struct, similar to get_decoration_mask.
  203. const Bitset &get_member_decoration_bitset(TypeID id, uint32_t index) const;
  204. // Returns whether the decoration has been applied to a member of a struct.
  205. bool has_member_decoration(TypeID id, uint32_t index, spv::Decoration decoration) const;
  206. // Similar to set_decoration, but for struct members.
  207. void set_member_decoration(TypeID id, uint32_t index, spv::Decoration decoration, uint32_t argument = 0);
  208. void set_member_decoration_string(TypeID id, uint32_t index, spv::Decoration decoration,
  209. const std::string &argument);
  210. // Unsets a member decoration, similar to unset_decoration.
  211. void unset_member_decoration(TypeID id, uint32_t index, spv::Decoration decoration);
  212. // Gets the fallback name for a member, similar to get_fallback_name.
  213. virtual const std::string get_fallback_member_name(uint32_t index) const
  214. {
  215. return join("_", index);
  216. }
  217. // Returns a vector of which members of a struct are potentially in use by a
  218. // SPIR-V shader. The granularity of this analysis is per-member of a struct.
  219. // This can be used for Buffer (UBO), BufferBlock/StorageBuffer (SSBO) and PushConstant blocks.
  220. // ID is the Resource::id obtained from get_shader_resources().
  221. SmallVector<BufferRange> get_active_buffer_ranges(VariableID id) const;
  222. // Returns the effective size of a buffer block.
  223. size_t get_declared_struct_size(const SPIRType &struct_type) const;
  224. // Returns the effective size of a buffer block, with a given array size
  225. // for a runtime array.
  226. // SSBOs are typically declared as runtime arrays. get_declared_struct_size() will return 0 for the size.
  227. // This is not very helpful for applications which might need to know the array stride of its last member.
  228. // This can be done through the API, but it is not very intuitive how to accomplish this, so here we provide a helper function
  229. // to query the size of the buffer, assuming that the last member has a certain size.
  230. // If the buffer does not contain a runtime array, array_size is ignored, and the function will behave as
  231. // get_declared_struct_size().
  232. // To get the array stride of the last member, something like:
  233. // get_declared_struct_size_runtime_array(type, 1) - get_declared_struct_size_runtime_array(type, 0) will work.
  234. size_t get_declared_struct_size_runtime_array(const SPIRType &struct_type, size_t array_size) const;
  235. // Returns the effective size of a buffer block struct member.
  236. size_t get_declared_struct_member_size(const SPIRType &struct_type, uint32_t index) const;
  237. // Returns a set of all global variables which are statically accessed
  238. // by the control flow graph from the current entry point.
  239. // Only variables which change the interface for a shader are returned, that is,
  240. // variables with storage class of Input, Output, Uniform, UniformConstant, PushConstant and AtomicCounter
  241. // storage classes are returned.
  242. //
  243. // To use the returned set as the filter for which variables are used during compilation,
  244. // this set can be moved to set_enabled_interface_variables().
  245. std::unordered_set<VariableID> get_active_interface_variables() const;
  246. // Sets the interface variables which are used during compilation.
  247. // By default, all variables are used.
  248. // Once set, compile() will only consider the set in active_variables.
  249. void set_enabled_interface_variables(std::unordered_set<VariableID> active_variables);
  250. // Query shader resources, use ids with reflection interface to modify or query binding points, etc.
  251. ShaderResources get_shader_resources() const;
  252. // Query shader resources, but only return the variables which are part of active_variables.
  253. // E.g.: get_shader_resources(get_active_variables()) to only return the variables which are statically
  254. // accessed.
  255. ShaderResources get_shader_resources(const std::unordered_set<VariableID> &active_variables) const;
  256. // Remapped variables are considered built-in variables and a backend will
  257. // not emit a declaration for this variable.
  258. // This is mostly useful for making use of builtins which are dependent on extensions.
  259. void set_remapped_variable_state(VariableID id, bool remap_enable);
  260. bool get_remapped_variable_state(VariableID id) const;
  261. // For subpassInput variables which are remapped to plain variables,
  262. // the number of components in the remapped
  263. // variable must be specified as the backing type of subpass inputs are opaque.
  264. void set_subpass_input_remapped_components(VariableID id, uint32_t components);
  265. uint32_t get_subpass_input_remapped_components(VariableID id) const;
  266. // All operations work on the current entry point.
  267. // Entry points can be swapped out with set_entry_point().
  268. // Entry points should be set right after the constructor completes as some reflection functions traverse the graph from the entry point.
  269. // Resource reflection also depends on the entry point.
  270. // By default, the current entry point is set to the first OpEntryPoint which appears in the SPIR-V module.
  271. // Some shader languages restrict the names that can be given to entry points, and the
  272. // corresponding backend will automatically rename an entry point name, during the call
  273. // to compile() if it is illegal. For example, the common entry point name main() is
  274. // illegal in MSL, and is renamed to an alternate name by the MSL backend.
  275. // Given the original entry point name contained in the SPIR-V, this function returns
  276. // the name, as updated by the backend during the call to compile(). If the name is not
  277. // illegal, and has not been renamed, or if this function is called before compile(),
  278. // this function will simply return the same name.
  279. // New variants of entry point query and reflection.
  280. // Names for entry points in the SPIR-V module may alias if they belong to different execution models.
  281. // To disambiguate, we must pass along with the entry point names the execution model.
  282. SmallVector<EntryPoint> get_entry_points_and_stages() const;
  283. void set_entry_point(const std::string &entry, spv::ExecutionModel execution_model);
  284. // Renames an entry point from old_name to new_name.
  285. // If old_name is currently selected as the current entry point, it will continue to be the current entry point,
  286. // albeit with a new name.
  287. // get_entry_points() is essentially invalidated at this point.
  288. void rename_entry_point(const std::string &old_name, const std::string &new_name,
  289. spv::ExecutionModel execution_model);
  290. const SPIREntryPoint &get_entry_point(const std::string &name, spv::ExecutionModel execution_model) const;
  291. SPIREntryPoint &get_entry_point(const std::string &name, spv::ExecutionModel execution_model);
  292. const std::string &get_cleansed_entry_point_name(const std::string &name,
  293. spv::ExecutionModel execution_model) const;
  294. // Traverses all reachable opcodes and sets active_builtins to a bitmask of all builtin variables which are accessed in the shader.
  295. void update_active_builtins();
  296. bool has_active_builtin(spv::BuiltIn builtin, spv::StorageClass storage) const;
  297. // Query and modify OpExecutionMode.
  298. const Bitset &get_execution_mode_bitset() const;
  299. void unset_execution_mode(spv::ExecutionMode mode);
  300. void set_execution_mode(spv::ExecutionMode mode, uint32_t arg0 = 0, uint32_t arg1 = 0, uint32_t arg2 = 0);
  301. // Gets argument for an execution mode (LocalSize, Invocations, OutputVertices).
  302. // For LocalSize or LocalSizeId, the index argument is used to select the dimension (X = 0, Y = 1, Z = 2).
  303. // For execution modes which do not have arguments, 0 is returned.
  304. // LocalSizeId query returns an ID. If LocalSizeId execution mode is not used, it returns 0.
  305. // LocalSize always returns a literal. If execution mode is LocalSizeId,
  306. // the literal (spec constant or not) is still returned.
  307. uint32_t get_execution_mode_argument(spv::ExecutionMode mode, uint32_t index = 0) const;
  308. spv::ExecutionModel get_execution_model() const;
  309. bool is_tessellation_shader() const;
  310. bool is_tessellating_triangles() const;
  311. // In SPIR-V, the compute work group size can be represented by a constant vector, in which case
  312. // the LocalSize execution mode is ignored.
  313. //
  314. // This constant vector can be a constant vector, specialization constant vector, or partly specialized constant vector.
  315. // To modify and query work group dimensions which are specialization constants, SPIRConstant values must be modified
  316. // directly via get_constant() rather than using LocalSize directly. This function will return which constants should be modified.
  317. //
  318. // To modify dimensions which are *not* specialization constants, set_execution_mode should be used directly.
  319. // Arguments to set_execution_mode which are specialization constants are effectively ignored during compilation.
  320. // NOTE: This is somewhat different from how SPIR-V works. In SPIR-V, the constant vector will completely replace LocalSize,
  321. // while in this interface, LocalSize is only ignored for specialization constants.
  322. //
  323. // The specialization constant will be written to x, y and z arguments.
  324. // If the component is not a specialization constant, a zeroed out struct will be written.
  325. // The return value is the constant ID of the builtin WorkGroupSize, but this is not expected to be useful
  326. // for most use cases.
  327. // If LocalSizeId is used, there is no uvec3 value representing the workgroup size, so the return value is 0,
  328. // but x, y and z are written as normal if the components are specialization constants.
  329. uint32_t get_work_group_size_specialization_constants(SpecializationConstant &x, SpecializationConstant &y,
  330. SpecializationConstant &z) const;
  331. // Analyzes all OpImageFetch (texelFetch) opcodes and checks if there are instances where
  332. // said instruction is used without a combined image sampler.
  333. // GLSL targets do not support the use of texelFetch without a sampler.
  334. // To workaround this, we must inject a dummy sampler which can be used to form a sampler2D at the call-site of
  335. // texelFetch as necessary.
  336. //
  337. // This must be called before build_combined_image_samplers().
  338. // build_combined_image_samplers() may refer to the ID returned by this method if the returned ID is non-zero.
  339. // The return value will be the ID of a sampler object if a dummy sampler is necessary, or 0 if no sampler object
  340. // is required.
  341. //
  342. // If the returned ID is non-zero, it can be decorated with set/bindings as desired before calling compile().
  343. // Calling this function also invalidates get_active_interface_variables(), so this should be called
  344. // before that function.
  345. VariableID build_dummy_sampler_for_combined_images();
  346. // Analyzes all separate image and samplers used from the currently selected entry point,
  347. // and re-routes them all to a combined image sampler instead.
  348. // This is required to "support" separate image samplers in targets which do not natively support
  349. // this feature, like GLSL/ESSL.
  350. //
  351. // This must be called before compile() if such remapping is desired.
  352. // This call will add new sampled images to the SPIR-V,
  353. // so it will appear in reflection if get_shader_resources() is called after build_combined_image_samplers.
  354. //
  355. // If any image/sampler remapping was found, no separate image/samplers will appear in the decompiled output,
  356. // but will still appear in reflection.
  357. //
  358. // The resulting samplers will be void of any decorations like name, descriptor sets and binding points,
  359. // so this can be added before compile() if desired.
  360. //
  361. // Combined image samplers originating from this set are always considered active variables.
  362. // Arrays of separate samplers are not supported, but arrays of separate images are supported.
  363. // Array of images + sampler -> Array of combined image samplers.
  364. void build_combined_image_samplers();
  365. // Gets a remapping for the combined image samplers.
  366. const SmallVector<CombinedImageSampler> &get_combined_image_samplers() const
  367. {
  368. return combined_image_samplers;
  369. }
  370. // Set a new variable type remap callback.
  371. // The type remapping is designed to allow global interface variable to assume more special types.
  372. // A typical example here is to remap sampler2D into samplerExternalOES, which currently isn't supported
  373. // directly by SPIR-V.
  374. //
  375. // In compile() while emitting code,
  376. // for every variable that is declared, including function parameters, the callback will be called
  377. // and the API user has a chance to change the textual representation of the type used to declare the variable.
  378. // The API user can detect special patterns in names to guide the remapping.
  379. void set_variable_type_remap_callback(VariableTypeRemapCallback cb)
  380. {
  381. variable_remap_callback = std::move(cb);
  382. }
  383. // API for querying which specialization constants exist.
  384. // To modify a specialization constant before compile(), use get_constant(constant.id),
  385. // then update constants directly in the SPIRConstant data structure.
  386. // For composite types, the subconstants can be iterated over and modified.
  387. // constant_type is the SPIRType for the specialization constant,
  388. // which can be queried to determine which fields in the unions should be poked at.
  389. SmallVector<SpecializationConstant> get_specialization_constants() const;
  390. SPIRConstant &get_constant(ConstantID id);
  391. const SPIRConstant &get_constant(ConstantID id) const;
  392. uint32_t get_current_id_bound() const
  393. {
  394. return uint32_t(ir.ids.size());
  395. }
  396. // API for querying buffer objects.
  397. // The type passed in here should be the base type of a resource, i.e.
  398. // get_type(resource.base_type_id)
  399. // as decorations are set in the basic Block type.
  400. // The type passed in here must have these decorations set, or an exception is raised.
  401. // Only UBOs and SSBOs or sub-structs which are part of these buffer types will have these decorations set.
  402. uint32_t type_struct_member_offset(const SPIRType &type, uint32_t index) const;
  403. uint32_t type_struct_member_array_stride(const SPIRType &type, uint32_t index) const;
  404. uint32_t type_struct_member_matrix_stride(const SPIRType &type, uint32_t index) const;
  405. // Gets the offset in SPIR-V words (uint32_t) for a decoration which was originally declared in the SPIR-V binary.
  406. // The offset will point to one or more uint32_t literals which can be modified in-place before using the SPIR-V binary.
  407. // Note that adding or removing decorations using the reflection API will not change the behavior of this function.
  408. // If the decoration was declared, sets the word_offset to an offset into the provided SPIR-V binary buffer and returns true,
  409. // otherwise, returns false.
  410. // If the decoration does not have any value attached to it (e.g. DecorationRelaxedPrecision), this function will also return false.
  411. bool get_binary_offset_for_decoration(VariableID id, spv::Decoration decoration, uint32_t &word_offset) const;
  412. // HLSL counter buffer reflection interface.
  413. // Append/Consume/Increment/Decrement in HLSL is implemented as two "neighbor" buffer objects where
  414. // one buffer implements the storage, and a single buffer containing just a lone "int" implements the counter.
  415. // To SPIR-V these will be exposed as two separate buffers, but glslang HLSL frontend emits a special indentifier
  416. // which lets us link the two buffers together.
  417. // Queries if a variable ID is a counter buffer which "belongs" to a regular buffer object.
  418. // If SPV_GOOGLE_hlsl_functionality1 is used, this can be used even with a stripped SPIR-V module.
  419. // Otherwise, this query is purely based on OpName identifiers as found in the SPIR-V module, and will
  420. // only return true if OpSource was reported HLSL.
  421. // To rely on this functionality, ensure that the SPIR-V module is not stripped.
  422. bool buffer_is_hlsl_counter_buffer(VariableID id) const;
  423. // Queries if a buffer object has a neighbor "counter" buffer.
  424. // If so, the ID of that counter buffer will be returned in counter_id.
  425. // If SPV_GOOGLE_hlsl_functionality1 is used, this can be used even with a stripped SPIR-V module.
  426. // Otherwise, this query is purely based on OpName identifiers as found in the SPIR-V module, and will
  427. // only return true if OpSource was reported HLSL.
  428. // To rely on this functionality, ensure that the SPIR-V module is not stripped.
  429. bool buffer_get_hlsl_counter_buffer(VariableID id, uint32_t &counter_id) const;
  430. // Gets the list of all SPIR-V Capabilities which were declared in the SPIR-V module.
  431. const SmallVector<spv::Capability> &get_declared_capabilities() const;
  432. // Gets the list of all SPIR-V extensions which were declared in the SPIR-V module.
  433. const SmallVector<std::string> &get_declared_extensions() const;
  434. // When declaring buffer blocks in GLSL, the name declared in the GLSL source
  435. // might not be the same as the name declared in the SPIR-V module due to naming conflicts.
  436. // In this case, SPIRV-Cross needs to find a fallback-name, and it might only
  437. // be possible to know this name after compiling to GLSL.
  438. // This is particularly important for HLSL input and UAVs which tends to reuse the same block type
  439. // for multiple distinct blocks. For these cases it is not possible to modify the name of the type itself
  440. // because it might be unique. Instead, you can use this interface to check after compilation which
  441. // name was actually used if your input SPIR-V tends to have this problem.
  442. // For other names like remapped names for variables, etc, it's generally enough to query the name of the variables
  443. // after compiling, block names are an exception to this rule.
  444. // ID is the name of a variable as returned by Resource::id, and must be a variable with a Block-like type.
  445. //
  446. // This also applies to HLSL cbuffers.
  447. std::string get_remapped_declared_block_name(VariableID id) const;
  448. // For buffer block variables, get the decorations for that variable.
  449. // Sometimes, decorations for buffer blocks are found in member decorations instead
  450. // of direct decorations on the variable itself.
  451. // The most common use here is to check if a buffer is readonly or writeonly.
  452. Bitset get_buffer_block_flags(VariableID id) const;
  453. // Returns whether the position output is invariant
  454. bool is_position_invariant() const
  455. {
  456. return position_invariant;
  457. }
  458. protected:
  459. const uint32_t *stream(const Instruction &instr) const
  460. {
  461. // If we're not going to use any arguments, just return nullptr.
  462. // We want to avoid case where we return an out of range pointer
  463. // that trips debug assertions on some platforms.
  464. if (!instr.length)
  465. return nullptr;
  466. if (instr.is_embedded())
  467. {
  468. auto &embedded = static_cast<const EmbeddedInstruction &>(instr);
  469. assert(embedded.ops.size() == instr.length);
  470. return embedded.ops.data();
  471. }
  472. else
  473. {
  474. if (instr.offset + instr.length > ir.spirv.size())
  475. SPIRV_CROSS_THROW("Compiler::stream() out of range.");
  476. return &ir.spirv[instr.offset];
  477. }
  478. }
  479. uint32_t *stream_mutable(const Instruction &instr) const
  480. {
  481. return const_cast<uint32_t *>(stream(instr));
  482. }
  483. ParsedIR ir;
  484. // Marks variables which have global scope and variables which can alias with other variables
  485. // (SSBO, image load store, etc)
  486. SmallVector<uint32_t> global_variables;
  487. SmallVector<uint32_t> aliased_variables;
  488. SPIRFunction *current_function = nullptr;
  489. SPIRBlock *current_block = nullptr;
  490. uint32_t current_loop_level = 0;
  491. std::unordered_set<VariableID> active_interface_variables;
  492. bool check_active_interface_variables = false;
  493. void add_loop_level();
  494. void set_initializers(SPIRExpression &e)
  495. {
  496. e.emitted_loop_level = current_loop_level;
  497. }
  498. template <typename T>
  499. void set_initializers(const T &)
  500. {
  501. }
  502. // If our IDs are out of range here as part of opcodes, throw instead of
  503. // undefined behavior.
  504. template <typename T, typename... P>
  505. T &set(uint32_t id, P &&... args)
  506. {
  507. ir.add_typed_id(static_cast<Types>(T::type), id);
  508. auto &var = variant_set<T>(ir.ids[id], std::forward<P>(args)...);
  509. var.self = id;
  510. set_initializers(var);
  511. return var;
  512. }
  513. template <typename T>
  514. T &get(uint32_t id)
  515. {
  516. return variant_get<T>(ir.ids[id]);
  517. }
  518. template <typename T>
  519. T *maybe_get(uint32_t id)
  520. {
  521. if (id >= ir.ids.size())
  522. return nullptr;
  523. else if (ir.ids[id].get_type() == static_cast<Types>(T::type))
  524. return &get<T>(id);
  525. else
  526. return nullptr;
  527. }
  528. template <typename T>
  529. const T &get(uint32_t id) const
  530. {
  531. return variant_get<T>(ir.ids[id]);
  532. }
  533. template <typename T>
  534. const T *maybe_get(uint32_t id) const
  535. {
  536. if (id >= ir.ids.size())
  537. return nullptr;
  538. else if (ir.ids[id].get_type() == static_cast<Types>(T::type))
  539. return &get<T>(id);
  540. else
  541. return nullptr;
  542. }
  543. // Gets the id of SPIR-V type underlying the given type_id, which might be a pointer.
  544. uint32_t get_pointee_type_id(uint32_t type_id) const;
  545. // Gets the SPIR-V type underlying the given type, which might be a pointer.
  546. const SPIRType &get_pointee_type(const SPIRType &type) const;
  547. // Gets the SPIR-V type underlying the given type_id, which might be a pointer.
  548. const SPIRType &get_pointee_type(uint32_t type_id) const;
  549. // Gets the ID of the SPIR-V type underlying a variable.
  550. uint32_t get_variable_data_type_id(const SPIRVariable &var) const;
  551. // Gets the SPIR-V type underlying a variable.
  552. SPIRType &get_variable_data_type(const SPIRVariable &var);
  553. // Gets the SPIR-V type underlying a variable.
  554. const SPIRType &get_variable_data_type(const SPIRVariable &var) const;
  555. // Gets the SPIR-V element type underlying an array variable.
  556. SPIRType &get_variable_element_type(const SPIRVariable &var);
  557. // Gets the SPIR-V element type underlying an array variable.
  558. const SPIRType &get_variable_element_type(const SPIRVariable &var) const;
  559. // Sets the qualified member identifier for OpTypeStruct ID, member number "index".
  560. void set_member_qualified_name(uint32_t type_id, uint32_t index, const std::string &name);
  561. void set_qualified_name(uint32_t id, const std::string &name);
  562. // Returns if the given type refers to a sampled image.
  563. bool is_sampled_image_type(const SPIRType &type);
  564. const SPIREntryPoint &get_entry_point() const;
  565. SPIREntryPoint &get_entry_point();
  566. static bool is_tessellation_shader(spv::ExecutionModel model);
  567. virtual std::string to_name(uint32_t id, bool allow_alias = true) const;
  568. bool is_builtin_variable(const SPIRVariable &var) const;
  569. bool is_builtin_type(const SPIRType &type) const;
  570. bool is_hidden_variable(const SPIRVariable &var, bool include_builtins = false) const;
  571. bool is_immutable(uint32_t id) const;
  572. bool is_member_builtin(const SPIRType &type, uint32_t index, spv::BuiltIn *builtin) const;
  573. bool is_scalar(const SPIRType &type) const;
  574. bool is_vector(const SPIRType &type) const;
  575. bool is_matrix(const SPIRType &type) const;
  576. bool is_array(const SPIRType &type) const;
  577. static bool is_runtime_size_array(const SPIRType &type);
  578. uint32_t expression_type_id(uint32_t id) const;
  579. const SPIRType &expression_type(uint32_t id) const;
  580. bool expression_is_lvalue(uint32_t id) const;
  581. bool variable_storage_is_aliased(const SPIRVariable &var);
  582. SPIRVariable *maybe_get_backing_variable(uint32_t chain);
  583. void register_read(uint32_t expr, uint32_t chain, bool forwarded);
  584. void register_write(uint32_t chain);
  585. inline bool is_continue(uint32_t next) const
  586. {
  587. return (ir.block_meta[next] & ParsedIR::BLOCK_META_CONTINUE_BIT) != 0;
  588. }
  589. inline bool is_single_block_loop(uint32_t next) const
  590. {
  591. auto &block = get<SPIRBlock>(next);
  592. return block.merge == SPIRBlock::MergeLoop && block.continue_block == ID(next);
  593. }
  594. inline bool is_break(uint32_t next) const
  595. {
  596. return (ir.block_meta[next] &
  597. (ParsedIR::BLOCK_META_LOOP_MERGE_BIT | ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT)) != 0;
  598. }
  599. inline bool is_loop_break(uint32_t next) const
  600. {
  601. return (ir.block_meta[next] & ParsedIR::BLOCK_META_LOOP_MERGE_BIT) != 0;
  602. }
  603. inline bool is_conditional(uint32_t next) const
  604. {
  605. return (ir.block_meta[next] &
  606. (ParsedIR::BLOCK_META_SELECTION_MERGE_BIT | ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT)) != 0;
  607. }
  608. // Dependency tracking for temporaries read from variables.
  609. void flush_dependees(SPIRVariable &var);
  610. void flush_all_active_variables();
  611. void flush_control_dependent_expressions(uint32_t block);
  612. void flush_all_atomic_capable_variables();
  613. void flush_all_aliased_variables();
  614. void register_global_read_dependencies(const SPIRBlock &func, uint32_t id);
  615. void register_global_read_dependencies(const SPIRFunction &func, uint32_t id);
  616. std::unordered_set<uint32_t> invalid_expressions;
  617. void update_name_cache(std::unordered_set<std::string> &cache, std::string &name);
  618. // A variant which takes two sets of names. The secondary is only used to verify there are no collisions,
  619. // but the set is not updated when we have found a new name.
  620. // Used primarily when adding block interface names.
  621. void update_name_cache(std::unordered_set<std::string> &cache_primary,
  622. const std::unordered_set<std::string> &cache_secondary, std::string &name);
  623. bool function_is_pure(const SPIRFunction &func);
  624. bool block_is_pure(const SPIRBlock &block);
  625. bool execution_is_branchless(const SPIRBlock &from, const SPIRBlock &to) const;
  626. bool execution_is_direct_branch(const SPIRBlock &from, const SPIRBlock &to) const;
  627. bool execution_is_noop(const SPIRBlock &from, const SPIRBlock &to) const;
  628. SPIRBlock::ContinueBlockType continue_block_type(const SPIRBlock &continue_block) const;
  629. void force_recompile();
  630. void force_recompile_guarantee_forward_progress();
  631. void clear_force_recompile();
  632. bool is_forcing_recompilation() const;
  633. bool is_force_recompile = false;
  634. bool is_force_recompile_forward_progress = false;
  635. bool block_is_noop(const SPIRBlock &block) const;
  636. bool block_is_loop_candidate(const SPIRBlock &block, SPIRBlock::Method method) const;
  637. bool types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const;
  638. void inherit_expression_dependencies(uint32_t dst, uint32_t source);
  639. void add_implied_read_expression(SPIRExpression &e, uint32_t source);
  640. void add_implied_read_expression(SPIRAccessChain &e, uint32_t source);
  641. void add_active_interface_variable(uint32_t var_id);
  642. // For proper multiple entry point support, allow querying if an Input or Output
  643. // variable is part of that entry points interface.
  644. bool interface_variable_exists_in_entry_point(uint32_t id) const;
  645. SmallVector<CombinedImageSampler> combined_image_samplers;
  646. void remap_variable_type_name(const SPIRType &type, const std::string &var_name, std::string &type_name) const
  647. {
  648. if (variable_remap_callback)
  649. variable_remap_callback(type, var_name, type_name);
  650. }
  651. void set_ir(const ParsedIR &parsed);
  652. void set_ir(ParsedIR &&parsed);
  653. void parse_fixup();
  654. // Used internally to implement various traversals for queries.
  655. struct OpcodeHandler
  656. {
  657. virtual ~OpcodeHandler() = default;
  658. // Return true if traversal should continue.
  659. // If false, traversal will end immediately.
  660. virtual bool handle(spv::Op opcode, const uint32_t *args, uint32_t length) = 0;
  661. virtual bool handle_terminator(const SPIRBlock &)
  662. {
  663. return true;
  664. }
  665. virtual bool follow_function_call(const SPIRFunction &)
  666. {
  667. return true;
  668. }
  669. virtual void set_current_block(const SPIRBlock &)
  670. {
  671. }
  672. // Called after returning from a function or when entering a block,
  673. // can be called multiple times per block,
  674. // while set_current_block is only called on block entry.
  675. virtual void rearm_current_block(const SPIRBlock &)
  676. {
  677. }
  678. virtual bool begin_function_scope(const uint32_t *, uint32_t)
  679. {
  680. return true;
  681. }
  682. virtual bool end_function_scope(const uint32_t *, uint32_t)
  683. {
  684. return true;
  685. }
  686. };
  687. struct BufferAccessHandler : OpcodeHandler
  688. {
  689. BufferAccessHandler(const Compiler &compiler_, SmallVector<BufferRange> &ranges_, uint32_t id_)
  690. : compiler(compiler_)
  691. , ranges(ranges_)
  692. , id(id_)
  693. {
  694. }
  695. bool handle(spv::Op opcode, const uint32_t *args, uint32_t length) override;
  696. const Compiler &compiler;
  697. SmallVector<BufferRange> &ranges;
  698. uint32_t id;
  699. std::unordered_set<uint32_t> seen;
  700. };
  701. struct InterfaceVariableAccessHandler : OpcodeHandler
  702. {
  703. InterfaceVariableAccessHandler(const Compiler &compiler_, std::unordered_set<VariableID> &variables_)
  704. : compiler(compiler_)
  705. , variables(variables_)
  706. {
  707. }
  708. bool handle(spv::Op opcode, const uint32_t *args, uint32_t length) override;
  709. const Compiler &compiler;
  710. std::unordered_set<VariableID> &variables;
  711. };
  712. struct CombinedImageSamplerHandler : OpcodeHandler
  713. {
  714. CombinedImageSamplerHandler(Compiler &compiler_)
  715. : compiler(compiler_)
  716. {
  717. }
  718. bool handle(spv::Op opcode, const uint32_t *args, uint32_t length) override;
  719. bool begin_function_scope(const uint32_t *args, uint32_t length) override;
  720. bool end_function_scope(const uint32_t *args, uint32_t length) override;
  721. Compiler &compiler;
  722. // Each function in the call stack needs its own remapping for parameters so we can deduce which global variable each texture/sampler the parameter is statically bound to.
  723. std::stack<std::unordered_map<uint32_t, uint32_t>> parameter_remapping;
  724. std::stack<SPIRFunction *> functions;
  725. uint32_t remap_parameter(uint32_t id);
  726. void push_remap_parameters(const SPIRFunction &func, const uint32_t *args, uint32_t length);
  727. void pop_remap_parameters();
  728. void register_combined_image_sampler(SPIRFunction &caller, VariableID combined_id, VariableID texture_id,
  729. VariableID sampler_id, bool depth);
  730. };
  731. struct DummySamplerForCombinedImageHandler : OpcodeHandler
  732. {
  733. DummySamplerForCombinedImageHandler(Compiler &compiler_)
  734. : compiler(compiler_)
  735. {
  736. }
  737. bool handle(spv::Op opcode, const uint32_t *args, uint32_t length) override;
  738. Compiler &compiler;
  739. bool need_dummy_sampler = false;
  740. };
  741. struct ActiveBuiltinHandler : OpcodeHandler
  742. {
  743. ActiveBuiltinHandler(Compiler &compiler_)
  744. : compiler(compiler_)
  745. {
  746. }
  747. bool handle(spv::Op opcode, const uint32_t *args, uint32_t length) override;
  748. Compiler &compiler;
  749. void handle_builtin(const SPIRType &type, spv::BuiltIn builtin, const Bitset &decoration_flags);
  750. void add_if_builtin(uint32_t id);
  751. void add_if_builtin_or_block(uint32_t id);
  752. void add_if_builtin(uint32_t id, bool allow_blocks);
  753. };
  754. bool traverse_all_reachable_opcodes(const SPIRBlock &block, OpcodeHandler &handler) const;
  755. bool traverse_all_reachable_opcodes(const SPIRFunction &block, OpcodeHandler &handler) const;
  756. // This must be an ordered data structure so we always pick the same type aliases.
  757. SmallVector<uint32_t> global_struct_cache;
  758. ShaderResources get_shader_resources(const std::unordered_set<VariableID> *active_variables) const;
  759. VariableTypeRemapCallback variable_remap_callback;
  760. bool get_common_basic_type(const SPIRType &type, SPIRType::BaseType &base_type);
  761. std::unordered_set<uint32_t> forced_temporaries;
  762. std::unordered_set<uint32_t> forwarded_temporaries;
  763. std::unordered_set<uint32_t> suppressed_usage_tracking;
  764. std::unordered_set<uint32_t> hoisted_temporaries;
  765. std::unordered_set<uint32_t> forced_invariant_temporaries;
  766. Bitset active_input_builtins;
  767. Bitset active_output_builtins;
  768. uint32_t clip_distance_count = 0;
  769. uint32_t cull_distance_count = 0;
  770. bool position_invariant = false;
  771. void analyze_parameter_preservation(
  772. SPIRFunction &entry, const CFG &cfg,
  773. const std::unordered_map<uint32_t, std::unordered_set<uint32_t>> &variable_to_blocks,
  774. const std::unordered_map<uint32_t, std::unordered_set<uint32_t>> &complete_write_blocks);
  775. // If a variable ID or parameter ID is found in this set, a sampler is actually a shadow/comparison sampler.
  776. // SPIR-V does not support this distinction, so we must keep track of this information outside the type system.
  777. // There might be unrelated IDs found in this set which do not correspond to actual variables.
  778. // This set should only be queried for the existence of samplers which are already known to be variables or parameter IDs.
  779. // Similar is implemented for images, as well as if subpass inputs are needed.
  780. std::unordered_set<uint32_t> comparison_ids;
  781. bool need_subpass_input = false;
  782. bool need_subpass_input_ms = false;
  783. // In certain backends, we will need to use a dummy sampler to be able to emit code.
  784. // GLSL does not support texelFetch on texture2D objects, but SPIR-V does,
  785. // so we need to workaround by having the application inject a dummy sampler.
  786. uint32_t dummy_sampler_id = 0;
  787. void analyze_image_and_sampler_usage();
  788. struct CombinedImageSamplerDrefHandler : OpcodeHandler
  789. {
  790. CombinedImageSamplerDrefHandler(Compiler &compiler_)
  791. : compiler(compiler_)
  792. {
  793. }
  794. bool handle(spv::Op opcode, const uint32_t *args, uint32_t length) override;
  795. Compiler &compiler;
  796. std::unordered_set<uint32_t> dref_combined_samplers;
  797. };
  798. struct CombinedImageSamplerUsageHandler : OpcodeHandler
  799. {
  800. CombinedImageSamplerUsageHandler(Compiler &compiler_,
  801. const std::unordered_set<uint32_t> &dref_combined_samplers_)
  802. : compiler(compiler_)
  803. , dref_combined_samplers(dref_combined_samplers_)
  804. {
  805. }
  806. bool begin_function_scope(const uint32_t *args, uint32_t length) override;
  807. bool handle(spv::Op opcode, const uint32_t *args, uint32_t length) override;
  808. Compiler &compiler;
  809. const std::unordered_set<uint32_t> &dref_combined_samplers;
  810. std::unordered_map<uint32_t, std::unordered_set<uint32_t>> dependency_hierarchy;
  811. std::unordered_set<uint32_t> comparison_ids;
  812. void add_hierarchy_to_comparison_ids(uint32_t ids);
  813. bool need_subpass_input = false;
  814. bool need_subpass_input_ms = false;
  815. void add_dependency(uint32_t dst, uint32_t src);
  816. };
  817. void build_function_control_flow_graphs_and_analyze();
  818. std::unordered_map<uint32_t, std::unique_ptr<CFG>> function_cfgs;
  819. const CFG &get_cfg_for_current_function() const;
  820. const CFG &get_cfg_for_function(uint32_t id) const;
  821. struct CFGBuilder : OpcodeHandler
  822. {
  823. explicit CFGBuilder(Compiler &compiler_);
  824. bool follow_function_call(const SPIRFunction &func) override;
  825. bool handle(spv::Op op, const uint32_t *args, uint32_t length) override;
  826. Compiler &compiler;
  827. std::unordered_map<uint32_t, std::unique_ptr<CFG>> function_cfgs;
  828. };
  829. struct AnalyzeVariableScopeAccessHandler : OpcodeHandler
  830. {
  831. AnalyzeVariableScopeAccessHandler(Compiler &compiler_, SPIRFunction &entry_);
  832. bool follow_function_call(const SPIRFunction &) override;
  833. void set_current_block(const SPIRBlock &block) override;
  834. void notify_variable_access(uint32_t id, uint32_t block);
  835. bool id_is_phi_variable(uint32_t id) const;
  836. bool id_is_potential_temporary(uint32_t id) const;
  837. bool handle(spv::Op op, const uint32_t *args, uint32_t length) override;
  838. bool handle_terminator(const SPIRBlock &block) override;
  839. Compiler &compiler;
  840. SPIRFunction &entry;
  841. std::unordered_map<uint32_t, std::unordered_set<uint32_t>> accessed_variables_to_block;
  842. std::unordered_map<uint32_t, std::unordered_set<uint32_t>> accessed_temporaries_to_block;
  843. std::unordered_map<uint32_t, uint32_t> result_id_to_type;
  844. std::unordered_map<uint32_t, std::unordered_set<uint32_t>> complete_write_variables_to_block;
  845. std::unordered_map<uint32_t, std::unordered_set<uint32_t>> partial_write_variables_to_block;
  846. std::unordered_set<uint32_t> access_chain_expressions;
  847. // Access chains used in multiple blocks mean hoisting all the variables used to construct the access chain as not all backends can use pointers.
  848. // This is also relevant when forwarding opaque objects since we cannot lower these to temporaries.
  849. std::unordered_map<uint32_t, std::unordered_set<uint32_t>> rvalue_forward_children;
  850. const SPIRBlock *current_block = nullptr;
  851. };
  852. struct StaticExpressionAccessHandler : OpcodeHandler
  853. {
  854. StaticExpressionAccessHandler(Compiler &compiler_, uint32_t variable_id_);
  855. bool follow_function_call(const SPIRFunction &) override;
  856. bool handle(spv::Op op, const uint32_t *args, uint32_t length) override;
  857. Compiler &compiler;
  858. uint32_t variable_id;
  859. uint32_t static_expression = 0;
  860. uint32_t write_count = 0;
  861. };
  862. struct PhysicalBlockMeta
  863. {
  864. uint32_t alignment = 0;
  865. };
  866. struct PhysicalStorageBufferPointerHandler : OpcodeHandler
  867. {
  868. explicit PhysicalStorageBufferPointerHandler(Compiler &compiler_);
  869. bool handle(spv::Op op, const uint32_t *args, uint32_t length) override;
  870. Compiler &compiler;
  871. std::unordered_set<uint32_t> non_block_types;
  872. std::unordered_map<uint32_t, PhysicalBlockMeta> physical_block_type_meta;
  873. std::unordered_map<uint32_t, PhysicalBlockMeta *> access_chain_to_physical_block;
  874. void mark_aligned_access(uint32_t id, const uint32_t *args, uint32_t length);
  875. PhysicalBlockMeta *find_block_meta(uint32_t id) const;
  876. bool type_is_bda_block_entry(uint32_t type_id) const;
  877. void setup_meta_chain(uint32_t type_id, uint32_t var_id);
  878. uint32_t get_minimum_scalar_alignment(const SPIRType &type) const;
  879. void analyze_non_block_types_from_block(const SPIRType &type);
  880. uint32_t get_base_non_block_type_id(uint32_t type_id) const;
  881. };
  882. void analyze_non_block_pointer_types();
  883. SmallVector<uint32_t> physical_storage_non_block_pointer_types;
  884. std::unordered_map<uint32_t, PhysicalBlockMeta> physical_storage_type_to_alignment;
  885. void analyze_variable_scope(SPIRFunction &function, AnalyzeVariableScopeAccessHandler &handler);
  886. void find_function_local_luts(SPIRFunction &function, const AnalyzeVariableScopeAccessHandler &handler,
  887. bool single_function);
  888. bool may_read_undefined_variable_in_block(const SPIRBlock &block, uint32_t var);
  889. // Finds all resources that are written to from inside the critical section, if present.
  890. // The critical section is delimited by OpBeginInvocationInterlockEXT and
  891. // OpEndInvocationInterlockEXT instructions. In MSL and HLSL, any resources written
  892. // while inside the critical section must be placed in a raster order group.
  893. struct InterlockedResourceAccessHandler : OpcodeHandler
  894. {
  895. InterlockedResourceAccessHandler(Compiler &compiler_, uint32_t entry_point_id)
  896. : compiler(compiler_)
  897. {
  898. call_stack.push_back(entry_point_id);
  899. }
  900. bool handle(spv::Op op, const uint32_t *args, uint32_t length) override;
  901. bool begin_function_scope(const uint32_t *args, uint32_t length) override;
  902. bool end_function_scope(const uint32_t *args, uint32_t length) override;
  903. Compiler &compiler;
  904. bool in_crit_sec = false;
  905. uint32_t interlock_function_id = 0;
  906. bool split_function_case = false;
  907. bool control_flow_interlock = false;
  908. bool use_critical_section = false;
  909. bool call_stack_is_interlocked = false;
  910. SmallVector<uint32_t> call_stack;
  911. void access_potential_resource(uint32_t id);
  912. };
  913. struct InterlockedResourceAccessPrepassHandler : OpcodeHandler
  914. {
  915. InterlockedResourceAccessPrepassHandler(Compiler &compiler_, uint32_t entry_point_id)
  916. : compiler(compiler_)
  917. {
  918. call_stack.push_back(entry_point_id);
  919. }
  920. void rearm_current_block(const SPIRBlock &block) override;
  921. bool handle(spv::Op op, const uint32_t *args, uint32_t length) override;
  922. bool begin_function_scope(const uint32_t *args, uint32_t length) override;
  923. bool end_function_scope(const uint32_t *args, uint32_t length) override;
  924. Compiler &compiler;
  925. uint32_t interlock_function_id = 0;
  926. uint32_t current_block_id = 0;
  927. bool split_function_case = false;
  928. bool control_flow_interlock = false;
  929. SmallVector<uint32_t> call_stack;
  930. };
  931. void analyze_interlocked_resource_usage();
  932. // The set of all resources written while inside the critical section, if present.
  933. std::unordered_set<uint32_t> interlocked_resources;
  934. bool interlocked_is_complex = false;
  935. void make_constant_null(uint32_t id, uint32_t type);
  936. std::unordered_map<uint32_t, std::string> declared_block_names;
  937. bool instruction_to_result_type(uint32_t &result_type, uint32_t &result_id, spv::Op op, const uint32_t *args,
  938. uint32_t length);
  939. Bitset combined_decoration_for_member(const SPIRType &type, uint32_t index) const;
  940. static bool is_desktop_only_format(spv::ImageFormat format);
  941. bool is_depth_image(const SPIRType &type, uint32_t id) const;
  942. void set_extended_decoration(uint32_t id, ExtendedDecorations decoration, uint32_t value = 0);
  943. uint32_t get_extended_decoration(uint32_t id, ExtendedDecorations decoration) const;
  944. bool has_extended_decoration(uint32_t id, ExtendedDecorations decoration) const;
  945. void unset_extended_decoration(uint32_t id, ExtendedDecorations decoration);
  946. void set_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration,
  947. uint32_t value = 0);
  948. uint32_t get_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration) const;
  949. bool has_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration) const;
  950. void unset_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration);
  951. bool type_is_array_of_pointers(const SPIRType &type) const;
  952. bool type_is_top_level_physical_pointer(const SPIRType &type) const;
  953. bool type_is_top_level_pointer(const SPIRType &type) const;
  954. bool type_is_top_level_array(const SPIRType &type) const;
  955. bool type_is_block_like(const SPIRType &type) const;
  956. bool type_is_opaque_value(const SPIRType &type) const;
  957. bool reflection_ssbo_instance_name_is_significant() const;
  958. std::string get_remapped_declared_block_name(uint32_t id, bool fallback_prefer_instance_name) const;
  959. bool flush_phi_required(BlockID from, BlockID to) const;
  960. uint32_t evaluate_spec_constant_u32(const SPIRConstantOp &spec) const;
  961. uint32_t evaluate_constant_u32(uint32_t id) const;
  962. bool is_vertex_like_shader() const;
  963. // Get the correct case list for the OpSwitch, since it can be either a
  964. // 32 bit wide condition or a 64 bit, but the type is not embedded in the
  965. // instruction itself.
  966. const SmallVector<SPIRBlock::Case> &get_case_list(const SPIRBlock &block) const;
  967. private:
  968. // Used only to implement the old deprecated get_entry_point() interface.
  969. const SPIREntryPoint &get_first_entry_point(const std::string &name) const;
  970. SPIREntryPoint &get_first_entry_point(const std::string &name);
  971. };
  972. } // namespace SPIRV_CROSS_NAMESPACE
  973. #endif