Debian Codegraph @

src/sksl/ir/SkSLType.cpp

raw
1 /*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/sksl/ir/SkSLType.h"
9
10 #include "include/private/base/SkTo.h"
11 #include "src/base/SkEnumBitMask.h"
12 #include "src/base/SkHalf.h"
13 #include "src/base/SkMathPriv.h"
14 #include "src/base/SkSafeMath.h"
15 #include "src/core/SkTHash.h"
16 #include "src/sksl/SkSLBuiltinTypes.h"
17 #include "src/sksl/SkSLConstantFolder.h"
18 #include "src/sksl/SkSLContext.h"
19 #include "src/sksl/SkSLErrorReporter.h"
20 #include "src/sksl/SkSLProgramSettings.h"
21 #include "src/sksl/SkSLString.h"
22 #include "src/sksl/ir/SkSLConstructorArrayCast.h"
23 #include "src/sksl/ir/SkSLConstructorCompoundCast.h"
24 #include "src/sksl/ir/SkSLConstructorScalarCast.h"
25 #include "src/sksl/ir/SkSLExpression.h"
26 #include "src/sksl/ir/SkSLLayout.h"
27 #include "src/sksl/ir/SkSLModifierFlags.h"
28 #include "src/sksl/ir/SkSLSymbolTable.h"
29
30 #include <algorithm>
31 #include <cstdint>
32 #include <limits>
33 #include <optional>
34 #include <string_view>
35 #include <utility>
36
37 using namespace skia_private;
38
39 namespace SkSL {
40
41 static constexpr int kMaxStructDepth = 8;
42
43 class AliasType final : public Type {
44 public:
45 AliasType(std::string_view name, const Type& targetType)
46 : INHERITED(name, targetType.abbreviatedName(), targetType.typeKind())
47 , fTargetType(targetType) {}
48
49 const Type& resolve() const override {
50 return fTargetType;
51 }
52
53 const Type& componentType() const override {
54 return fTargetType.componentType();
55 }
56
57 NumberKind numberKind() const override {
58 return fTargetType.numberKind();
59 }
60
61 int priority() const override {
62 return fTargetType.priority();
63 }
64
65 int columns() const override {
66 return fTargetType.columns();
67 }
68
69 int rows() const override {
70 return fTargetType.rows();
71 }
72
73 int bitWidth() const override {
74 return fTargetType.bitWidth();
75 }
76
77 bool isAllowedInES2() const override {
78 return fTargetType.isAllowedInES2();
79 }
80
81 bool isOrContainsBool() const override {
82 return fTargetType.isOrContainsBool();
83 }
84
85 bool isOrContainsAtomic() const override {
86 return fTargetType.isOrContainsAtomic();
87 }
88
89 size_t slotCount() const override {
90 return fTargetType.slotCount();
91 }
92
93 const Type& slotType(size_t n) const override {
94 return fTargetType.slotType(n);
95 }
96
97 SpvDim_ dimensions() const override {
98 return fTargetType.dimensions();
99 }
100
101 bool isDepth() const override {
102 return fTargetType.isDepth();
103 }
104
105 bool isArrayedTexture() const override {
106 return fTargetType.isArrayedTexture();
107 }
108
109 bool isScalar() const override {
110 return fTargetType.isScalar();
111 }
112
113 bool isLiteral() const override {
114 return fTargetType.isLiteral();
115 }
116
117 bool isVector() const override {
118 return fTargetType.isVector();
119 }
120
121 bool isMatrix() const override {
122 return fTargetType.isMatrix();
123 }
124
125 bool isArray() const override {
126 return fTargetType.isArray();
127 }
128
129 bool isUnsizedArray() const override {
130 return fTargetType.isUnsizedArray();
131 }
132
133 bool isStruct() const override {
134 return fTargetType.isStruct();
135 }
136
137 bool isInterfaceBlock() const override {
138 return fTargetType.isInterfaceBlock();
139 }
140
141 bool isMultisampled() const override {
142 return fTargetType.isMultisampled();
143 }
144
145 TextureAccess textureAccess() const override {
146 return fTargetType.textureAccess();
147 }
148
149 SkSpan<const Type* const> coercibleTypes() const override {
150 return fTargetType.coercibleTypes();
151 }
152
153 private:
154 using INHERITED = Type;
155
156 const Type& fTargetType;
157 };
158
159 class ArrayType final : public Type {
160 public:
161 inline static constexpr TypeKind kTypeKind = TypeKind::kArray;
162
163 ArrayType(std::string_view name, const char* abbrev, const Type& componentType, int count,
164 bool isBuiltin)
165 : INHERITED(name, abbrev, kTypeKind)
166 , fComponentType(componentType)
167 , fCount(count)
168 , fIsBuiltin(isBuiltin) {
169 SkASSERT(count > 0 || count == kUnsizedArray);
170 // Multi-dimensional arrays are disallowed.
171 SkASSERT(!componentType.is<ArrayType>());
172 }
173
174 bool matches(const Type& otherType) const override {
175 const Type& that = otherType.resolve();
176 return that.isArray() && this->columns() == that.columns() &&
177 this->componentType().matches(that.componentType());
178 }
179
180 bool isArray() const override {
181 return true;
182 }
183
184 bool isBuiltin() const override {
185 return fIsBuiltin;
186 }
187
188 bool isOrContainsArray() const override {
189 return true;
190 }
191
192 bool isOrContainsAtomic() const override {
193 return fComponentType.isOrContainsAtomic();
194 }
195
196 bool isOrContainsBool() const override {
197 return fComponentType.isOrContainsBool();
198 }
199
200 bool isUnsizedArray() const override {
201 return fCount == kUnsizedArray;
202 }
203
204 bool isOrContainsUnsizedArray() const override {
205 return this->isUnsizedArray() || fComponentType.isOrContainsUnsizedArray();
206 }
207
208 const Type& componentType() const override {
209 return fComponentType;
210 }
211
212 int columns() const override {
213 return fCount;
214 }
215
216 int bitWidth() const override {
217 return fComponentType.bitWidth();
218 }
219
220 bool isAllowedInES2() const override {
221 return fComponentType.isAllowedInES2();
222 }
223
224 bool isAllowedInUniform(Position* errorPosition) const override {
225 return fComponentType.isAllowedInUniform(errorPosition);
226 }
227
228 size_t slotCount() const override {
229 SkASSERT(fCount != kUnsizedArray);
230 SkASSERT(fCount > 0);
231 return fCount * fComponentType.slotCount();
232 }
233
234 const Type& slotType(size_t n) const override {
235 SkASSERT(fCount == kUnsizedArray || n < this->slotCount());
236 return fComponentType.slotType(n % fComponentType.slotCount());
237 }
238
239 private:
240 using INHERITED = Type;
241
242 const Type& fComponentType;
243 int fCount;
244 bool fIsBuiltin;
245 };
246
247 class GenericType final : public Type {
248 public:
249 inline static constexpr TypeKind kTypeKind = TypeKind::kGeneric;
250
251 GenericType(const char* name, SkSpan<const Type* const> coercibleTypes, const Type* slotType)
252 : INHERITED(name, "G", kTypeKind)
253 , fSlotType(slotType) {
254 fNumTypes = coercibleTypes.size();
255 SkASSERT(fNumTypes <= std::size(fCoercibleTypes));
256 std::copy(coercibleTypes.begin(), coercibleTypes.end(), fCoercibleTypes);
257 }
258
259 SkSpan<const Type* const> coercibleTypes() const override {
260 return SkSpan(fCoercibleTypes, fNumTypes);
261 }
262
263 const Type& slotType(size_t) const override {
264 return *fSlotType;
265 }
266
267 private:
268 using INHERITED = Type;
269
270 const Type* fCoercibleTypes[9];
271 const Type* fSlotType;
272 size_t fNumTypes;
273 };
274
275 class LiteralType : public Type {
276 public:
277 inline static constexpr TypeKind kTypeKind = TypeKind::kLiteral;
278
279 LiteralType(const char* name, const Type& scalarType, int8_t priority)
280 : INHERITED(name, "L", kTypeKind)
281 , fScalarType(scalarType)
282 , fPriority(priority) {}
283
284 const Type& scalarTypeForLiteral() const override {
285 return fScalarType;
286 }
287
288 int priority() const override {
289 return fPriority;
290 }
291
292 int columns() const override {
293 return 1;
294 }
295
296 int rows() const override {
297 return 1;
298 }
299
300 NumberKind numberKind() const override {
301 return fScalarType.numberKind();
302 }
303
304 int bitWidth() const override {
305 return fScalarType.bitWidth();
306 }
307
308 double minimumValue() const override {
309 return fScalarType.minimumValue();
310 }
311
312 double maximumValue() const override {
313 return fScalarType.maximumValue();
314 }
315
316 bool isScalar() const override {
317 return true;
318 }
319
320 bool isLiteral() const override {
321 return true;
322 }
323
324 bool isOrContainsBool() const override {
325 return fScalarType.isBoolean();
326 }
327
328 size_t slotCount() const override {
329 return 1;
330 }
331
332 const Type& slotType(size_t n) const override {
333 SkASSERT(n == 0);
334 return fScalarType;
335 }
336
337 private:
338 using INHERITED = Type;
339
340 const Type& fScalarType;
341 int8_t fPriority;
342 };
343
344
345 class ScalarType final : public Type {
346 public:
347 inline static constexpr TypeKind kTypeKind = TypeKind::kScalar;
348
349 ScalarType(std::string_view name, const char* abbrev, NumberKind numberKind, int8_t priority,
350 int8_t bitWidth)
351 : INHERITED(name, abbrev, kTypeKind)
352 , fNumberKind(numberKind)
353 , fPriority(priority)
354 , fBitWidth(bitWidth) {}
355
356 NumberKind numberKind() const override {
357 return fNumberKind;
358 }
359
360 int priority() const override {
361 return fPriority;
362 }
363
364 int bitWidth() const override {
365 return fBitWidth;
366 }
367
368 int columns() const override {
369 return 1;
370 }
371
372 int rows() const override {
373 return 1;
374 }
375
376 bool isScalar() const override {
377 return true;
378 }
379
380 bool isAllowedInES2() const override {
381 return fNumberKind != NumberKind::kUnsigned;
382 }
383
384 bool isAllowedInUniform(Position*) const override {
385 return fNumberKind != NumberKind::kBoolean;
386 }
387
388 bool isOrContainsBool() const override {
389 return fNumberKind == NumberKind::kBoolean;
390 }
391
392 size_t slotCount() const override {
393 return 1;
394 }
395
396 const Type& slotType(size_t n) const override {
397 SkASSERT(n == 0);
398 return *this;
399 }
400
401 using int_limits = std::numeric_limits<int32_t>;
402 using short_limits = std::numeric_limits<int16_t>;
403 using uint_limits = std::numeric_limits<uint32_t>;
404 using ushort_limits = std::numeric_limits<uint16_t>;
405 using float_limits = std::numeric_limits<float>;
406
407 /** Returns the maximum value that can fit in the type. */
408 double minimumValue() const override {
409 switch (this->numberKind()) {
410 case NumberKind::kSigned:
411 return this->highPrecision() ? int_limits::lowest()
412 : short_limits::lowest();
413
414 case NumberKind::kUnsigned:
415 return 0;
416
417 case NumberKind::kFloat:
418 default:
419 return this->highPrecision() ? float_limits::lowest()
420 : -SkHalfToFloat(SK_HalfMax);
421 }
422 }
423
424 /** Returns the maximum value that can fit in the type. */
425 double maximumValue() const override {
426 switch (this->numberKind()) {
427 case NumberKind::kSigned:
428 return this->highPrecision() ? int_limits::max()
429 : short_limits::max();
430
431 case NumberKind::kUnsigned:
432 return this->highPrecision() ? uint_limits::max()
433 : ushort_limits::max();
434
435 case NumberKind::kFloat:
436 default:
437 return this->highPrecision() ? float_limits::max()
438 : SkHalfToFloat(SK_HalfMax);
439 }
440 }
441
442 private:
443 using INHERITED = Type;
444
445 NumberKind fNumberKind;
446 int8_t fPriority;
447 int8_t fBitWidth;
448 };
449
450 class AtomicType final : public Type {
451 public:
452 inline static constexpr TypeKind kTypeKind = TypeKind::kAtomic;
453
454 AtomicType(std::string_view name, const char* abbrev) : INHERITED(name, abbrev, kTypeKind) {}
455
456 bool isAllowedInES2() const override { return false; }
457
458 bool isAllowedInUniform(Position*) const override { return false; }
459
460 bool isOrContainsAtomic() const override { return true; }
461
462 const Type& slotType(size_t n) const override {
463 SkASSERT(n == 0);
464 return *this;
465 }
466
467 private:
468 using INHERITED = Type;
469 };
470
471 class MatrixType final : public Type {
472 public:
473 inline static constexpr TypeKind kTypeKind = TypeKind::kMatrix;
474
475 MatrixType(std::string_view name, const char* abbrev, const Type& componentType,
476 int8_t columns, int8_t rows)
477 : INHERITED(name, abbrev, kTypeKind)
478 , fComponentType(componentType.as<ScalarType>())
479 , fColumns(columns)
480 , fRows(rows) {
481 SkASSERT(columns >= 2 && columns <= 4);
482 SkASSERT(rows >= 2 && rows <= 4);
483 }
484
485 const ScalarType& componentType() const override {
486 return fComponentType;
487 }
488
489 int columns() const override {
490 return fColumns;
491 }
492
493 int rows() const override {
494 return fRows;
495 }
496
497 int bitWidth() const override {
498 return this->componentType().bitWidth();
499 }
500
501 bool isMatrix() const override {
502 return true;
503 }
504
505 bool isAllowedInES2() const override {
506 return fColumns == fRows;
507 }
508
509 size_t slotCount() const override {
510 return fColumns * fRows;
511 }
512
513 const Type& slotType(size_t n) const override {
514 SkASSERT(n < this->slotCount());
515 return fComponentType;
516 }
517
518 private:
519 using INHERITED = Type;
520
521 const ScalarType& fComponentType;
522 int8_t fColumns;
523 int8_t fRows;
524 };
525
526 class TextureType final : public Type {
527 public:
528 inline static constexpr TypeKind kTypeKind = TypeKind::kTexture;
529
530 TextureType(const char* name, SpvDim_ dimensions, bool isDepth, bool isArrayed,
531 bool isMultisampled, TextureAccess textureAccess)
532 : INHERITED(name, "T", kTypeKind)
533 , fDimensions(dimensions)
534 , fIsDepth(isDepth)
535 , fIsArrayed(isArrayed)
536 , fIsMultisampled(isMultisampled)
537 , fTextureAccess(textureAccess) {}
538
539 SpvDim_ dimensions() const override {
540 return fDimensions;
541 }
542
543 bool isDepth() const override {
544 return fIsDepth;
545 }
546
547 bool isArrayedTexture() const override {
548 return fIsArrayed;
549 }
550
551 bool isMultisampled() const override {
552 return fIsMultisampled;
553 }
554
555 TextureAccess textureAccess() const override {
556 return fTextureAccess;
557 }
558
559 const Type& slotType(size_t n) const override {
560 SkASSERT(n == 0);
561 return *this;
562 }
563
564 private:
565 using INHERITED = Type;
566
567 SpvDim_ fDimensions;
568 bool fIsDepth;
569 bool fIsArrayed;
570 bool fIsMultisampled;
571 TextureAccess fTextureAccess;
572 };
573
574 class SamplerType final : public Type {
575 public:
576 inline static constexpr TypeKind kTypeKind = TypeKind::kSampler;
577
578 SamplerType(const char* name, const Type& textureType)
579 : INHERITED(name, "Z", kTypeKind)
580 , fTextureType(textureType.as<TextureType>()) {
581 // Samplers require sampled texture access.
582 SkASSERT(this->textureAccess() == TextureAccess::kSample);
583 // Subpass inputs cannot be sampled.
584 SkASSERT(this->dimensions() != SpvDimSubpassData);
585 }
586
587 const TextureType& textureType() const override {
588 return fTextureType;
589 }
590
591 SpvDim_ dimensions() const override {
592 return fTextureType.dimensions();
593 }
594
595 bool isDepth() const override {
596 return fTextureType.isDepth();
597 }
598
599 bool isArrayedTexture() const override {
600 return fTextureType.isArrayedTexture();
601 }
602
603 bool isMultisampled() const override {
604 return fTextureType.isMultisampled();
605 }
606
607 TextureAccess textureAccess() const override {
608 return fTextureType.textureAccess();
609 }
610
611 const Type& slotType(size_t n) const override {
612 SkASSERT(n == 0);
613 return *this;
614 }
615
616 private:
617 using INHERITED = Type;
618
619 const TextureType& fTextureType;
620 };
621
622 class StructType final : public Type {
623 public:
624 inline static constexpr TypeKind kTypeKind = TypeKind::kStruct;
625
626 StructType(Position pos, std::string_view name, TArray<Field> fields, int nestingDepth,
627 bool interfaceBlock, bool isBuiltin)
628 : INHERITED(std::move(name), "S", kTypeKind, pos)
629 , fFields(std::move(fields))
630 , fNestingDepth(nestingDepth)
631 , fInterfaceBlock(interfaceBlock)
632 , fIsBuiltin(isBuiltin) {
633 for (const Field& f : fFields) {
634 fContainsArray = fContainsArray || f.fType->isOrContainsArray();
635 fContainsUnsizedArray = fContainsUnsizedArray || f.fType->isOrContainsUnsizedArray();
636 fContainsAtomic = fContainsAtomic || f.fType->isOrContainsAtomic();
637 fContainsBool = fContainsBool || f.fType->isOrContainsBool();
638 fIsAllowedInES2 = fIsAllowedInES2 && f.fType->isAllowedInES2();
639 }
640 for (const Field& f : fFields) {
641 Position errorPosition = f.fPosition;
642 if (!f.fType->isAllowedInUniform(&errorPosition)) {
643 fUniformErrorPosition = errorPosition;
644 break;
645 }
646 }
647 if (!fContainsUnsizedArray) {
648 for (const Field& f : fFields) {
649 fSlotCount += f.fType->slotCount();
650 }
651 }
652 }
653
654 SkSpan<const Field> fields() const override {
655 return fFields;
656 }
657
658 bool isStruct() const override {
659 return true;
660 }
661
662 bool isInterfaceBlock() const override {
663 return fInterfaceBlock;
664 }
665
666 bool isBuiltin() const override {
667 return fIsBuiltin;
668 }
669
670 bool isAllowedInES2() const override {
671 return fIsAllowedInES2;
672 }
673
674 bool isAllowedInUniform(Position* errorPosition) const override {
675 if (errorPosition != nullptr) {
676 *errorPosition = fUniformErrorPosition;
677 }
678 return !fUniformErrorPosition.valid();
679 }
680
681 bool isOrContainsArray() const override {
682 return fContainsArray;
683 }
684
685 bool isOrContainsUnsizedArray() const override {
686 return fContainsUnsizedArray;
687 }
688
689 bool isOrContainsAtomic() const override {
690 return fContainsAtomic;
691 }
692
693 bool isOrContainsBool() const override {
694 return fContainsBool;
695 }
696
697 size_t slotCount() const override {
698 SkASSERT(!fContainsUnsizedArray);
699 return fSlotCount;
700 }
701
702 int structNestingDepth() const override {
703 return fNestingDepth;
704 }
705
706 const Type& slotType(size_t n) const override {
707 for (const Field& field : fFields) {
708 size_t fieldSlots = field.fType->slotCount();
709 if (n < fieldSlots) {
710 return field.fType->slotType(n);
711 } else {
712 n -= fieldSlots;
713 }
714 }
715 SkDEBUGFAIL("slot index out of range");
716 return *this;
717 }
718
719 private:
720 using INHERITED = Type;
721
722 TArray<Field> fFields;
723 size_t fSlotCount = 0;
724 int fNestingDepth = 0;
725 Position fUniformErrorPosition = {};
726 bool fInterfaceBlock = false;
727 bool fContainsArray = false;
728 bool fContainsUnsizedArray = false;
729 bool fContainsAtomic = false;
730 bool fContainsBool = false;
731 bool fIsBuiltin = false;
732 bool fIsAllowedInES2 = true;
733 };
734
735 class VectorType final : public Type {
736 public:
737 inline static constexpr TypeKind kTypeKind = TypeKind::kVector;
738
739 VectorType(std::string_view name, const char* abbrev, const Type& componentType,
740 int8_t columns)
741 : INHERITED(name, abbrev, kTypeKind)
742 , fComponentType(componentType.as<ScalarType>())
743 , fColumns(columns) {
744 SkASSERT(columns >= 2 && columns <= 4);
745 }
746
747 const ScalarType& componentType() const override {
748 return fComponentType;
749 }
750
751 int columns() const override {
752 return fColumns;
753 }
754
755 int rows() const override {
756 return 1;
757 }
758
759 int bitWidth() const override {
760 return this->componentType().bitWidth();
761 }
762
763 bool isVector() const override {
764 return true;
765 }
766
767 bool isAllowedInES2() const override {
768 return fComponentType.isAllowedInES2();
769 }
770
771 bool isAllowedInUniform(Position* errorPosition) const override {
772 return fComponentType.isAllowedInUniform(errorPosition);
773 }
774
775 bool isOrContainsBool() const override {
776 return fComponentType.isOrContainsBool();
777 }
778
779 size_t slotCount() const override {
780 return fColumns;
781 }
782
783 const Type& slotType(size_t n) const override {
784 SkASSERT(n < SkToSizeT(fColumns));
785 return fComponentType;
786 }
787
788 private:
789 using INHERITED = Type;
790
791 const ScalarType& fComponentType;
792 int8_t fColumns;
793 };
794
795 std::string Type::getArrayName(int arraySize) const {
796 std::string_view name = this->name();
797 if (arraySize == kUnsizedArray) {
798 return String::printf("%.*s[]", (int)name.size(), name.data());
799 }
800 return String::printf("%.*s[%d]", (int)name.size(), name.data(), arraySize);
801 }
802
803 std::unique_ptr<Type> Type::MakeAliasType(std::string_view name, const Type& targetType) {
804 return std::make_unique<AliasType>(std::move(name), targetType);
805 }
806
807 std::unique_ptr<Type> Type::MakeArrayType(const Context& context,
808 std::string_view name,
809 const Type& componentType,
810 int columns) {
811 return std::make_unique<ArrayType>(std::move(name), componentType.abbreviatedName(),
812 componentType, columns, context.fConfig->isBuiltinCode());
813 }
814
815 std::unique_ptr<Type> Type::MakeGenericType(const char* name,
816 SkSpan<const Type* const> types,
817 const Type* slotType) {
818 return std::make_unique<GenericType>(name, types, slotType);
819 }
820
821 std::unique_ptr<Type> Type::MakeLiteralType(const char* name, const Type& scalarType,
822 int8_t priority) {
823 return std::make_unique<LiteralType>(name, scalarType, priority);
824 }
825
826 std::unique_ptr<Type> Type::MakeMatrixType(std::string_view name, const char* abbrev,
827 const Type& componentType, int columns, int8_t rows) {
828 return std::make_unique<MatrixType>(name, abbrev, componentType, columns, rows);
829 }
830
831 std::unique_ptr<Type> Type::MakeSamplerType(const char* name, const Type& textureType) {
832 return std::make_unique<SamplerType>(name, textureType);
833 }
834
835 std::unique_ptr<Type> Type::MakeSpecialType(const char* name, const char* abbrev,
836 Type::TypeKind typeKind) {
837 return std::unique_ptr<Type>(new Type(name, abbrev, typeKind));
838 }
839
840 std::unique_ptr<Type> Type::MakeScalarType(std::string_view name, const char* abbrev,
841 Type::NumberKind numberKind, int8_t priority,
842 int8_t bitWidth) {
843 return std::make_unique<ScalarType>(name, abbrev, numberKind, priority, bitWidth);
844 }
845
846 std::unique_ptr<Type> Type::MakeAtomicType(std::string_view name, const char* abbrev) {
847 return std::make_unique<AtomicType>(name, abbrev);
848 }
849
850 std::unique_ptr<Type> Type::MakeStructType(const Context& context,
851 Position pos,
852 std::string_view name,
853 TArray<Field> fields,
854 bool interfaceBlock) {
855 const char* const structOrIB = interfaceBlock ? "interface block" : "struct";
856 const char* const aStructOrIB = interfaceBlock ? "an interface block" : "a struct";
857
858 if (fields.empty()) {
859 context.fErrors->error(pos, std::string(structOrIB) + " '" + std::string(name) +
860 "' must contain at least one field");
861 }
862 size_t slots = 0;
863
864 THashSet<std::string_view> fieldNames;
865 for (const Field& field : fields) {
866 // Add this field name to our set; if the set doesn't grow, we found a duplicate.
867 int numFieldNames = fieldNames.count();
868 fieldNames.add(field.fName);
869 if (fieldNames.count() == numFieldNames) {
870 context.fErrors->error(field.fPosition, "field '" + std::string(field.fName) +
871 "' was already defined in the same " +
872 std::string(structOrIB) + " ('" +
873 std::string(name) + "')");
874 }
875 if (field.fModifierFlags != ModifierFlag::kNone) {
876 std::string desc = field.fModifierFlags.description();
877 context.fErrors->error(field.fPosition, "modifier '" + desc + "' is not permitted on " +
878 std::string(aStructOrIB) + " field");
879 }
880 if (field.fLayout.fFlags & LayoutFlag::kBinding) {
881 context.fErrors->error(field.fPosition, "layout qualifier 'binding' is not permitted "
882 "on " + std::string(aStructOrIB) + " field");
883 }
884 if (field.fLayout.fFlags & LayoutFlag::kSet) {
885 context.fErrors->error(field.fPosition, "layout qualifier 'set' is not permitted on " +
886 std::string(aStructOrIB) + " field");
887 }
888
889 if (field.fType->isVoid()) {
890 context.fErrors->error(field.fPosition, "type 'void' is not permitted in " +
891 std::string(aStructOrIB));
892 }
893 if (field.fType->isOpaque() && !field.fType->isAtomic()) {
894 context.fErrors->error(field.fPosition, "opaque type '" + field.fType->displayName() +
895 "' is not permitted in " +
896 std::string(aStructOrIB));
897 }
898 if (interfaceBlock && field.fType->isOrContainsBool()) {
899 // Reject booleans anywhere in an interface block.
900 context.fErrors->error(field.fPosition, "type 'bool' is not permitted in an "
901 "interface block");
902 }
903 if (field.fType->isOrContainsUnsizedArray()) {
904 if (!interfaceBlock) {
905 // Reject unsized arrays anywhere in structs.
906 context.fErrors->error(field.fPosition, "unsized arrays are not permitted here");
907 }
908 } else {
909 // If we haven't already exceeded the struct size limit...
910 if (slots < kVariableSlotLimit) {
911 // ... see if this field causes us to exceed the size limit.
912 slots = SkSafeMath::Add(slots, field.fType->slotCount());
913 if (slots >= kVariableSlotLimit) {
914 context.fErrors->error(pos, std::string(structOrIB) + " is too large");
915 }
916 }
917 }
918 }
919 int nestingDepth = 0;
920 for (const Field& field : fields) {
921 nestingDepth = std::max(nestingDepth, field.fType->structNestingDepth());
922 }
923 if (nestingDepth >= kMaxStructDepth) {
924 context.fErrors->error(pos, std::string(structOrIB) + " '" + std::string(name) +
925 "' is too deeply nested");
926 }
927 return std::make_unique<StructType>(pos, name, std::move(fields), nestingDepth + 1,
928 interfaceBlock, context.fConfig->isBuiltinCode());
929 }
930
931 std::unique_ptr<Type> Type::MakeTextureType(const char* name, SpvDim_ dimensions, bool isDepth,
932 bool isArrayedTexture, bool isMultisampled,
933 TextureAccess textureAccess) {
934 return std::make_unique<TextureType>(name, dimensions, isDepth, isArrayedTexture,
935 isMultisampled, textureAccess);
936 }
937
938 std::unique_ptr<Type> Type::MakeVectorType(std::string_view name, const char* abbrev,
939 const Type& componentType, int columns) {
940 return std::make_unique<VectorType>(name, abbrev, componentType, columns);
941 }
942
943 CoercionCost Type::coercionCost(const Type& other) const {
944 if (this->matches(other)) {
945 return CoercionCost::Free();
946 }
947 if (this->typeKind() == other.typeKind() &&
948 (this->isVector() || this->isMatrix() || this->isArray())) {
949 // Vectors/matrices/arrays of the same size can be coerced if their component type can be.
950 if (this->isMatrix() && (this->rows() != other.rows())) {
951 return CoercionCost::Impossible();
952 }
953 if (this->columns() != other.columns()) {
954 return CoercionCost::Impossible();
955 }
956 return this->componentType().coercionCost(other.componentType());
957 }
958
959 if (this->isNumber() && other.isNumber()) {
960 if (this->isLiteral() && (this->isInteger() ||
961 this->numberKind() == other.numberKind())) {
962 // NOTE: We allow ${intLiteral} and ${floatLiteral} to coerce freely to `float` and
963 // `half`. Without this check, ${floatLiteral}'s priority would treat conversion to
964 // `half` as a cheaper "normal" conversion compared to conversion to `float`. Treating
965 // the cost as free means function overload selection is based off the types of the
966 // non-literal arguments; in the case where only literals are passed in, SkSL will
967 // require a cast to disambiguate between half or float function calls.
968 return CoercionCost::Free();
969 } else if (this->numberKind() != other.numberKind()) {
970 return CoercionCost::Impossible();
971 } else if (other.priority() >= this->priority()) {
972 return CoercionCost::Normal(other.priority() - this->priority());
973 } else {
974 return CoercionCost::Narrowing(this->priority() - other.priority());
975 }
976 }
977 if (fTypeKind == TypeKind::kGeneric) {
978 SkSpan<const Type* const> types = this->coercibleTypes();
979 for (size_t i = 0; i < types.size(); i++) {
980 if (types[i]->matches(other)) {
981 return CoercionCost::Normal((int) i + 1);
982 }
983 }
984 }
985 return CoercionCost::Impossible();
986 }
987
988 const Type* Type::applyQualifiers(const Context& context,
989 ModifierFlags* modifierFlags,
990 Position pos) const {
991 const Type* type;
992 type = this->applyPrecisionQualifiers(context, modifierFlags, pos);
993 type = type->applyAccessQualifiers(context, modifierFlags, pos);
994 return type;
995 }
996
997 const Type* Type::applyPrecisionQualifiers(const Context& context,
998 ModifierFlags* modifierFlags,
999 Position pos) const {
1000 ModifierFlags precisionQualifiers = *modifierFlags & (ModifierFlag::kHighp |
1001 ModifierFlag::kMediump |
1002 ModifierFlag::kLowp);
1003 if (precisionQualifiers == ModifierFlag::kNone) {
1004 // No precision qualifiers here. Return the type as-is.
1005 return this;
1006 }
1007
1008 if (!ProgramConfig::IsRuntimeEffect(context.fConfig->fKind)) {
1009 // We want to discourage precision modifiers internally. Instead, use the type that
1010 // corresponds to the precision you need. (e.g. half vs float, short vs int)
1011 context.fErrors->error(pos, "precision qualifiers are not allowed");
1012 return context.fTypes.fPoison.get();
1013 }
1014
1015 if (SkPopCount(precisionQualifiers.value()) > 1) {
1016 context.fErrors->error(pos, "only one precision qualifier can be used");
1017 return context.fTypes.fPoison.get();
1018 }
1019
1020 // We're going to return a whole new type, so the modifier bits can be cleared out.
1021 *modifierFlags &= ~(ModifierFlag::kHighp |
1022 ModifierFlag::kMediump |
1023 ModifierFlag::kLowp);
1024
1025 const Type& component = this->componentType();
1026 if (component.highPrecision()) {
1027 if (precisionQualifiers & ModifierFlag::kHighp) {
1028 // Type is already high precision, and we are requesting high precision. Return as-is.
1029 return this;
1030 }
1031
1032 // SkSL doesn't support low precision, so `lowp` is interpreted as medium precision.
1033 // Ascertain the mediump equivalent type for this type, if any.
1034 const Type* mediumpType;
1035 switch (component.numberKind()) {
1036 case Type::NumberKind::kFloat:
1037 mediumpType = context.fTypes.fHalf.get();
1038 break;
1039
1040 case Type::NumberKind::kSigned:
1041 mediumpType = context.fTypes.fShort.get();
1042 break;
1043
1044 case Type::NumberKind::kUnsigned:
1045 mediumpType = context.fTypes.fUShort.get();
1046 break;
1047
1048 default:
1049 mediumpType = context.fTypes.fPoison.get();
1050 break;
1051 }
1052
1053 if (mediumpType) {
1054 // Convert the mediump component type into the final vector/matrix/array type as needed.
1055 return this->isArray()
1056 ? context.fSymbolTable->addArrayDimension(context, mediumpType, this->columns())
1057 : &mediumpType->toCompound(context, this->columns(), this->rows());
1058 }
1059 }
1060
1061 context.fErrors->error(pos, "type '" + this->displayName() +
1062 "' does not support precision qualifiers");
1063 return context.fTypes.fPoison.get();
1064 }
1065
1066 const Type* Type::applyAccessQualifiers(const Context& context,
1067 ModifierFlags* modifierFlags,
1068 Position pos) const {
1069 ModifierFlags accessQualifiers = *modifierFlags & (ModifierFlag::kReadOnly |
1070 ModifierFlag::kWriteOnly);
1071
1072 // We're going to return a whole new type, so the modifier bits must be cleared out.
1073 *modifierFlags &= ~(ModifierFlag::kReadOnly |
1074 ModifierFlag::kWriteOnly);
1075
1076 if (this->matches(*context.fTypes.fTexture2D)) {
1077 // We require all texture2Ds to be qualified with `readonly` or `writeonly`.
1078 // (Read-write textures are not yet supported in WGSL.)
1079 if (accessQualifiers == ModifierFlag::kReadOnly) {
1080 return context.fTypes.fReadOnlyTexture2D.get();
1081 }
1082 if (accessQualifiers == ModifierFlag::kWriteOnly) {
1083 return context.fTypes.fWriteOnlyTexture2D.get();
1084 }
1085 context.fErrors->error(
1086 pos,
1087 accessQualifiers
1088 ? "'readonly' and 'writeonly' qualifiers cannot be combined"
1089 : "'texture2D' requires a 'readonly' or 'writeonly' access qualifier");
1090 return this;
1091 }
1092
1093 if (accessQualifiers) {
1094 context.fErrors->error(pos, "type '" + this->displayName() + "' does not support "
1095 "qualifier '" + accessQualifiers.description() + "'");
1096 }
1097
1098 return this;
1099 }
1100
1101 const Type& Type::toCompound(const Context& context, int columns, int rows) const {
1102 SkASSERT(this->isScalar());
1103 if (columns == 1 && rows == 1) {
1104 return *this;
1105 }
1106 if (this->matches(*context.fTypes.fFloat) || this->matches(*context.fTypes.fFloatLiteral)) {
1107 switch (rows) {
1108 case 1:
1109 switch (columns) {
1110 case 1: return *context.fTypes.fFloat;
1111 case 2: return *context.fTypes.fFloat2;
1112 case 3: return *context.fTypes.fFloat3;
1113 case 4: return *context.fTypes.fFloat4;
1114 default: SK_ABORT("unsupported vector column count (%d)", columns);
1115 }
1116 case 2:
1117 switch (columns) {
1118 case 2: return *context.fTypes.fFloat2x2;
1119 case 3: return *context.fTypes.fFloat3x2;
1120 case 4: return *context.fTypes.fFloat4x2;
1121 default: SK_ABORT("unsupported matrix column count (%d)", columns);
1122 }
1123 case 3:
1124 switch (columns) {
1125 case 2: return *context.fTypes.fFloat2x3;
1126 case 3: return *context.fTypes.fFloat3x3;
1127 case 4: return *context.fTypes.fFloat4x3;
1128 default: SK_ABORT("unsupported matrix column count (%d)", columns);
1129 }
1130 case 4:
1131 switch (columns) {
1132 case 2: return *context.fTypes.fFloat2x4;
1133 case 3: return *context.fTypes.fFloat3x4;
1134 case 4: return *context.fTypes.fFloat4x4;
1135 default: SK_ABORT("unsupported matrix column count (%d)", columns);
1136 }
1137 default: SK_ABORT("unsupported row count (%d)", rows);
1138 }
1139 } else if (this->matches(*context.fTypes.fHalf)) {
1140 switch (rows) {
1141 case 1:
1142 switch (columns) {
1143 case 1: return *context.fTypes.fHalf;
1144 case 2: return *context.fTypes.fHalf2;
1145 case 3: return *context.fTypes.fHalf3;
1146 case 4: return *context.fTypes.fHalf4;
1147 default: SK_ABORT("unsupported vector column count (%d)", columns);
1148 }
1149 case 2:
1150 switch (columns) {
1151 case 2: return *context.fTypes.fHalf2x2;
1152 case 3: return *context.fTypes.fHalf3x2;
1153 case 4: return *context.fTypes.fHalf4x2;
1154 default: SK_ABORT("unsupported matrix column count (%d)", columns);
1155 }
1156 case 3:
1157 switch (columns) {
1158 case 2: return *context.fTypes.fHalf2x3;
1159 case 3: return *context.fTypes.fHalf3x3;
1160 case 4: return *context.fTypes.fHalf4x3;
1161 default: SK_ABORT("unsupported matrix column count (%d)", columns);
1162 }
1163 case 4:
1164 switch (columns) {
1165 case 2: return *context.fTypes.fHalf2x4;
1166 case 3: return *context.fTypes.fHalf3x4;
1167 case 4: return *context.fTypes.fHalf4x4;
1168 default: SK_ABORT("unsupported matrix column count (%d)", columns);
1169 }
1170 default: SK_ABORT("unsupported row count (%d)", rows);
1171 }
1172 } else if (this->matches(*context.fTypes.fInt) || this->matches(*context.fTypes.fIntLiteral)) {
1173 switch (rows) {
1174 case 1:
1175 switch (columns) {
1176 case 1: return *context.fTypes.fInt;
1177 case 2: return *context.fTypes.fInt2;
1178 case 3: return *context.fTypes.fInt3;
1179 case 4: return *context.fTypes.fInt4;
1180 default: SK_ABORT("unsupported vector column count (%d)", columns);
1181 }
1182 default: SK_ABORT("unsupported row count (%d)", rows);
1183 }
1184 } else if (this->matches(*context.fTypes.fShort)) {
1185 switch (rows) {
1186 case 1:
1187 switch (columns) {
1188 case 1: return *context.fTypes.fShort;
1189 case 2: return *context.fTypes.fShort2;
1190 case 3: return *context.fTypes.fShort3;
1191 case 4: return *context.fTypes.fShort4;
1192 default: SK_ABORT("unsupported vector column count (%d)", columns);
1193 }
1194 default: SK_ABORT("unsupported row count (%d)", rows);
1195 }
1196 } else if (this->matches(*context.fTypes.fUInt)) {
1197 switch (rows) {
1198 case 1:
1199 switch (columns) {
1200 case 1: return *context.fTypes.fUInt;
1201 case 2: return *context.fTypes.fUInt2;
1202 case 3: return *context.fTypes.fUInt3;
1203 case 4: return *context.fTypes.fUInt4;
1204 default: SK_ABORT("unsupported vector column count (%d)", columns);
1205 }
1206 default: SK_ABORT("unsupported row count (%d)", rows);
1207 }
1208 } else if (this->matches(*context.fTypes.fUShort)) {
1209 switch (rows) {
1210 case 1:
1211 switch (columns) {
1212 case 1: return *context.fTypes.fUShort;
1213 case 2: return *context.fTypes.fUShort2;
1214 case 3: return *context.fTypes.fUShort3;
1215 case 4: return *context.fTypes.fUShort4;
1216 default: SK_ABORT("unsupported vector column count (%d)", columns);
1217 }
1218 default: SK_ABORT("unsupported row count (%d)", rows);
1219 }
1220 } else if (this->matches(*context.fTypes.fBool)) {
1221 switch (rows) {
1222 case 1:
1223 switch (columns) {
1224 case 1: return *context.fTypes.fBool;
1225 case 2: return *context.fTypes.fBool2;
1226 case 3: return *context.fTypes.fBool3;
1227 case 4: return *context.fTypes.fBool4;
1228 default: SK_ABORT("unsupported vector column count (%d)", columns);
1229 }
1230 default: SK_ABORT("unsupported row count (%d)", rows);
1231 }
1232 }
1233 SkDEBUGFAILF("unsupported toCompound type %s", this->description().c_str());
1234 return *context.fTypes.fVoid;
1235 }
1236
1237 const Type* Type::clone(const Context& context, SymbolTable* symbolTable) const {
1238 // Many types are built-ins, and exist in every SymbolTable by default.
1239 if (this->isInRootSymbolTable()) {
1240 return this;
1241 }
1242 // If we are compiling a program, and the type comes from the program's module, it is safe to
1243 // assume that the type is in-scope anywhere in the program without actually recursing through
1244 // the SymbolTable hierarchy to prove it.
1245 if (!context.fConfig->isBuiltinCode() && this->isBuiltin()) {
1246 return this;
1247 }
1248 // Even if the type isn't a built-in, it might already exist in the SymbolTable. Search by name.
1249 const Symbol* existingSymbol = symbolTable->find(this->name());
1250 if (existingSymbol != nullptr) {
1251 const Type* existingType = &existingSymbol->as<Type>();
1252 SkASSERT(existingType->typeKind() == this->typeKind());
1253 return existingType;
1254 }
1255 // This type actually needs to be cloned into the destination SymbolTable.
1256 switch (this->typeKind()) {
1257 case TypeKind::kArray: {
1258 return symbolTable->addArrayDimension(context, &this->componentType(), this->columns());
1259 }
1260 case TypeKind::kStruct: {
1261 // We are cloning an existing struct, so there's no need to call MakeStructType and
1262 // fully error-check it again.
1263 const std::string* name = symbolTable->takeOwnershipOfString(std::string(this->name()));
1264 SkSpan<const Field> fieldSpan = this->fields();
1265 return symbolTable->add(
1266 context,
1267 std::make_unique<StructType>(this->fPosition,
1268 *name,
1269 TArray<Field>(fieldSpan.data(), fieldSpan.size()),
1270 this->structNestingDepth(),
1271 /*interfaceBlock=*/this->isInterfaceBlock(),
1272 /*isBuiltin=*/context.fConfig->isBuiltinCode()));
1273 }
1274 default:
1275 SkDEBUGFAILF("don't know how to clone type '%s'", this->description().c_str());
1276 return nullptr;
1277 }
1278 }
1279
1280 std::unique_ptr<Expression> Type::coerceExpression(std::unique_ptr<Expression> expr,
1281 const Context& context) const {
1282 if (!expr || expr->isIncomplete(context)) {
1283 return nullptr;
1284 }
1285 if (expr->type().matches(*this)) {
1286 return expr;
1287 }
1288
1289 const Position pos = expr->fPosition;
1290 const ProgramSettings& settings = context.fConfig->fSettings;
1291 if (!expr->coercionCost(*this).isPossible(settings.fAllowNarrowingConversions)) {
1292 context.fErrors->error(pos, "expected '" + this->displayName() + "', but found '" +
1293 expr->type().displayName() + "'");
1294 return nullptr;
1295 }
1296
1297 if (this->isScalar()) {
1298 return ConstructorScalarCast::Make(context, pos, *this, std::move(expr));
1299 }
1300 if (this->isVector() || this->isMatrix()) {
1301 return ConstructorCompoundCast::Make(context, pos, *this, std::move(expr));
1302 }
1303 if (this->isArray()) {
1304 return ConstructorArrayCast::Make(context, pos, *this, std::move(expr));
1305 }
1306 context.fErrors->error(pos, "cannot construct '" + this->displayName() + "'");
1307 return nullptr;
1308 }
1309
1310 bool Type::isAllowedInES2(const Context& context) const {
1311 return !context.fConfig->strictES2Mode() || this->isAllowedInES2();
1312 }
1313
1314 bool Type::checkForOutOfRangeLiteral(const Context& context, const Expression& expr) const {
1315 bool foundError = false;
1316 const Type& baseType = this->componentType();
1317 if (baseType.isNumber()) {
1318 // Replace constant expressions with their corresponding values.
1319 const Expression* valueExpr = ConstantFolder::GetConstantValueForVariable(expr);
1320 // Unsized arrays can't have constants and fails to get a slotCount.
1321 if (valueExpr->supportsConstantValues() && !valueExpr->type().isUnsizedArray()) {
1322 // Iterate over every constant subexpression in the value.
1323 int numSlots = valueExpr->type().slotCount();
1324 for (int slot = 0; slot < numSlots; ++slot) {
1325 std::optional<double> slotVal = valueExpr->getConstantValue(slot);
1326 // Check for Literal values that are out of range for the base type.
1327 if (slotVal.has_value() &&
1328 baseType.checkForOutOfRangeLiteral(context, *slotVal, valueExpr->fPosition)) {
1329 foundError = true;
1330 }
1331 }
1332 }
1333 }
1334
1335 // We don't need range checks for floats or booleans; any matched-type value is acceptable.
1336 return foundError;
1337 }
1338
1339 bool Type::checkForOutOfRangeLiteral(const Context& context, double value, Position pos) const {
1340 SkASSERT(this->isScalar());
1341 if (!this->isNumber()) {
1342 return false;
1343 }
1344 if (value >= this->minimumValue() && value <= this->maximumValue()) {
1345 return false;
1346 }
1347 // We found a value that can't fit in our type. Flag it as an error.
1348 context.fErrors->error(pos, SkSL::String::printf("value is out of range for type '%s': %.0f",
1349 this->displayName().c_str(),
1350 value));
1351 return true;
1352 }
1353
1354 bool Type::checkIfUsableInArray(const Context& context, Position arrayPos) const {
1355 if (this->isArray()) {
1356 context.fErrors->error(arrayPos, "multi-dimensional arrays are not supported");
1357 return false;
1358 }
1359 if (this->isVoid()) {
1360 context.fErrors->error(arrayPos, "type 'void' may not be used in an array");
1361 return false;
1362 }
1363 if (this->isOpaque() && !this->isAtomic()) {
1364 context.fErrors->error(arrayPos, "opaque type '" + std::string(this->name()) +
1365 "' may not be used in an array");
1366 return false;
1367 }
1368 return true;
1369 }
1370
1371 SKSL_INT Type::convertArraySize(const Context& context,
1372 Position arrayPos,
1373 std::unique_ptr<Expression> size) const {
1374 size = context.fTypes.fInt->coerceExpression(std::move(size), context);
1375 if (!size) {
1376 return 0;
1377 }
1378 SKSL_INT count;
1379 if (!ConstantFolder::GetConstantInt(*size, &count)) {
1380 context.fErrors->error(size->fPosition, "array size must be an integer");
1381 return 0;
1382 }
1383 return this->convertArraySize(context, arrayPos, size->fPosition, count);
1384 }
1385
1386 SKSL_INT Type::convertArraySize(const Context& context,
1387 Position arrayPos,
1388 Position sizePos,
1389 SKSL_INT size) const {
1390 if (!this->checkIfUsableInArray(context, arrayPos)) {
1391 // `checkIfUsableInArray` will generate an error for us.
1392 return 0;
1393 }
1394 if (size <= 0) {
1395 context.fErrors->error(sizePos, "array size must be positive");
1396 return 0;
1397 }
1398 // We can't get a meaningful slot count if the interior type contains an unsized array; we'll
1399 // assert if we try. Unsized arrays should only occur in a handful of limited cases (e.g. an
1400 // interface block with a trailing buffer), and will never be valid in a runtime effect.
1401 if (!this->isOrContainsUnsizedArray()) {
1402 if (SkSafeMath::Mul(this->slotCount(), size) > kVariableSlotLimit) {
1403 context.fErrors->error(sizePos, "array size is too large");
1404 return 0;
1405 }
1406 }
1407 return size;
1408 }
1409
1410 std::string Field::description() const {
1411 return fLayout.paddedDescription() + fModifierFlags.paddedDescription() + fType->displayName() +
1412 ' ' + std::string(fName) + ';';
1413 }
1414
1415 } // namespace SkSL