Debian Codegraph @

third_party/spirv-cross/spirv_common.hpp

raw
1 /*
2 * Copyright 2015-2020 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
17 #ifndef SPIRV_CROSS_COMMON_HPP
18 #define SPIRV_CROSS_COMMON_HPP
19
20 #include "spirv.hpp"
21 #include "spirv_cross_containers.hpp"
22 #include "spirv_cross_error_handling.hpp"
23 #include <functional>
24
25 // A bit crude, but allows projects which embed SPIRV-Cross statically to
26 // effectively hide all the symbols from other projects.
27 // There is a case where we have:
28 // - Project A links against SPIRV-Cross statically.
29 // - Project A links against Project B statically.
30 // - Project B links against SPIRV-Cross statically (might be a different version).
31 // This leads to a conflict with extremely bizarre results.
32 // By overriding the namespace in one of the project builds, we can work around this.
33 // If SPIRV-Cross is embedded in dynamic libraries,
34 // prefer using -fvisibility=hidden on GCC/Clang instead.
35 #ifdef SPIRV_CROSS_NAMESPACE_OVERRIDE
36 #define SPIRV_CROSS_NAMESPACE SPIRV_CROSS_NAMESPACE_OVERRIDE
37 #else
38 #define SPIRV_CROSS_NAMESPACE spirv_cross
39 #endif
40
41 namespace SPIRV_CROSS_NAMESPACE
42 {
43 namespace inner
44 {
45 template <typename T>
46 void join_helper(StringStream<> &stream, T &&t)
47 {
48 stream << std::forward<T>(t);
49 }
50
51 template <typename T, typename... Ts>
52 void join_helper(StringStream<> &stream, T &&t, Ts &&... ts)
53 {
54 stream << std::forward<T>(t);
55 join_helper(stream, std::forward<Ts>(ts)...);
56 }
57 } // namespace inner
58
59 class Bitset
60 {
61 public:
62 Bitset() = default;
63 explicit inline Bitset(uint64_t lower_)
64 : lower(lower_)
65 {
66 }
67
68 inline bool get(uint32_t bit) const
69 {
70 if (bit < 64)
71 return (lower & (1ull << bit)) != 0;
72 else
73 return higher.count(bit) != 0;
74 }
75
76 inline void set(uint32_t bit)
77 {
78 if (bit < 64)
79 lower |= 1ull << bit;
80 else
81 higher.insert(bit);
82 }
83
84 inline void clear(uint32_t bit)
85 {
86 if (bit < 64)
87 lower &= ~(1ull << bit);
88 else
89 higher.erase(bit);
90 }
91
92 inline uint64_t get_lower() const
93 {
94 return lower;
95 }
96
97 inline void reset()
98 {
99 lower = 0;
100 higher.clear();
101 }
102
103 inline void merge_and(const Bitset &other)
104 {
105 lower &= other.lower;
106 std::unordered_set<uint32_t> tmp_set;
107 for (auto &v : higher)
108 if (other.higher.count(v) != 0)
109 tmp_set.insert(v);
110 higher = std::move(tmp_set);
111 }
112
113 inline void merge_or(const Bitset &other)
114 {
115 lower |= other.lower;
116 for (auto &v : other.higher)
117 higher.insert(v);
118 }
119
120 inline bool operator==(const Bitset &other) const
121 {
122 if (lower != other.lower)
123 return false;
124
125 if (higher.size() != other.higher.size())
126 return false;
127
128 for (auto &v : higher)
129 if (other.higher.count(v) == 0)
130 return false;
131
132 return true;
133 }
134
135 inline bool operator!=(const Bitset &other) const
136 {
137 return !(*this == other);
138 }
139
140 template <typename Op>
141 void for_each_bit(const Op &op) const
142 {
143 // TODO: Add ctz-based iteration.
144 for (uint32_t i = 0; i < 64; i++)
145 {
146 if (lower & (1ull << i))
147 op(i);
148 }
149
150 if (higher.empty())
151 return;
152
153 // Need to enforce an order here for reproducible results,
154 // but hitting this path should happen extremely rarely, so having this slow path is fine.
155 SmallVector<uint32_t> bits;
156 bits.reserve(higher.size());
157 for (auto &v : higher)
158 bits.push_back(v);
159 std::sort(std::begin(bits), std::end(bits));
160
161 for (auto &v : bits)
162 op(v);
163 }
164
165 inline bool empty() const
166 {
167 return lower == 0 && higher.empty();
168 }
169
170 private:
171 // The most common bits to set are all lower than 64,
172 // so optimize for this case. Bits spilling outside 64 go into a slower data structure.
173 // In almost all cases, higher data structure will not be used.
174 uint64_t lower = 0;
175 std::unordered_set<uint32_t> higher;
176 };
177
178 // Helper template to avoid lots of nasty string temporary munging.
179 template <typename... Ts>
180 std::string join(Ts &&... ts)
181 {
182 StringStream<> stream;
183 inner::join_helper(stream, std::forward<Ts>(ts)...);
184 return stream.str();
185 }
186
187 inline std::string merge(const SmallVector<std::string> &list, const char *between = ", ")
188 {
189 StringStream<> stream;
190 for (auto &elem : list)
191 {
192 stream << elem;
193 if (&elem != &list.back())
194 stream << between;
195 }
196 return stream.str();
197 }
198
199 // Make sure we don't accidentally call this with float or doubles with SFINAE.
200 // Have to use the radix-aware overload.
201 template <typename T, typename std::enable_if<!std::is_floating_point<T>::value, int>::type = 0>
202 inline std::string convert_to_string(const T &t)
203 {
204 return std::to_string(t);
205 }
206
207 // Allow implementations to set a convenient standard precision
208 #ifndef SPIRV_CROSS_FLT_FMT
209 #define SPIRV_CROSS_FLT_FMT "%.32g"
210 #endif
211
212 // Disable sprintf and strcat warnings.
213 // We cannot rely on snprintf and family existing because, ..., MSVC.
214 #if defined(__clang__) || defined(__GNUC__)
215 #pragma GCC diagnostic push
216 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
217 #elif defined(_MSC_VER)
218 #pragma warning(push)
219 #pragma warning(disable : 4996)
220 #endif
221
222 static inline void fixup_radix_point(char *str, char radix_point)
223 {
224 // Setting locales is a very risky business in multi-threaded program,
225 // so just fixup locales instead. We only need to care about the radix point.
226 if (radix_point != '.')
227 {
228 while (*str != '\0')
229 {
230 if (*str == radix_point)
231 *str = '.';
232 str++;
233 }
234 }
235 }
236
237 inline std::string convert_to_string(float t, char locale_radix_point)
238 {
239 // std::to_string for floating point values is broken.
240 // Fallback to something more sane.
241 char buf[64];
242 sprintf(buf, SPIRV_CROSS_FLT_FMT, t);
243 fixup_radix_point(buf, locale_radix_point);
244
245 // Ensure that the literal is float.
246 if (!strchr(buf, '.') && !strchr(buf, 'e'))
247 strcat(buf, ".0");
248 return buf;
249 }
250
251 inline std::string convert_to_string(double t, char locale_radix_point)
252 {
253 // std::to_string for floating point values is broken.
254 // Fallback to something more sane.
255 char buf[64];
256 sprintf(buf, SPIRV_CROSS_FLT_FMT, t);
257 fixup_radix_point(buf, locale_radix_point);
258
259 // Ensure that the literal is float.
260 if (!strchr(buf, '.') && !strchr(buf, 'e'))
261 strcat(buf, ".0");
262 return buf;
263 }
264
265 template <typename T>
266 struct ValueSaver
267 {
268 explicit ValueSaver(T &current_)
269 : current(current_)
270 , saved(current_)
271 {
272 }
273
274 void release()
275 {
276 current = saved;
277 }
278
279 ~ValueSaver()
280 {
281 release();
282 }
283
284 T &current;
285 T saved;
286 };
287
288 #if defined(__clang__) || defined(__GNUC__)
289 #pragma GCC diagnostic pop
290 #elif defined(_MSC_VER)
291 #pragma warning(pop)
292 #endif
293
294 struct Instruction
295 {
296 uint16_t op = 0;
297 uint16_t count = 0;
298 uint32_t offset = 0;
299 uint32_t length = 0;
300 };
301
302 enum Types
303 {
304 TypeNone,
305 TypeType,
306 TypeVariable,
307 TypeConstant,
308 TypeFunction,
309 TypeFunctionPrototype,
310 TypeBlock,
311 TypeExtension,
312 TypeExpression,
313 TypeConstantOp,
314 TypeCombinedImageSampler,
315 TypeAccessChain,
316 TypeUndef,
317 TypeString,
318 TypeCount
319 };
320
321 template <Types type>
322 class TypedID;
323
324 template <>
325 class TypedID<TypeNone>
326 {
327 public:
328 TypedID() = default;
329 TypedID(uint32_t id_)
330 : id(id_)
331 {
332 }
333
334 template <Types U>
335 TypedID(const TypedID<U> &other)
336 {
337 *this = other;
338 }
339
340 template <Types U>
341 TypedID &operator=(const TypedID<U> &other)
342 {
343 id = uint32_t(other);
344 return *this;
345 }
346
347 // Implicit conversion to u32 is desired here.
348 // As long as we block implicit conversion between TypedID<A> and TypedID<B> we're good.
349 operator uint32_t() const
350 {
351 return id;
352 }
353
354 template <Types U>
355 operator TypedID<U>() const
356 {
357 return TypedID<U>(*this);
358 }
359
360 private:
361 uint32_t id = 0;
362 };
363
364 template <Types type>
365 class TypedID
366 {
367 public:
368 TypedID() = default;
369 TypedID(uint32_t id_)
370 : id(id_)
371 {
372 }
373
374 explicit TypedID(const TypedID<TypeNone> &other)
375 : id(uint32_t(other))
376 {
377 }
378
379 operator uint32_t() const
380 {
381 return id;
382 }
383
384 private:
385 uint32_t id = 0;
386 };
387
388 using VariableID = TypedID<TypeVariable>;
389 using TypeID = TypedID<TypeType>;
390 using ConstantID = TypedID<TypeConstant>;
391 using FunctionID = TypedID<TypeFunction>;
392 using BlockID = TypedID<TypeBlock>;
393 using ID = TypedID<TypeNone>;
394
395 // Helper for Variant interface.
396 struct IVariant
397 {
398 virtual ~IVariant() = default;
399 virtual IVariant *clone(ObjectPoolBase *pool) = 0;
400 ID self = 0;
401 };
402
403 #define SPIRV_CROSS_DECLARE_CLONE(T) \
404 IVariant *clone(ObjectPoolBase *pool) override \
405 { \
406 return static_cast<ObjectPool<T> *>(pool)->allocate(*this); \
407 }
408
409 struct SPIRUndef : IVariant
410 {
411 enum
412 {
413 type = TypeUndef
414 };
415
416 explicit SPIRUndef(TypeID basetype_)
417 : basetype(basetype_)
418 {
419 }
420 TypeID basetype;
421
422 SPIRV_CROSS_DECLARE_CLONE(SPIRUndef)
423 };
424
425 struct SPIRString : IVariant
426 {
427 enum
428 {
429 type = TypeString
430 };
431
432 explicit SPIRString(std::string str_)
433 : str(std::move(str_))
434 {
435 }
436
437 std::string str;
438
439 SPIRV_CROSS_DECLARE_CLONE(SPIRString)
440 };
441
442 // This type is only used by backends which need to access the combined image and sampler IDs separately after
443 // the OpSampledImage opcode.
444 struct SPIRCombinedImageSampler : IVariant
445 {
446 enum
447 {
448 type = TypeCombinedImageSampler
449 };
450 SPIRCombinedImageSampler(TypeID type_, VariableID image_, VariableID sampler_)
451 : combined_type(type_)
452 , image(image_)
453 , sampler(sampler_)
454 {
455 }
456 TypeID combined_type;
457 VariableID image;
458 VariableID sampler;
459
460 SPIRV_CROSS_DECLARE_CLONE(SPIRCombinedImageSampler)
461 };
462
463 struct SPIRConstantOp : IVariant
464 {
465 enum
466 {
467 type = TypeConstantOp
468 };
469
470 SPIRConstantOp(TypeID result_type, spv::Op op, const uint32_t *args, uint32_t length)
471 : opcode(op)
472 , basetype(result_type)
473 {
474 arguments.reserve(length);
475 for (uint32_t i = 0; i < length; i++)
476 arguments.push_back(args[i]);
477 }
478
479 spv::Op opcode;
480 SmallVector<uint32_t> arguments;
481 TypeID basetype;
482
483 SPIRV_CROSS_DECLARE_CLONE(SPIRConstantOp)
484 };
485
486 struct SPIRType : IVariant
487 {
488 enum
489 {
490 type = TypeType
491 };
492
493 enum BaseType
494 {
495 Unknown,
496 Void,
497 Boolean,
498 SByte,
499 UByte,
500 Short,
501 UShort,
502 Int,
503 UInt,
504 Int64,
505 UInt64,
506 AtomicCounter,
507 Half,
508 Float,
509 Double,
510 Struct,
511 Image,
512 SampledImage,
513 Sampler,
514 AccelerationStructure,
515 RayQuery,
516
517 // Keep internal types at the end.
518 ControlPointArray,
519 Interpolant,
520 Char
521 };
522
523 // Scalar/vector/matrix support.
524 BaseType basetype = Unknown;
525 uint32_t width = 0;
526 uint32_t vecsize = 1;
527 uint32_t columns = 1;
528
529 // Arrays, support array of arrays by having a vector of array sizes.
530 SmallVector<uint32_t> array;
531
532 // Array elements can be either specialization constants or specialization ops.
533 // This array determines how to interpret the array size.
534 // If an element is true, the element is a literal,
535 // otherwise, it's an expression, which must be resolved on demand.
536 // The actual size is not really known until runtime.
537 SmallVector<bool> array_size_literal;
538
539 // Pointers
540 // Keep track of how many pointer layers we have.
541 uint32_t pointer_depth = 0;
542 bool pointer = false;
543 bool forward_pointer = false;
544
545 spv::StorageClass storage = spv::StorageClassGeneric;
546
547 SmallVector<TypeID> member_types;
548
549 // If member order has been rewritten to handle certain scenarios with Offset,
550 // allow codegen to rewrite the index.
551 SmallVector<uint32_t> member_type_index_redirection;
552
553 struct ImageType
554 {
555 TypeID type;
556 spv::Dim dim;
557 bool depth;
558 bool arrayed;
559 bool ms;
560 uint32_t sampled;
561 spv::ImageFormat format;
562 spv::AccessQualifier access;
563 } image;
564
565 // Structs can be declared multiple times if they are used as part of interface blocks.
566 // We want to detect this so that we only emit the struct definition once.
567 // Since we cannot rely on OpName to be equal, we need to figure out aliases.
568 TypeID type_alias = 0;
569
570 // Denotes the type which this type is based on.
571 // Allows the backend to traverse how a complex type is built up during access chains.
572 TypeID parent_type = 0;
573
574 // Used in backends to avoid emitting members with conflicting names.
575 std::unordered_set<std::string> member_name_cache;
576
577 SPIRV_CROSS_DECLARE_CLONE(SPIRType)
578 };
579
580 struct SPIRExtension : IVariant
581 {
582 enum
583 {
584 type = TypeExtension
585 };
586
587 enum Extension
588 {
589 Unsupported,
590 GLSL,
591 SPV_debug_info,
592 SPV_AMD_shader_ballot,
593 SPV_AMD_shader_explicit_vertex_parameter,
594 SPV_AMD_shader_trinary_minmax,
595 SPV_AMD_gcn_shader
596 };
597
598 explicit SPIRExtension(Extension ext_)
599 : ext(ext_)
600 {
601 }
602
603 Extension ext;
604 SPIRV_CROSS_DECLARE_CLONE(SPIRExtension)
605 };
606
607 // SPIREntryPoint is not a variant since its IDs are used to decorate OpFunction,
608 // so in order to avoid conflicts, we can't stick them in the ids array.
609 struct SPIREntryPoint
610 {
611 SPIREntryPoint(FunctionID self_, spv::ExecutionModel execution_model, const std::string &entry_name)
612 : self(self_)
613 , name(entry_name)
614 , orig_name(entry_name)
615 , model(execution_model)
616 {
617 }
618 SPIREntryPoint() = default;
619
620 FunctionID self = 0;
621 std::string name;
622 std::string orig_name;
623 SmallVector<VariableID> interface_variables;
624
625 Bitset flags;
626 struct WorkgroupSize
627 {
628 uint32_t x = 0, y = 0, z = 0;
629 uint32_t constant = 0; // Workgroup size can be expressed as a constant/spec-constant instead.
630 } workgroup_size;
631 uint32_t invocations = 0;
632 uint32_t output_vertices = 0;
633 spv::ExecutionModel model = spv::ExecutionModelMax;
634 bool geometry_passthrough = false;
635 };
636
637 struct SPIRExpression : IVariant
638 {
639 enum
640 {
641 type = TypeExpression
642 };
643
644 // Only created by the backend target to avoid creating tons of temporaries.
645 SPIRExpression(std::string expr, TypeID expression_type_, bool immutable_)
646 : expression(move(expr))
647 , expression_type(expression_type_)
648 , immutable(immutable_)
649 {
650 }
651
652 // If non-zero, prepend expression with to_expression(base_expression).
653 // Used in amortizing multiple calls to to_expression()
654 // where in certain cases that would quickly force a temporary when not needed.
655 ID base_expression = 0;
656
657 std::string expression;
658 TypeID expression_type = 0;
659
660 // If this expression is a forwarded load,
661 // allow us to reference the original variable.
662 ID loaded_from = 0;
663
664 // If this expression will never change, we can avoid lots of temporaries
665 // in high level source.
666 // An expression being immutable can be speculative,
667 // it is assumed that this is true almost always.
668 bool immutable = false;
669
670 // Before use, this expression must be transposed.
671 // This is needed for targets which don't support row_major layouts.
672 bool need_transpose = false;
673
674 // Whether or not this is an access chain expression.
675 bool access_chain = false;
676
677 // A list of expressions which this expression depends on.
678 SmallVector<ID> expression_dependencies;
679
680 // By reading this expression, we implicitly read these expressions as well.
681 // Used by access chain Store and Load since we read multiple expressions in this case.
682 SmallVector<ID> implied_read_expressions;
683
684 // The expression was emitted at a certain scope. Lets us track when an expression read means multiple reads.
685 uint32_t emitted_loop_level = 0;
686
687 SPIRV_CROSS_DECLARE_CLONE(SPIRExpression)
688 };
689
690 struct SPIRFunctionPrototype : IVariant
691 {
692 enum
693 {
694 type = TypeFunctionPrototype
695 };
696
697 explicit SPIRFunctionPrototype(TypeID return_type_)
698 : return_type(return_type_)
699 {
700 }
701
702 TypeID return_type;
703 SmallVector<uint32_t> parameter_types;
704
705 SPIRV_CROSS_DECLARE_CLONE(SPIRFunctionPrototype)
706 };
707
708 struct SPIRBlock : IVariant
709 {
710 enum
711 {
712 type = TypeBlock
713 };
714
715 enum Terminator
716 {
717 Unknown,
718 Direct, // Emit next block directly without a particular condition.
719
720 Select, // Block ends with an if/else block.
721 MultiSelect, // Block ends with switch statement.
722
723 Return, // Block ends with return.
724 Unreachable, // Noop
725 Kill // Discard
726 };
727
728 enum Merge
729 {
730 MergeNone,
731 MergeLoop,
732 MergeSelection
733 };
734
735 enum Hints
736 {
737 HintNone,
738 HintUnroll,
739 HintDontUnroll,
740 HintFlatten,
741 HintDontFlatten
742 };
743
744 enum Method
745 {
746 MergeToSelectForLoop,
747 MergeToDirectForLoop,
748 MergeToSelectContinueForLoop
749 };
750
751 enum ContinueBlockType
752 {
753 ContinueNone,
754
755 // Continue block is branchless and has at least one instruction.
756 ForLoop,
757
758 // Noop continue block.
759 WhileLoop,
760
761 // Continue block is conditional.
762 DoWhileLoop,
763
764 // Highly unlikely that anything will use this,
765 // since it is really awkward/impossible to express in GLSL.
766 ComplexLoop
767 };
768
769 enum : uint32_t
770 {
771 NoDominator = 0xffffffffu
772 };
773
774 Terminator terminator = Unknown;
775 Merge merge = MergeNone;
776 Hints hint = HintNone;
777 BlockID next_block = 0;
778 BlockID merge_block = 0;
779 BlockID continue_block = 0;
780
781 ID return_value = 0; // If 0, return nothing (void).
782 ID condition = 0;
783 BlockID true_block = 0;
784 BlockID false_block = 0;
785 BlockID default_block = 0;
786
787 SmallVector<Instruction> ops;
788
789 struct Phi
790 {
791 ID local_variable; // flush local variable ...
792 BlockID parent; // If we're in from_block and want to branch into this block ...
793 VariableID function_variable; // to this function-global "phi" variable first.
794 };
795
796 // Before entering this block flush out local variables to magical "phi" variables.
797 SmallVector<Phi> phi_variables;
798
799 // Declare these temporaries before beginning the block.
800 // Used for handling complex continue blocks which have side effects.
801 SmallVector<std::pair<TypeID, ID>> declare_temporary;
802
803 // Declare these temporaries, but only conditionally if this block turns out to be
804 // a complex loop header.
805 SmallVector<std::pair<TypeID, ID>> potential_declare_temporary;
806
807 struct Case
808 {
809 uint32_t value;
810 BlockID block;
811 };
812 SmallVector<Case> cases;
813
814 // If we have tried to optimize code for this block but failed,
815 // keep track of this.
816 bool disable_block_optimization = false;
817
818 // If the continue block is complex, fallback to "dumb" for loops.
819 bool complex_continue = false;
820
821 // Do we need a ladder variable to defer breaking out of a loop construct after a switch block?
822 bool need_ladder_break = false;
823
824 // If marked, we have explicitly handled Phi from this block, so skip any flushes related to that on a branch.
825 // Used to handle an edge case with switch and case-label fallthrough where fall-through writes to Phi.
826 BlockID ignore_phi_from_block = 0;
827
828 // The dominating block which this block might be within.
829 // Used in continue; blocks to determine if we really need to write continue.
830 BlockID loop_dominator = 0;
831
832 // All access to these variables are dominated by this block,
833 // so before branching anywhere we need to make sure that we declare these variables.
834 SmallVector<VariableID> dominated_variables;
835
836 // These are variables which should be declared in a for loop header, if we
837 // fail to use a classic for-loop,
838 // we remove these variables, and fall back to regular variables outside the loop.
839 SmallVector<VariableID> loop_variables;
840
841 // Some expressions are control-flow dependent, i.e. any instruction which relies on derivatives or
842 // sub-group-like operations.
843 // Make sure that we only use these expressions in the original block.
844 SmallVector<ID> invalidate_expressions;
845
846 SPIRV_CROSS_DECLARE_CLONE(SPIRBlock)
847 };
848
849 struct SPIRFunction : IVariant
850 {
851 enum
852 {
853 type = TypeFunction
854 };
855
856 SPIRFunction(TypeID return_type_, TypeID function_type_)
857 : return_type(return_type_)
858 , function_type(function_type_)
859 {
860 }
861
862 struct Parameter
863 {
864 TypeID type;
865 ID id;
866 uint32_t read_count;
867 uint32_t write_count;
868
869 // Set to true if this parameter aliases a global variable,
870 // used mostly in Metal where global variables
871 // have to be passed down to functions as regular arguments.
872 // However, for this kind of variable, we should not care about
873 // read and write counts as access to the function arguments
874 // is not local to the function in question.
875 bool alias_global_variable;
876 };
877
878 // When calling a function, and we're remapping separate image samplers,
879 // resolve these arguments into combined image samplers and pass them
880 // as additional arguments in this order.
881 // It gets more complicated as functions can pull in their own globals
882 // and combine them with parameters,
883 // so we need to distinguish if something is local parameter index
884 // or a global ID.
885 struct CombinedImageSamplerParameter
886 {
887 VariableID id;
888 VariableID image_id;
889 VariableID sampler_id;
890 bool global_image;
891 bool global_sampler;
892 bool depth;
893 };
894
895 TypeID return_type;
896 TypeID function_type;
897 SmallVector<Parameter> arguments;
898
899 // Can be used by backends to add magic arguments.
900 // Currently used by combined image/sampler implementation.
901
902 SmallVector<Parameter> shadow_arguments;
903 SmallVector<VariableID> local_variables;
904 BlockID entry_block = 0;
905 SmallVector<BlockID> blocks;
906 SmallVector<CombinedImageSamplerParameter> combined_parameters;
907
908 struct EntryLine
909 {
910 uint32_t file_id = 0;
911 uint32_t line_literal = 0;
912 };
913 EntryLine entry_line;
914
915 void add_local_variable(VariableID id)
916 {
917 local_variables.push_back(id);
918 }
919
920 void add_parameter(TypeID parameter_type, ID id, bool alias_global_variable = false)
921 {
922 // Arguments are read-only until proven otherwise.
923 arguments.push_back({ parameter_type, id, 0u, 0u, alias_global_variable });
924 }
925
926 // Hooks to be run when the function returns.
927 // Mostly used for lowering internal data structures onto flattened structures.
928 // Need to defer this, because they might rely on things which change during compilation.
929 // Intentionally not a small vector, this one is rare, and std::function can be large.
930 Vector<std::function<void()>> fixup_hooks_out;
931
932 // Hooks to be run when the function begins.
933 // Mostly used for populating internal data structures from flattened structures.
934 // Need to defer this, because they might rely on things which change during compilation.
935 // Intentionally not a small vector, this one is rare, and std::function can be large.
936 Vector<std::function<void()>> fixup_hooks_in;
937
938 // On function entry, make sure to copy a constant array into thread addr space to work around
939 // the case where we are passing a constant array by value to a function on backends which do not
940 // consider arrays value types.
941 SmallVector<ID> constant_arrays_needed_on_stack;
942
943 bool active = false;
944 bool flush_undeclared = true;
945 bool do_combined_parameters = true;
946
947 SPIRV_CROSS_DECLARE_CLONE(SPIRFunction)
948 };
949
950 struct SPIRAccessChain : IVariant
951 {
952 enum
953 {
954 type = TypeAccessChain
955 };
956
957 SPIRAccessChain(TypeID basetype_, spv::StorageClass storage_, std::string base_, std::string dynamic_index_,
958 int32_t static_index_)
959 : basetype(basetype_)
960 , storage(storage_)
961 , base(std::move(base_))
962 , dynamic_index(std::move(dynamic_index_))
963 , static_index(static_index_)
964 {
965 }
966
967 // The access chain represents an offset into a buffer.
968 // Some backends need more complicated handling of access chains to be able to use buffers, like HLSL
969 // which has no usable buffer type ala GLSL SSBOs.
970 // StructuredBuffer is too limited, so our only option is to deal with ByteAddressBuffer which works with raw addresses.
971
972 TypeID basetype;
973 spv::StorageClass storage;
974 std::string base;
975 std::string dynamic_index;
976 int32_t static_index;
977
978 VariableID loaded_from = 0;
979 uint32_t matrix_stride = 0;
980 uint32_t array_stride = 0;
981 bool row_major_matrix = false;
982 bool immutable = false;
983
984 // By reading this expression, we implicitly read these expressions as well.
985 // Used by access chain Store and Load since we read multiple expressions in this case.
986 SmallVector<ID> implied_read_expressions;
987
988 SPIRV_CROSS_DECLARE_CLONE(SPIRAccessChain)
989 };
990
991 struct SPIRVariable : IVariant
992 {
993 enum
994 {
995 type = TypeVariable
996 };
997
998 SPIRVariable() = default;
999 SPIRVariable(TypeID basetype_, spv::StorageClass storage_, ID initializer_ = 0, VariableID basevariable_ = 0)
1000 : basetype(basetype_)
1001 , storage(storage_)
1002 , initializer(initializer_)
1003 , basevariable(basevariable_)
1004 {
1005 }
1006
1007 TypeID basetype = 0;
1008 spv::StorageClass storage = spv::StorageClassGeneric;
1009 uint32_t decoration = 0;
1010 ID initializer = 0;
1011 VariableID basevariable = 0;
1012
1013 SmallVector<uint32_t> dereference_chain;
1014 bool compat_builtin = false;
1015
1016 // If a variable is shadowed, we only statically assign to it
1017 // and never actually emit a statement for it.
1018 // When we read the variable as an expression, just forward
1019 // shadowed_id as the expression.
1020 bool statically_assigned = false;
1021 ID static_expression = 0;
1022
1023 // Temporaries which can remain forwarded as long as this variable is not modified.
1024 SmallVector<ID> dependees;
1025 bool forwardable = true;
1026
1027 bool deferred_declaration = false;
1028 bool phi_variable = false;
1029
1030 // Used to deal with Phi variable flushes. See flush_phi().
1031 bool allocate_temporary_copy = false;
1032
1033 bool remapped_variable = false;
1034 uint32_t remapped_components = 0;
1035
1036 // The block which dominates all access to this variable.
1037 BlockID dominator = 0;
1038 // If true, this variable is a loop variable, when accessing the variable
1039 // outside a loop,
1040 // we should statically forward it.
1041 bool loop_variable = false;
1042 // Set to true while we're inside the for loop.
1043 bool loop_variable_enable = false;
1044
1045 SPIRFunction::Parameter *parameter = nullptr;
1046
1047 SPIRV_CROSS_DECLARE_CLONE(SPIRVariable)
1048 };
1049
1050 struct SPIRConstant : IVariant
1051 {
1052 enum
1053 {
1054 type = TypeConstant
1055 };
1056
1057 union Constant
1058 {
1059 uint32_t u32;
1060 int32_t i32;
1061 float f32;
1062
1063 uint64_t u64;
1064 int64_t i64;
1065 double f64;
1066 };
1067
1068 struct ConstantVector
1069 {
1070 Constant r[4];
1071 // If != 0, this element is a specialization constant, and we should keep track of it as such.
1072 ID id[4];
1073 uint32_t vecsize = 1;
1074
1075 ConstantVector()
1076 {
1077 memset(r, 0, sizeof(r));
1078 }
1079 };
1080
1081 struct ConstantMatrix
1082 {
1083 ConstantVector c[4];
1084 // If != 0, this column is a specialization constant, and we should keep track of it as such.
1085 ID id[4];
1086 uint32_t columns = 1;
1087 };
1088
1089 static inline float f16_to_f32(uint16_t u16_value)
1090 {
1091 // Based on the GLM implementation.
1092 int s = (u16_value >> 15) & 0x1;
1093 int e = (u16_value >> 10) & 0x1f;
1094 int m = (u16_value >> 0) & 0x3ff;
1095
1096 union
1097 {
1098 float f32;
1099 uint32_t u32;
1100 } u;
1101
1102 if (e == 0)
1103 {
1104 if (m == 0)
1105 {
1106 u.u32 = uint32_t(s) << 31;
1107 return u.f32;
1108 }
1109 else
1110 {
1111 while ((m & 0x400) == 0)
1112 {
1113 m <<= 1;
1114 e--;
1115 }
1116
1117 e++;
1118 m &= ~0x400;
1119 }
1120 }
1121 else if (e == 31)
1122 {
1123 if (m == 0)
1124 {
1125 u.u32 = (uint32_t(s) << 31) | 0x7f800000u;
1126 return u.f32;
1127 }
1128 else
1129 {
1130 u.u32 = (uint32_t(s) << 31) | 0x7f800000u | (m << 13);
1131 return u.f32;
1132 }
1133 }
1134
1135 e += 127 - 15;
1136 m <<= 13;
1137 u.u32 = (uint32_t(s) << 31) | (e << 23) | m;
1138 return u.f32;
1139 }
1140
1141 inline uint32_t specialization_constant_id(uint32_t col, uint32_t row) const
1142 {
1143 return m.c[col].id[row];
1144 }
1145
1146 inline uint32_t specialization_constant_id(uint32_t col) const
1147 {
1148 return m.id[col];
1149 }
1150
1151 inline uint32_t scalar(uint32_t col = 0, uint32_t row = 0) const
1152 {
1153 return m.c[col].r[row].u32;
1154 }
1155
1156 inline int16_t scalar_i16(uint32_t col = 0, uint32_t row = 0) const
1157 {
1158 return int16_t(m.c[col].r[row].u32 & 0xffffu);
1159 }
1160
1161 inline uint16_t scalar_u16(uint32_t col = 0, uint32_t row = 0) const
1162 {
1163 return uint16_t(m.c[col].r[row].u32 & 0xffffu);
1164 }
1165
1166 inline int8_t scalar_i8(uint32_t col = 0, uint32_t row = 0) const
1167 {
1168 return int8_t(m.c[col].r[row].u32 & 0xffu);
1169 }
1170
1171 inline uint8_t scalar_u8(uint32_t col = 0, uint32_t row = 0) const
1172 {
1173 return uint8_t(m.c[col].r[row].u32 & 0xffu);
1174 }
1175
1176 inline float scalar_f16(uint32_t col = 0, uint32_t row = 0) const
1177 {
1178 return f16_to_f32(scalar_u16(col, row));
1179 }
1180
1181 inline float scalar_f32(uint32_t col = 0, uint32_t row = 0) const
1182 {
1183 return m.c[col].r[row].f32;
1184 }
1185
1186 inline int32_t scalar_i32(uint32_t col = 0, uint32_t row = 0) const
1187 {
1188 return m.c[col].r[row].i32;
1189 }
1190
1191 inline double scalar_f64(uint32_t col = 0, uint32_t row = 0) const
1192 {
1193 return m.c[col].r[row].f64;
1194 }
1195
1196 inline int64_t scalar_i64(uint32_t col = 0, uint32_t row = 0) const
1197 {
1198 return m.c[col].r[row].i64;
1199 }
1200
1201 inline uint64_t scalar_u64(uint32_t col = 0, uint32_t row = 0) const
1202 {
1203 return m.c[col].r[row].u64;
1204 }
1205
1206 inline const ConstantVector &vector() const
1207 {
1208 return m.c[0];
1209 }
1210
1211 inline uint32_t vector_size() const
1212 {
1213 return m.c[0].vecsize;
1214 }
1215
1216 inline uint32_t columns() const
1217 {
1218 return m.columns;
1219 }
1220
1221 inline void make_null(const SPIRType &constant_type_)
1222 {
1223 m = {};
1224 m.columns = constant_type_.columns;
1225 for (auto &c : m.c)
1226 c.vecsize = constant_type_.vecsize;
1227 }
1228
1229 inline bool constant_is_null() const
1230 {
1231 if (specialization)
1232 return false;
1233 if (!subconstants.empty())
1234 return false;
1235
1236 for (uint32_t col = 0; col < columns(); col++)
1237 for (uint32_t row = 0; row < vector_size(); row++)
1238 if (scalar_u64(col, row) != 0)
1239 return false;
1240
1241 return true;
1242 }
1243
1244 explicit SPIRConstant(uint32_t constant_type_)
1245 : constant_type(constant_type_)
1246 {
1247 }
1248
1249 SPIRConstant() = default;
1250
1251 SPIRConstant(TypeID constant_type_, const uint32_t *elements, uint32_t num_elements, bool specialized)
1252 : constant_type(constant_type_)
1253 , specialization(specialized)
1254 {
1255 subconstants.reserve(num_elements);
1256 for (uint32_t i = 0; i < num_elements; i++)
1257 subconstants.push_back(elements[i]);
1258 specialization = specialized;
1259 }
1260
1261 // Construct scalar (32-bit).
1262 SPIRConstant(TypeID constant_type_, uint32_t v0, bool specialized)
1263 : constant_type(constant_type_)
1264 , specialization(specialized)
1265 {
1266 m.c[0].r[0].u32 = v0;
1267 m.c[0].vecsize = 1;
1268 m.columns = 1;
1269 }
1270
1271 // Construct scalar (64-bit).
1272 SPIRConstant(TypeID constant_type_, uint64_t v0, bool specialized)
1273 : constant_type(constant_type_)
1274 , specialization(specialized)
1275 {
1276 m.c[0].r[0].u64 = v0;
1277 m.c[0].vecsize = 1;
1278 m.columns = 1;
1279 }
1280
1281 // Construct vectors and matrices.
1282 SPIRConstant(TypeID constant_type_, const SPIRConstant *const *vector_elements, uint32_t num_elements,
1283 bool specialized)
1284 : constant_type(constant_type_)
1285 , specialization(specialized)
1286 {
1287 bool matrix = vector_elements[0]->m.c[0].vecsize > 1;
1288
1289 if (matrix)
1290 {
1291 m.columns = num_elements;
1292
1293 for (uint32_t i = 0; i < num_elements; i++)
1294 {
1295 m.c[i] = vector_elements[i]->m.c[0];
1296 if (vector_elements[i]->specialization)
1297 m.id[i] = vector_elements[i]->self;
1298 }
1299 }
1300 else
1301 {
1302 m.c[0].vecsize = num_elements;
1303 m.columns = 1;
1304
1305 for (uint32_t i = 0; i < num_elements; i++)
1306 {
1307 m.c[0].r[i] = vector_elements[i]->m.c[0].r[0];
1308 if (vector_elements[i]->specialization)
1309 m.c[0].id[i] = vector_elements[i]->self;
1310 }
1311 }
1312 }
1313
1314 TypeID constant_type = 0;
1315 ConstantMatrix m;
1316
1317 // If this constant is a specialization constant (i.e. created with OpSpecConstant*).
1318 bool specialization = false;
1319 // If this constant is used as an array length which creates specialization restrictions on some backends.
1320 bool is_used_as_array_length = false;
1321
1322 // If true, this is a LUT, and should always be declared in the outer scope.
1323 bool is_used_as_lut = false;
1324
1325 // For composites which are constant arrays, etc.
1326 SmallVector<ConstantID> subconstants;
1327
1328 // Non-Vulkan GLSL, HLSL and sometimes MSL emits defines for each specialization constant,
1329 // and uses them to initialize the constant. This allows the user
1330 // to still be able to specialize the value by supplying corresponding
1331 // preprocessor directives before compiling the shader.
1332 std::string specialization_constant_macro_name;
1333
1334 SPIRV_CROSS_DECLARE_CLONE(SPIRConstant)
1335 };
1336
1337 // Variants have a very specific allocation scheme.
1338 struct ObjectPoolGroup
1339 {
1340 std::unique_ptr<ObjectPoolBase> pools[TypeCount];
1341 };
1342
1343 class Variant
1344 {
1345 public:
1346 explicit Variant(ObjectPoolGroup *group_)
1347 : group(group_)
1348 {
1349 }
1350
1351 ~Variant()
1352 {
1353 if (holder)
1354 group->pools[type]->free_opaque(holder);
1355 }
1356
1357 // Marking custom move constructor as noexcept is important.
1358 Variant(Variant &&other) SPIRV_CROSS_NOEXCEPT
1359 {
1360 *this = std::move(other);
1361 }
1362
1363 // We cannot copy from other variant without our own pool group.
1364 // Have to explicitly copy.
1365 Variant(const Variant &variant) = delete;
1366
1367 // Marking custom move constructor as noexcept is important.
1368 Variant &operator=(Variant &&other) SPIRV_CROSS_NOEXCEPT
1369 {
1370 if (this != &other)
1371 {
1372 if (holder)
1373 group->pools[type]->free_opaque(holder);
1374 holder = other.holder;
1375 group = other.group;
1376 type = other.type;
1377 allow_type_rewrite = other.allow_type_rewrite;
1378
1379 other.holder = nullptr;
1380 other.type = TypeNone;
1381 }
1382 return *this;
1383 }
1384
1385 // This copy/clone should only be called in the Compiler constructor.
1386 // If this is called inside ::compile(), we invalidate any references we took higher in the stack.
1387 // This should never happen.
1388 Variant &operator=(const Variant &other)
1389 {
1390 //#define SPIRV_CROSS_COPY_CONSTRUCTOR_SANITIZE
1391 #ifdef SPIRV_CROSS_COPY_CONSTRUCTOR_SANITIZE
1392 abort();
1393 #endif
1394 if (this != &other)
1395 {
1396 if (holder)
1397 group->pools[type]->free_opaque(holder);
1398
1399 if (other.holder)
1400 holder = other.holder->clone(group->pools[other.type].get());
1401 else
1402 holder = nullptr;
1403
1404 type = other.type;
1405 allow_type_rewrite = other.allow_type_rewrite;
1406 }
1407 return *this;
1408 }
1409
1410 void set(IVariant *val, Types new_type)
1411 {
1412 if (holder)
1413 group->pools[type]->free_opaque(holder);
1414 holder = nullptr;
1415
1416 if (!allow_type_rewrite && type != TypeNone && type != new_type)
1417 {
1418 if (val)
1419 group->pools[new_type]->free_opaque(val);
1420 SPIRV_CROSS_THROW("Overwriting a variant with new type.");
1421 }
1422
1423 holder = val;
1424 type = new_type;
1425 allow_type_rewrite = false;
1426 }
1427
1428 template <typename T, typename... Ts>
1429 T *allocate_and_set(Types new_type, Ts &&... ts)
1430 {
1431 T *val = static_cast<ObjectPool<T> &>(*group->pools[new_type]).allocate(std::forward<Ts>(ts)...);
1432 set(val, new_type);
1433 return val;
1434 }
1435
1436 template <typename T>
1437 T &get()
1438 {
1439 if (!holder)
1440 SPIRV_CROSS_THROW("nullptr");
1441 if (static_cast<Types>(T::type) != type)
1442 SPIRV_CROSS_THROW("Bad cast");
1443 return *static_cast<T *>(holder);
1444 }
1445
1446 template <typename T>
1447 const T &get() const
1448 {
1449 if (!holder)
1450 SPIRV_CROSS_THROW("nullptr");
1451 if (static_cast<Types>(T::type) != type)
1452 SPIRV_CROSS_THROW("Bad cast");
1453 return *static_cast<const T *>(holder);
1454 }
1455
1456 Types get_type() const
1457 {
1458 return type;
1459 }
1460
1461 ID get_id() const
1462 {
1463 return holder ? holder->self : ID(0);
1464 }
1465
1466 bool empty() const
1467 {
1468 return !holder;
1469 }
1470
1471 void reset()
1472 {
1473 if (holder)
1474 group->pools[type]->free_opaque(holder);
1475 holder = nullptr;
1476 type = TypeNone;
1477 }
1478
1479 void set_allow_type_rewrite()
1480 {
1481 allow_type_rewrite = true;
1482 }
1483
1484 private:
1485 ObjectPoolGroup *group = nullptr;
1486 IVariant *holder = nullptr;
1487 Types type = TypeNone;
1488 bool allow_type_rewrite = false;
1489 };
1490
1491 template <typename T>
1492 T &variant_get(Variant &var)
1493 {
1494 return var.get<T>();
1495 }
1496
1497 template <typename T>
1498 const T &variant_get(const Variant &var)
1499 {
1500 return var.get<T>();
1501 }
1502
1503 template <typename T, typename... P>
1504 T &variant_set(Variant &var, P &&... args)
1505 {
1506 auto *ptr = var.allocate_and_set<T>(static_cast<Types>(T::type), std::forward<P>(args)...);
1507 return *ptr;
1508 }
1509
1510 struct AccessChainMeta
1511 {
1512 uint32_t storage_physical_type = 0;
1513 bool need_transpose = false;
1514 bool storage_is_packed = false;
1515 bool storage_is_invariant = false;
1516 bool flattened_struct = false;
1517 };
1518
1519 enum ExtendedDecorations
1520 {
1521 // Marks if a buffer block is re-packed, i.e. member declaration might be subject to PhysicalTypeID remapping and padding.
1522 SPIRVCrossDecorationBufferBlockRepacked = 0,
1523
1524 // A type in a buffer block might be declared with a different physical type than the logical type.
1525 // If this is not set, PhysicalTypeID == the SPIR-V type as declared.
1526 SPIRVCrossDecorationPhysicalTypeID,
1527
1528 // Marks if the physical type is to be declared with tight packing rules, i.e. packed_floatN on MSL and friends.
1529 // If this is set, PhysicalTypeID might also be set. It can be set to same as logical type if all we're doing
1530 // is converting float3 to packed_float3 for example.
1531 // If this is marked on a struct, it means the struct itself must use only Packed types for all its members.
1532 SPIRVCrossDecorationPhysicalTypePacked,
1533
1534 // The padding in bytes before declaring this struct member.
1535 // If used on a struct type, marks the target size of a struct.
1536 SPIRVCrossDecorationPaddingTarget,
1537
1538 SPIRVCrossDecorationInterfaceMemberIndex,
1539 SPIRVCrossDecorationInterfaceOrigID,
1540 SPIRVCrossDecorationResourceIndexPrimary,
1541 // Used for decorations like resource indices for samplers when part of combined image samplers.
1542 // A variable might need to hold two resource indices in this case.
1543 SPIRVCrossDecorationResourceIndexSecondary,
1544 // Used for resource indices for multiplanar images when part of combined image samplers.
1545 SPIRVCrossDecorationResourceIndexTertiary,
1546 SPIRVCrossDecorationResourceIndexQuaternary,
1547
1548 // Marks a buffer block for using explicit offsets (GLSL/HLSL).
1549 SPIRVCrossDecorationExplicitOffset,
1550
1551 // Apply to a variable in the Input storage class; marks it as holding the base group passed to vkCmdDispatchBase(),
1552 // or the base vertex and instance indices passed to vkCmdDrawIndexed().
1553 // In MSL, this is used to adjust the WorkgroupId and GlobalInvocationId variables in compute shaders,
1554 // and to hold the BaseVertex and BaseInstance variables in vertex shaders.
1555 SPIRVCrossDecorationBuiltInDispatchBase,
1556
1557 // Apply to a variable that is a function parameter; marks it as being a "dynamic"
1558 // combined image-sampler. In MSL, this is used when a function parameter might hold
1559 // either a regular combined image-sampler or one that has an attached sampler
1560 // Y'CbCr conversion.
1561 SPIRVCrossDecorationDynamicImageSampler,
1562
1563 // Apply to a variable in the Input storage class; marks it as holding the size of the stage
1564 // input grid.
1565 // In MSL, this is used to hold the vertex and instance counts in a tessellation pipeline
1566 // vertex shader.
1567 SPIRVCrossDecorationBuiltInStageInputSize,
1568
1569 // Apply to any access chain of a tessellation I/O variable; stores the type of the sub-object
1570 // that was chained to, as recorded in the input variable itself. This is used in case the pointer
1571 // is itself used as the base of an access chain, to calculate the original type of the sub-object
1572 // chained to, in case a swizzle needs to be applied. This should not happen normally with valid
1573 // SPIR-V, but the MSL backend can change the type of input variables, necessitating the
1574 // addition of swizzles to keep the generated code compiling.
1575 SPIRVCrossDecorationTessIOOriginalInputTypeID,
1576
1577 // Apply to any access chain of an interface variable used with pull-model interpolation, where the variable is a
1578 // vector but the resulting pointer is a scalar; stores the component index that is to be accessed by the chain.
1579 // This is used when emitting calls to interpolation functions on the chain in MSL: in this case, the component
1580 // must be applied to the result, since pull-model interpolants in MSL cannot be swizzled directly, but the
1581 // results of interpolation can.
1582 SPIRVCrossDecorationInterpolantComponentExpr,
1583
1584 SPIRVCrossDecorationCount
1585 };
1586
1587 struct Meta
1588 {
1589 struct Decoration
1590 {
1591 std::string alias;
1592 std::string qualified_alias;
1593 std::string hlsl_semantic;
1594 Bitset decoration_flags;
1595 spv::BuiltIn builtin_type = spv::BuiltInMax;
1596 uint32_t location = 0;
1597 uint32_t component = 0;
1598 uint32_t set = 0;
1599 uint32_t binding = 0;
1600 uint32_t offset = 0;
1601 uint32_t xfb_buffer = 0;
1602 uint32_t xfb_stride = 0;
1603 uint32_t stream = 0;
1604 uint32_t array_stride = 0;
1605 uint32_t matrix_stride = 0;
1606 uint32_t input_attachment = 0;
1607 uint32_t spec_id = 0;
1608 uint32_t index = 0;
1609 spv::FPRoundingMode fp_rounding_mode = spv::FPRoundingModeMax;
1610 bool builtin = false;
1611
1612 struct Extended
1613 {
1614 Extended()
1615 {
1616 // MSVC 2013 workaround to init like this.
1617 for (auto &v : values)
1618 v = 0;
1619 }
1620
1621 Bitset flags;
1622 uint32_t values[SPIRVCrossDecorationCount];
1623 } extended;
1624 };
1625
1626 Decoration decoration;
1627
1628 // Intentionally not a SmallVector. Decoration is large and somewhat rare.
1629 Vector<Decoration> members;
1630
1631 std::unordered_map<uint32_t, uint32_t> decoration_word_offset;
1632
1633 // For SPV_GOOGLE_hlsl_functionality1.
1634 bool hlsl_is_magic_counter_buffer = false;
1635 // ID for the sibling counter buffer.
1636 uint32_t hlsl_magic_counter_buffer = 0;
1637 };
1638
1639 // A user callback that remaps the type of any variable.
1640 // var_name is the declared name of the variable.
1641 // name_of_type is the textual name of the type which will be used in the code unless written to by the callback.
1642 using VariableTypeRemapCallback =
1643 std::function<void(const SPIRType &type, const std::string &var_name, std::string &name_of_type)>;
1644
1645 class Hasher
1646 {
1647 public:
1648 inline void u32(uint32_t value)
1649 {
1650 h = (h * 0x100000001b3ull) ^ value;
1651 }
1652
1653 inline uint64_t get() const
1654 {
1655 return h;
1656 }
1657
1658 private:
1659 uint64_t h = 0xcbf29ce484222325ull;
1660 };
1661
1662 static inline bool type_is_floating_point(const SPIRType &type)
1663 {
1664 return type.basetype == SPIRType::Half || type.basetype == SPIRType::Float || type.basetype == SPIRType::Double;
1665 }
1666
1667 static inline bool type_is_integral(const SPIRType &type)
1668 {
1669 return type.basetype == SPIRType::SByte || type.basetype == SPIRType::UByte || type.basetype == SPIRType::Short ||
1670 type.basetype == SPIRType::UShort || type.basetype == SPIRType::Int || type.basetype == SPIRType::UInt ||
1671 type.basetype == SPIRType::Int64 || type.basetype == SPIRType::UInt64;
1672 }
1673
1674 static inline SPIRType::BaseType to_signed_basetype(uint32_t width)
1675 {
1676 switch (width)
1677 {
1678 case 8:
1679 return SPIRType::SByte;
1680 case 16:
1681 return SPIRType::Short;
1682 case 32:
1683 return SPIRType::Int;
1684 case 64:
1685 return SPIRType::Int64;
1686 default:
1687 SPIRV_CROSS_THROW("Invalid bit width.");
1688 }
1689 }
1690
1691 static inline SPIRType::BaseType to_unsigned_basetype(uint32_t width)
1692 {
1693 switch (width)
1694 {
1695 case 8:
1696 return SPIRType::UByte;
1697 case 16:
1698 return SPIRType::UShort;
1699 case 32:
1700 return SPIRType::UInt;
1701 case 64:
1702 return SPIRType::UInt64;
1703 default:
1704 SPIRV_CROSS_THROW("Invalid bit width.");
1705 }
1706 }
1707
1708 // Returns true if an arithmetic operation does not change behavior depending on signedness.
1709 static inline bool opcode_is_sign_invariant(spv::Op opcode)
1710 {
1711 switch (opcode)
1712 {
1713 case spv::OpIEqual:
1714 case spv::OpINotEqual:
1715 case spv::OpISub:
1716 case spv::OpIAdd:
1717 case spv::OpIMul:
1718 case spv::OpShiftLeftLogical:
1719 case spv::OpBitwiseOr:
1720 case spv::OpBitwiseXor:
1721 case spv::OpBitwiseAnd:
1722 return true;
1723
1724 default:
1725 return false;
1726 }
1727 }
1728
1729 struct SetBindingPair
1730 {
1731 uint32_t desc_set;
1732 uint32_t binding;
1733
1734 inline bool operator==(const SetBindingPair &other) const
1735 {
1736 return desc_set == other.desc_set && binding == other.binding;
1737 }
1738
1739 inline bool operator<(const SetBindingPair &other) const
1740 {
1741 return desc_set < other.desc_set || (desc_set == other.desc_set && binding < other.binding);
1742 }
1743 };
1744
1745 struct StageSetBinding
1746 {
1747 spv::ExecutionModel model;
1748 uint32_t desc_set;
1749 uint32_t binding;
1750
1751 inline bool operator==(const StageSetBinding &other) const
1752 {
1753 return model == other.model && desc_set == other.desc_set && binding == other.binding;
1754 }
1755 };
1756
1757 struct InternalHasher
1758 {
1759 inline size_t operator()(const SetBindingPair &value) const
1760 {
1761 // Quality of hash doesn't really matter here.
1762 auto hash_set = std::hash<uint32_t>()(value.desc_set);
1763 auto hash_binding = std::hash<uint32_t>()(value.binding);
1764 return (hash_set * 0x10001b31) ^ hash_binding;
1765 }
1766
1767 inline size_t operator()(const StageSetBinding &value) const
1768 {
1769 // Quality of hash doesn't really matter here.
1770 auto hash_model = std::hash<uint32_t>()(value.model);
1771 auto hash_set = std::hash<uint32_t>()(value.desc_set);
1772 auto tmp_hash = (hash_model * 0x10001b31) ^ hash_set;
1773 return (tmp_hash * 0x10001b31) ^ value.binding;
1774 }
1775 };
1776
1777 // Special constant used in a {MSL,HLSL}ResourceBinding desc_set
1778 // element to indicate the bindings for the push constants.
1779 static const uint32_t ResourceBindingPushConstantDescriptorSet = ~(0u);
1780
1781 // Special constant used in a {MSL,HLSL}ResourceBinding binding
1782 // element to indicate the bindings for the push constants.
1783 static const uint32_t ResourceBindingPushConstantBinding = 0;
1784 } // namespace SPIRV_CROSS_NAMESPACE
1785
1786 namespace std
1787 {
1788 template <SPIRV_CROSS_NAMESPACE::Types type>
1789 struct hash<SPIRV_CROSS_NAMESPACE::TypedID<type>>
1790 {
1791 size_t operator()(const SPIRV_CROSS_NAMESPACE::TypedID<type> &value) const
1792 {
1793 return std::hash<uint32_t>()(value);
1794 }
1795 };
1796 } // namespace std
1797
1798 #endif