Debian Codegraph @

src/sksl/codegen/SkSLWGSLCodeGenerator.cpp

raw
1 /*
2 * Copyright 2022 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/codegen/SkSLWGSLCodeGenerator.h"
9
10 #include "include/core/SkSpan.h"
11 #include "include/core/SkTypes.h"
12 #include "include/private/base/SkTArray.h"
13 #include "include/private/base/SkTo.h"
14 #include "src/base/SkEnumBitMask.h"
15 #include "src/base/SkStringView.h"
16 #include "src/core/SkTHash.h"
17 #include "src/core/SkTraceEvent.h"
18 #include "src/sksl/SkSLAnalysis.h"
19 #include "src/sksl/SkSLBuiltinTypes.h"
20 #include "src/sksl/SkSLCompiler.h"
21 #include "src/sksl/SkSLConstantFolder.h"
22 #include "src/sksl/SkSLContext.h"
23 #include "src/sksl/SkSLDefines.h"
24 #include "src/sksl/SkSLErrorReporter.h"
25 #include "src/sksl/SkSLIntrinsicList.h"
26 #include "src/sksl/SkSLMemoryLayout.h"
27 #include "src/sksl/SkSLOperator.h"
28 #include "src/sksl/SkSLOutputStream.h"
29 #include "src/sksl/SkSLPosition.h"
30 #include "src/sksl/SkSLProgramSettings.h"
31 #include "src/sksl/SkSLString.h"
32 #include "src/sksl/SkSLStringStream.h"
33 #include "src/sksl/SkSLUtil.h"
34 #include "src/sksl/analysis/SkSLProgramUsage.h"
35 #include "src/sksl/analysis/SkSLProgramVisitor.h"
36 #include "src/sksl/codegen/SkSLCodeGenTypes.h"
37 #include "src/sksl/codegen/SkSLCodeGenerator.h"
38 #include "src/sksl/codegen/SkSLNativeShader.h"
39 #include "src/sksl/ir/SkSLBinaryExpression.h"
40 #include "src/sksl/ir/SkSLBlock.h"
41 #include "src/sksl/ir/SkSLConstructor.h"
42 #include "src/sksl/ir/SkSLConstructorArrayCast.h"
43 #include "src/sksl/ir/SkSLConstructorCompound.h"
44 #include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
45 #include "src/sksl/ir/SkSLConstructorMatrixResize.h"
46 #include "src/sksl/ir/SkSLDoStatement.h"
47 #include "src/sksl/ir/SkSLExpression.h"
48 #include "src/sksl/ir/SkSLExpressionStatement.h"
49 #include "src/sksl/ir/SkSLFieldAccess.h"
50 #include "src/sksl/ir/SkSLFieldSymbol.h"
51 #include "src/sksl/ir/SkSLForStatement.h"
52 #include "src/sksl/ir/SkSLFunctionCall.h"
53 #include "src/sksl/ir/SkSLFunctionDeclaration.h"
54 #include "src/sksl/ir/SkSLFunctionDefinition.h"
55 #include "src/sksl/ir/SkSLIRHelpers.h"
56 #include "src/sksl/ir/SkSLIRNode.h"
57 #include "src/sksl/ir/SkSLIfStatement.h"
58 #include "src/sksl/ir/SkSLIndexExpression.h"
59 #include "src/sksl/ir/SkSLInterfaceBlock.h"
60 #include "src/sksl/ir/SkSLLayout.h"
61 #include "src/sksl/ir/SkSLLiteral.h"
62 #include "src/sksl/ir/SkSLModifierFlags.h"
63 #include "src/sksl/ir/SkSLModifiers.h"
64 #include "src/sksl/ir/SkSLModifiersDeclaration.h"
65 #include "src/sksl/ir/SkSLPostfixExpression.h"
66 #include "src/sksl/ir/SkSLPrefixExpression.h"
67 #include "src/sksl/ir/SkSLProgram.h"
68 #include "src/sksl/ir/SkSLProgramElement.h"
69 #include "src/sksl/ir/SkSLReturnStatement.h"
70 #include "src/sksl/ir/SkSLSetting.h"
71 #include "src/sksl/ir/SkSLStatement.h"
72 #include "src/sksl/ir/SkSLStructDefinition.h"
73 #include "src/sksl/ir/SkSLSwitchCase.h"
74 #include "src/sksl/ir/SkSLSwitchStatement.h"
75 #include "src/sksl/ir/SkSLSwizzle.h"
76 #include "src/sksl/ir/SkSLTernaryExpression.h"
77 #include "src/sksl/ir/SkSLType.h"
78 #include "src/sksl/ir/SkSLVarDeclarations.h"
79 #include "src/sksl/ir/SkSLVariable.h"
80 #include "src/sksl/ir/SkSLVariableReference.h"
81 #include "src/sksl/spirv.h"
82 #include "src/sksl/transform/SkSLTransform.h"
83
84 #include <algorithm>
85 #include <cstddef>
86 #include <cstdint>
87 #include <initializer_list>
88 #include <iterator>
89 #include <memory>
90 #include <optional>
91 #include <string>
92 #include <string_view>
93 #include <utility>
94
95 using namespace skia_private;
96
97 namespace {
98
99 // Represents a function's dependencies that are not accessible in global scope. For instance,
100 // pipeline stage input and output parameters must be passed in as an argument.
101 //
102 // This is a bitmask enum. (It would be inside `class WGSLCodeGenerator`, but this leads to build
103 // errors in MSVC.)
104 enum class WGSLFunctionDependency : uint8_t {
105 kNone = 0,
106 kPipelineInputs = 1 << 0,
107 kPipelineOutputs = 1 << 1,
108 };
109 using WGSLFunctionDependencies = SkEnumBitMask<WGSLFunctionDependency>;
110
111 SK_MAKE_BITMASK_OPS(WGSLFunctionDependency)
112
113 } // namespace
114
115 namespace SkSL {
116
117 class WGSLCodeGenerator : public CodeGenerator {
118 public:
119 // See https://www.w3.org/TR/WGSL/#builtin-values
120 enum class Builtin {
121 // Vertex stage:
122 kVertexIndex, // input
123 kInstanceIndex, // input
124 kPosition, // output, fragment stage input
125
126 // Fragment stage:
127 kLastFragColor, // input
128 kFrontFacing, // input
129 kSampleIndex, // input
130 kFragDepth, // output
131 kSampleMaskIn, // input
132 kSampleMask, // output
133
134 // Compute stage:
135 kLocalInvocationId, // input
136 kLocalInvocationIndex, // input
137 kGlobalInvocationId, // input
138 kWorkgroupId, // input
139 kNumWorkgroups, // input
140 };
141
142 // Variable declarations can be terminated by:
143 // - comma (","), e.g. in struct member declarations or function parameters
144 // - semicolon (";"), e.g. in function scope variables
145 // A "none" option is provided to skip the delimiter when not needed, e.g. at the end of a list
146 // of declarations.
147 enum class Delimiter {
148 kComma,
149 kSemicolon,
150 kNone,
151 };
152
153 struct ProgramRequirements {
154 using DepsMap = skia_private::THashMap<const FunctionDeclaration*,
155 WGSLFunctionDependencies>;
156
157 // Mappings used to synthesize function parameters according to dependencies on pipeline
158 // input/output variables.
159 DepsMap fDependencies;
160
161 // These flags track extensions that will need to be enabled.
162 bool fPixelLocalExtension = false;
163 };
164
165 WGSLCodeGenerator(const Context* context,
166 const ShaderCaps* caps,
167 const Program* program,
168 OutputStream* out,
169 PrettyPrint pp,
170 IncludeSyntheticCode isc)
171 : CodeGenerator(context, caps, program, out)
172 , fPrettyPrint(pp)
173 , fGenSyntheticCode(isc) {}
174
175 bool generateCode() override;
176
177 private:
178 using Precedence = OperatorPrecedence;
179 class AutoConstEvalWorkaround;
180
181 // Called by generateCode() as the first step.
182 void preprocessProgram();
183
184 // Write output content while correctly handling indentation.
185 void write(std::string_view s);
186 void writeLine(std::string_view s = std::string_view());
187 void finishLine();
188
189 // Helpers to declare a pipeline stage IO parameter declaration.
190 void writePipelineIODeclaration(const Layout& layout,
191 const Type& type,
192 ModifierFlags modifiers,
193 std::string_view name,
194 Delimiter delimiter);
195 void writeUserDefinedIODecl(const Layout& layout,
196 const Type& type,
197 ModifierFlags modifiers,
198 std::string_view name,
199 Delimiter delimiter);
200 void writeBuiltinIODecl(const Type& type,
201 std::string_view name,
202 Builtin builtin,
203 Delimiter delimiter);
204 void writeVariableDecl(const Layout& layout,
205 const Type& type,
206 std::string_view name,
207 Delimiter delimiter);
208
209 // Write a function definition.
210 void writeFunction(const FunctionDefinition& f);
211 void writeFunctionDeclaration(const FunctionDeclaration& f,
212 SkSpan<const bool> paramNeedsDedicatedStorage);
213
214 // Write the program entry point.
215 void writeEntryPoint(const FunctionDefinition& f);
216
217 // Writers for supported statement types.
218 void writeStatement(const Statement& s);
219 void writeStatements(const StatementArray& statements);
220 void writeBlock(const Block& b);
221 void writeDoStatement(const DoStatement& expr);
222 void writeExpressionStatement(const Expression& expr);
223 void writeForStatement(const ForStatement& s);
224 void writeIfStatement(const IfStatement& s);
225 void writeReturnStatement(const ReturnStatement& s);
226 void writeSwitchStatement(const SwitchStatement& s);
227 void writeSwitchCases(SkSpan<const SwitchCase* const> cases);
228 void writeEmulatedSwitchFallthroughCases(SkSpan<const SwitchCase* const> cases,
229 std::string_view switchValue);
230 void writeSwitchCaseList(SkSpan<const SwitchCase* const> cases);
231 void writeVarDeclaration(const VarDeclaration& varDecl);
232
233 // Synthesizes an LValue for an expression.
234 class LValue;
235 class PointerLValue;
236 class SwizzleLValue;
237 class VectorComponentLValue;
238 std::unique_ptr<LValue> makeLValue(const Expression& e);
239
240 std::string variableReferenceNameForLValue(const VariableReference& r);
241 std::string variablePrefix(const Variable& v);
242
243 bool binaryOpNeedsComponentwiseMatrixPolyfill(const Type& left, const Type& right, Operator op);
244
245 enum AssembleMode {
246 kAuto, // Will either be inlined expression or let to avoid const-eval
247 kUsedMultipleTimes, // Will be inlined if trivial, or a let so reuse by caller is free
248 kForceLet, // Will be written to a let
249 };
250 // Writers for expressions. These return the final expression text as a string, and emit any
251 // necessary setup code directly into the program as necessary. The returned expression may be
252 // a `let`-alias that cannot be assigned-into; use `makeLValue` for an assignable expression.
253 std::string assembleExpression(const Expression& e, Precedence parentPrecedence,
254 AssembleMode mode = kAuto);
255
256 std::string assembleBinaryExpression(const BinaryExpression& b, Precedence parentPrecedence);
257 std::string assembleBinaryExpression(const Expression& left,
258 Operator op,
259 const Expression& right,
260 const Type& resultType,
261 Precedence parentPrecedence);
262 std::string assembleFieldAccess(const FieldAccess& f);
263 std::string assembleFunctionCall(const FunctionCall& call, Precedence parentPrecedence);
264 std::string assembleIndexExpression(const IndexExpression& i);
265 std::string assembleLiteral(const Literal& l);
266 std::string assemblePostfixExpression(const PostfixExpression& p, Precedence parentPrecedence);
267 std::string assemblePrefixExpression(const PrefixExpression& p, Precedence parentPrecedence);
268 std::string assembleSwizzle(const Swizzle& swizzle);
269 std::string assembleTernaryExpression(const TernaryExpression& t, Precedence parentPrecedence);
270 std::string assembleVariableReference(const VariableReference& r);
271 std::string assembleName(std::string_view name);
272
273 std::string assembleIncrementExpr(const Type& type);
274
275 // Intrinsic helper functions.
276 std::string assembleIntrinsicCall(const FunctionCall& call,
277 IntrinsicKind kind,
278 Precedence parentPrecedence);
279 std::string assembleSimpleIntrinsic(std::string_view intrinsicName,
280 const FunctionCall& call,
281 bool wgslOnlySupportsHighPrecision=false);
282 std::string assembleUnaryOpIntrinsic(Operator op,
283 const FunctionCall& call,
284 Precedence parentPrecedence);
285 std::string assembleBinaryOpIntrinsic(Operator op,
286 const FunctionCall& call,
287 Precedence parentPrecedence);
288 std::string assembleVectorizedIntrinsic(std::string_view intrinsicName,
289 const FunctionCall& call);
290 std::string assembleOutAssignedIntrinsic(std::string_view intrinsicName,
291 std::string_view returnFieldName,
292 std::string_view outFieldName,
293 const FunctionCall& call);
294 // Returns the beginning of the expression and the closing parentheses string to append once
295 // any additional arguments are added.
296 std::pair<std::string, const char*> assemblePartialSampleCall(std::string_view intrinsicName,
297 const Type& type,
298 const Expression& sampler,
299 const Expression& coords);
300 std::string assembleInversePolyfill(const FunctionCall& call);
301 std::string assembleOuterProductPolyfill(const FunctionCall& call);
302 std::string assembleComponentwiseMatrixBinary(const Type& leftType,
303 const Type& rightType,
304 const std::string& left,
305 const std::string& right,
306 Operator op);
307
308 // Constructor expressions
309 std::string assembleAnyConstructor(const AnyConstructor& c);
310 std::string assembleConstructorCompound(const ConstructorCompound& c);
311 std::string assembleConstructorCompoundVector(const ConstructorCompound& c);
312 std::string assembleConstructorCompoundMatrix(const ConstructorCompound& c);
313 std::string assembleConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c);
314 std::string assembleConstructorMatrixResize(const ConstructorMatrixResize& ctor);
315 std::string assembleConstructorArrayCast(const ConstructorArrayCast& c,
316 Precedence parentPrecedence);
317
318 // Synthesized helper functions for comparison operators that are not supported by WGSL.
319 std::string assembleEqualityExpression(const Type& left,
320 const std::string& leftName,
321 const Type& right,
322 const std::string& rightName,
323 Operator op,
324 Precedence parentPrecedence);
325 std::string assembleEqualityExpression(const Expression& left,
326 const Expression& right,
327 Operator op,
328 Precedence parentPrecedence);
329
330 // Writes a scratch variable into the program and returns its name (e.g. `_skTemp123`).
331 std::string writeScratchVar(const Type& type, const std::string& value = "");
332
333 // Writes a scratch let-variable into the program, gives it the value of `expr`, and returns its
334 // name (e.g. `_skTemp123`). This can be `const` instead of `let` when isCompileTimeConstant is
335 // true and at function scope.
336 //
337 // Prefer using assembleExpression() with an AssembleMode to control when scratch lets should
338 // be created automatically.
339 std::string writeScratchLet(const std::string& expr, bool isCompileTimeConstant = false);
340
341 // Generic recursive ProgramElement visitor.
342 void writeProgramElement(const ProgramElement& e);
343 void writeGlobalVarDeclaration(const GlobalVarDeclaration& d);
344 void writeStructDefinition(const StructDefinition& s);
345 void writeModifiersDeclaration(const ModifiersDeclaration&);
346
347 // Writes the WGSL struct fields for SkSL structs and interface blocks. Enforces WGSL address
348 // space layout constraints
349 // (https://www.w3.org/TR/WGSL/#address-space-layout-constraints) if a `layout` is
350 // provided. A struct that does not need to be host-shareable does not require a `layout`.
351 void writeFields(SkSpan<const Field> fields, const MemoryLayout* memoryLayout = nullptr);
352
353 // We bundle uniforms, and all varying pipeline stage inputs and outputs, into separate structs.
354 bool needsStageInputStruct() const;
355 void writeStageInputStruct();
356 bool needsStageOutputStruct() const;
357 void writeStageOutputStruct();
358 void writeUniformsAndBuffers();
359 void writeInterfaceBlock(const InterfaceBlock& ib);
360
361 void prepareUniformPolyfillsForInterfaceBlock(const InterfaceBlock* interfaceBlock,
362 std::string_view instanceName,
363 MemoryLayout::Standard nativeLayout);
364 void writeEnables();
365 void writeUniformPolyfills();
366
367 void writeTextureOrSampler(const Variable& var,
368 int bindingLocation,
369 std::string_view suffix,
370 std::string_view wgslType);
371
372 // Writes all top-level non-opaque global uniform declarations (i.e. not part of an interface
373 // block) into a single uniform block binding.
374 //
375 // In complete fragment/vertex/compute programs, uniforms will be declared only as interface
376 // blocks and global opaque types (like textures and samplers) which we expect to be declared
377 // with a unique binding and descriptor set index. However, test files that are declared as RTE
378 // programs may contain OpenGL-style global uniform declarations with no clear binding index to
379 // use for the containing synthesized block.
380 //
381 // Since we are handling these variables only to generate gold files from RTEs and never run
382 // them, we always declare them at the default bind group and binding index.
383 void writeNonBlockUniformsForTests();
384
385 // For a given function declaration, writes out any implicitly required pipeline stage arguments
386 // based on the function's pre-determined dependencies. These are expected to be written out as
387 // the first parameters for a function that requires them. Returns true if any arguments were
388 // written.
389 std::string functionDependencyArgs(const FunctionDeclaration&);
390 bool writeFunctionDependencyParams(const FunctionDeclaration&);
391
392 // Code in the header appears before the main body of code.
393 StringStream fHeader;
394
395 // We assign unique names to anonymous interface blocks based on the type.
396 skia_private::THashMap<const Type*, std::string> fInterfaceBlockNameMap;
397
398 // Stores the functions which use stage inputs/outputs as well as required WGSL extensions.
399 ProgramRequirements fRequirements;
400 skia_private::TArray<const Variable*> fPipelineInputs;
401 skia_private::TArray<const Variable*> fPipelineOutputs;
402
403 // These fields track whether we have written the polyfill for `inverse()` for a given matrix
404 // type. Indexed by row or column count - 2, i.e. [2,3,4] -> idx [0,1,2]
405 struct WrittenPolyfills {
406 std::array<bool, 3> fInverse;
407 std::array<std::array<bool, 3>, 3> fOuterProduct;
408
409 WrittenPolyfills() : fInverse({false, false, false})
410 , fOuterProduct({std::array{false, false, false},
411 std::array{false, false, false},
412 std::array{false, false, false}}) {}
413 };
414 WrittenPolyfills fF32Polyfills;
415 WrittenPolyfills fF16Polyfills;
416
417 PrettyPrint fPrettyPrint;
418 IncludeSyntheticCode fGenSyntheticCode;
419
420 // These fields control uniform polyfill support in cases where WGSL and std140 disagree.
421 // In std140 layout, matrices need to be represented as arrays of @align(16) vectors, and
422 // array elements are wrapped in a struct containing a single @align(16) element. Arrays
423 // of matrices combine both wrappers. These wrapper structs are unpacked into natively-typed
424 // globals at the shader entrypoint.
425 struct FieldPolyfillInfo {
426 const InterfaceBlock* fInterfaceBlock;
427 std::string fReplacementName;
428 bool fIsArray = false;
429 bool fIsMatrix = false;
430 bool fWasAccessed = false;
431 };
432 using FieldPolyfillMap = skia_private::THashMap<const Field*, FieldPolyfillInfo>;
433 FieldPolyfillMap fFieldPolyfillMap;
434
435 std::unique_ptr<InterfaceBlock> fSyntheticGlobalUniformsBlock;
436
437 // Output processing state.
438 int fIndentation = 0;
439 bool fAtLineStart = false;
440 bool fHasUnconditionalReturn = false;
441 bool fAtFunctionScope = false;
442 bool fNeedsConstEvalWorkaround = false; // See skbug.com/40045457
443 int fConditionalScopeDepth = 0;
444 int fLocalSizeX = 1;
445 int fLocalSizeY = 1;
446 int fLocalSizeZ = 1;
447
448 int fScratchCount = 0;
449 };
450
451 enum class ProgramKind : int8_t;
452
453 namespace {
454
455 static constexpr char kSamplerSuffix[] = "_Sampler";
456 static constexpr char kTextureSuffix[] = "_Texture";
457
458 // See https://www.w3.org/TR/WGSL/#memory-view-types
459 enum class PtrAddressSpace {
460 kFunction,
461 kPrivate,
462 kStorage,
463 };
464
465 const char* operator_name(Operator op) {
466 switch (op.kind()) {
467 case Operator::Kind::LOGICALXOR: return " != ";
468 default: return op.operatorName();
469 }
470 }
471
472 bool is_reserved_word(std::string_view word) {
473 static const THashSet<std::string_view> kReservedWords{
474 // Used by SkSL:
475 "FSIn",
476 "FSOut",
477 "VSIn",
478 "VSOut",
479 "CSIn",
480 "_globalUniforms",
481 "_GlobalUniforms",
482 "_return",
483 "_stageIn",
484 "_stageOut",
485 // Keywords: https://www.w3.org/TR/WGSL/#keyword-summary
486 "alias",
487 "break",
488 "case",
489 "const",
490 "const_assert",
491 "continue",
492 "continuing",
493 "default",
494 "diagnostic",
495 "discard",
496 "else",
497 "enable",
498 "false",
499 "fn",
500 "for",
501 "if",
502 "let",
503 "loop",
504 "override",
505 "requires",
506 "return",
507 "struct",
508 "switch",
509 "true",
510 "var",
511 "while",
512 // Pre-declared types: https://www.w3.org/TR/WGSL/#predeclared-types
513 "bool",
514 "f16",
515 "f32",
516 "i32",
517 "u32",
518 // ... and pre-declared type generators:
519 "array",
520 "atomic",
521 "mat2x2",
522 "mat2x3",
523 "mat2x4",
524 "mat3x2",
525 "mat3x3",
526 "mat3x4",
527 "mat4x2",
528 "mat4x3",
529 "mat4x4",
530 "ptr",
531 "texture_1d",
532 "texture_2d",
533 "texture_2d_array",
534 "texture_3d",
535 "texture_cube",
536 "texture_cube_array",
537 "texture_multisampled_2d",
538 "texture_storage_1d",
539 "texture_storage_2d",
540 "texture_storage_2d_array",
541 "texture_storage_3d",
542 "vec2",
543 "vec3",
544 "vec4",
545 // Pre-declared enumerants: https://www.w3.org/TR/WGSL/#predeclared-enumerants
546 "read",
547 "write",
548 "read_write",
549 "function",
550 "private",
551 "workgroup",
552 "uniform",
553 "storage",
554 "perspective",
555 "linear",
556 "flat",
557 "center",
558 "centroid",
559 "sample",
560 "vertex_index",
561 "instance_index",
562 "position",
563 "front_facing",
564 "frag_depth",
565 "local_invocation_id",
566 "local_invocation_index",
567 "global_invocation_id",
568 "workgroup_id",
569 "num_workgroups",
570 "sample_index",
571 "sample_mask",
572 "rgba8unorm",
573 "rgba8snorm",
574 "rgba8uint",
575 "rgba8sint",
576 "rgba16uint",
577 "rgba16sint",
578 "rgba16float",
579 "r32uint",
580 "r32sint",
581 "r32float",
582 "rg32uint",
583 "rg32sint",
584 "rg32float",
585 "rgba32uint",
586 "rgba32sint",
587 "rgba32float",
588 "bgra8unorm",
589 // Reserved words: https://www.w3.org/TR/WGSL/#reserved-words
590 "_",
591 "NULL",
592 "Self",
593 "abstract",
594 "active",
595 "alignas",
596 "alignof",
597 "as",
598 "asm",
599 "asm_fragment",
600 "async",
601 "attribute",
602 "auto",
603 "await",
604 "become",
605 "binding_array",
606 "cast",
607 "catch",
608 "class",
609 "co_await",
610 "co_return",
611 "co_yield",
612 "coherent",
613 "column_major",
614 "common",
615 "compile",
616 "compile_fragment",
617 "concept",
618 "const_cast",
619 "consteval",
620 "constexpr",
621 "constinit",
622 "crate",
623 "debugger",
624 "decltype",
625 "delete",
626 "demote",
627 "demote_to_helper",
628 "do",
629 "dynamic_cast",
630 "enum",
631 "explicit",
632 "export",
633 "extends",
634 "extern",
635 "external",
636 "fallthrough",
637 "filter",
638 "final",
639 "finally",
640 "friend",
641 "from",
642 "fxgroup",
643 "get",
644 "goto",
645 "groupshared",
646 "highp",
647 "impl",
648 "implements",
649 "import",
650 "inline",
651 "instanceof",
652 "interface",
653 "layout",
654 "lowp",
655 "macro",
656 "macro_rules",
657 "match",
658 "mediump",
659 "meta",
660 "mod",
661 "module",
662 "move",
663 "mut",
664 "mutable",
665 "namespace",
666 "new",
667 "nil",
668 "noexcept",
669 "noinline",
670 "nointerpolation",
671 "noperspective",
672 "null",
673 "nullptr",
674 "of",
675 "operator",
676 "package",
677 "packoffset",
678 "partition",
679 "pass",
680 "patch",
681 "pixelfragment",
682 "precise",
683 "precision",
684 "premerge",
685 "priv",
686 "protected",
687 "pub",
688 "public",
689 "readonly",
690 "ref",
691 "regardless",
692 "register",
693 "reinterpret_cast",
694 "require",
695 "resource",
696 "restrict",
697 "self",
698 "set",
699 "shared",
700 "sizeof",
701 "smooth",
702 "snorm",
703 "static",
704 "static_assert",
705 "static_cast",
706 "std",
707 "subroutine",
708 "super",
709 "target",
710 "template",
711 "this",
712 "thread_local",
713 "throw",
714 "trait",
715 "try",
716 "type",
717 "typedef",
718 "typeid",
719 "typename",
720 "typeof",
721 "union",
722 "unless",
723 "unorm",
724 "unsafe",
725 "unsized",
726 "use",
727 "using",
728 "varying",
729 "virtual",
730 "volatile",
731 "wgsl",
732 "where",
733 "with",
734 "writeonly",
735 "yield",
736 };
737
738 return kReservedWords.contains(word);
739 }
740
741 std::string_view pipeline_struct_prefix(ProgramKind kind) {
742 if (ProgramConfig::IsVertex(kind)) {
743 return "VS";
744 }
745 if (ProgramConfig::IsFragment(kind)) {
746 return "FS";
747 }
748 if (ProgramConfig::IsCompute(kind)) {
749 return "CS";
750 }
751 // Compute programs don't have stage-in/stage-out pipeline structs.
752 return "";
753 }
754
755 std::string_view address_space_to_str(PtrAddressSpace addressSpace) {
756 switch (addressSpace) {
757 case PtrAddressSpace::kFunction:
758 return "function";
759 case PtrAddressSpace::kPrivate:
760 return "private";
761 case PtrAddressSpace::kStorage:
762 return "storage";
763 }
764 SkDEBUGFAIL("unsupported ptr address space");
765 return "unsupported";
766 }
767
768 bool type_is_low_precision(const Type& type, bool f16Available) {
769 // For now only consider half vs. float, not short vs int
770 return f16Available && (type.componentType().isFloat() && !type.highPrecision());
771 }
772
773 bool type_is_low_precision(const Type& type, const Context& context) {
774 return type_is_low_precision(type, !context.fConfig->fSettings.fForceHighPrecision);
775 }
776
777 std::string_view to_scalar_type(const Type& type, bool f16Available) {
778 SkASSERT(type.typeKind() == Type::TypeKind::kScalar);
779 switch (type.numberKind()) {
780 case Type::NumberKind::kFloat:
781 // Floating point numbers can map to f32 or f16 depending on whether or not the
782 // shader-f16 wgsl extension is supported.
783 return type_is_low_precision(type, f16Available) ? "f16" : "f32";
784 case Type::NumberKind::kSigned:
785 return "i32";
786 case Type::NumberKind::kUnsigned:
787 return "u32";
788 case Type::NumberKind::kBoolean:
789 return "bool";
790 case Type::NumberKind::kNonnumeric:
791 [[fallthrough]];
792 default:
793 break;
794 }
795 return type.name();
796 }
797
798 // Convert a SkSL type to a WGSL type. Handles all plain types except structure types
799 // (see https://www.w3.org/TR/WGSL/#plain-types-section).
800 std::string to_wgsl_type(const Context& context, const Type& raw,
801 const Layout* layout = nullptr, bool forceHighPrecision=false) {
802 const Type& type = raw.resolve().scalarTypeForLiteral();
803 const bool f16Available = !context.fConfig->fSettings.fForceHighPrecision &&
804 !forceHighPrecision;
805
806 switch (type.typeKind()) {
807 case Type::TypeKind::kScalar:
808 return std::string(to_scalar_type(type, f16Available));
809
810 case Type::TypeKind::kAtomic:
811 SkASSERT(type.matches(*context.fTypes.fAtomicUInt));
812 return "atomic<u32>";
813
814 case Type::TypeKind::kVector: {
815 std::string_view ct = to_scalar_type(type.componentType(), f16Available);
816 return String::printf("vec%d<%.*s>", type.columns(), (int)ct.length(), ct.data());
817 }
818 case Type::TypeKind::kMatrix: {
819 std::string_view ct = to_scalar_type(type.componentType(), f16Available);
820 return String::printf("mat%dx%d<%.*s>",
821 type.columns(), type.rows(), (int)ct.length(), ct.data());
822 }
823 case Type::TypeKind::kArray: {
824 std::string result = "array<" + to_wgsl_type(context, type.componentType(), layout);
825 if (!type.isUnsizedArray()) {
826 result += ", ";
827 result += std::to_string(type.columns());
828 }
829 return result + '>';
830 }
831 case Type::TypeKind::kTexture: {
832 if (type.matches(*context.fTypes.fWriteOnlyTexture2D)) {
833 std::string result = "texture_storage_2d<";
834 // Write-only storage texture types require a pixel format, which is in the layout.
835 SkASSERT(layout);
836 LayoutFlags pixelFormat = layout->fFlags & LayoutFlag::kAllPixelFormats;
837 switch (pixelFormat.value()) {
838 case (int)LayoutFlag::kRGBA8:
839 return result + "rgba8unorm, write>";
840
841 case (int)LayoutFlag::kRGBA32F:
842 return result + "rgba32float, write>";
843
844 case (int)LayoutFlag::kR32F:
845 return result + "r32float, write>";
846
847 default:
848 // The front-end should have rejected this.
849 return result + "write>";
850 }
851 }
852 if (type.matches(*context.fTypes.fReadOnlyTexture2D)) {
853 return "texture_2d<f32>";
854 }
855 break;
856 }
857 default:
858 break;
859 }
860 return std::string(type.name());
861 }
862
863 std::string to_ptr_type(const Context& context,
864 const Type& type,
865 const Layout* layout,
866 PtrAddressSpace addressSpace = PtrAddressSpace::kFunction) {
867 return "ptr<" + std::string(address_space_to_str(addressSpace)) + ", " +
868 to_wgsl_type(context, type, layout) + '>';
869 }
870
871 std::string_view wgsl_builtin_name(WGSLCodeGenerator::Builtin builtin) {
872 using Builtin = WGSLCodeGenerator::Builtin;
873 switch (builtin) {
874 case Builtin::kVertexIndex:
875 return "@builtin(vertex_index)";
876 case Builtin::kInstanceIndex:
877 return "@builtin(instance_index)";
878 case Builtin::kPosition:
879 return "@builtin(position)";
880 case Builtin::kLastFragColor:
881 return "@color(0)";
882 case Builtin::kFrontFacing:
883 return "@builtin(front_facing)";
884 case Builtin::kSampleIndex:
885 return "@builtin(sample_index)";
886 case Builtin::kFragDepth:
887 return "@builtin(frag_depth)";
888 case Builtin::kSampleMask:
889 case Builtin::kSampleMaskIn:
890 return "@builtin(sample_mask)";
891 case Builtin::kLocalInvocationId:
892 return "@builtin(local_invocation_id)";
893 case Builtin::kLocalInvocationIndex:
894 return "@builtin(local_invocation_index)";
895 case Builtin::kGlobalInvocationId:
896 return "@builtin(global_invocation_id)";
897 case Builtin::kWorkgroupId:
898 return "@builtin(workgroup_id)";
899 case Builtin::kNumWorkgroups:
900 return "@builtin(num_workgroups)";
901 default:
902 break;
903 }
904
905 SkDEBUGFAIL("unsupported builtin");
906 return "unsupported";
907 }
908
909 std::string_view wgsl_builtin_type(WGSLCodeGenerator::Builtin builtin, const Context& context) {
910 using Builtin = WGSLCodeGenerator::Builtin;
911 switch (builtin) {
912 case Builtin::kVertexIndex:
913 return "u32";
914 case Builtin::kInstanceIndex:
915 return "u32";
916 case Builtin::kPosition:
917 return "vec4<f32>";
918 case Builtin::kLastFragColor:
919 // The last frag color is declared as a half4 in SkSL, so its type depends on f16
920 // being available or not.
921 return context.fConfig->fSettings.fForceHighPrecision ? "vec4<f32>" : "vec4<f16>";
922 case Builtin::kFrontFacing:
923 return "bool";
924 case Builtin::kSampleIndex:
925 return "u32";
926 case Builtin::kFragDepth:
927 return "f32";
928 case Builtin::kSampleMask:
929 return "u32";
930 case Builtin::kSampleMaskIn:
931 return "u32";
932 case Builtin::kLocalInvocationId:
933 return "vec3<u32>";
934 case Builtin::kLocalInvocationIndex:
935 return "u32";
936 case Builtin::kGlobalInvocationId:
937 return "vec3<u32>";
938 case Builtin::kWorkgroupId:
939 return "vec3<u32>";
940 case Builtin::kNumWorkgroups:
941 return "vec3<u32>";
942 default:
943 break;
944 }
945
946 SkDEBUGFAIL("unsupported builtin");
947 return "unsupported";
948 }
949
950 // Some built-in variables have a type that differs from their SkSL counterpart (e.g. signed vs
951 // unsigned integer). We handle these cases with an explicit type conversion during a variable
952 // reference. Returns the WGSL type of the conversion target if conversion is needed, otherwise
953 // returns std::nullopt.
954 std::optional<std::string_view> needs_builtin_type_conversion(const Variable& v) {
955 switch (v.layout().fBuiltin) {
956 case SK_VERTEXID_BUILTIN:
957 case SK_INSTANCEID_BUILTIN:
958 return {"i32"};
959 default:
960 break;
961 }
962 return std::nullopt;
963 }
964
965 // Map a SkSL builtin flag to a WGSL builtin kind. Returns std::nullopt if `builtin` is not
966 // not supported for WGSL.
967 //
968 // Also see //src/sksl/sksl_vert.sksl and //src/sksl/sksl_frag.sksl for supported built-ins.
969 std::optional<WGSLCodeGenerator::Builtin> builtin_from_sksl_name(int builtin) {
970 using Builtin = WGSLCodeGenerator::Builtin;
971 switch (builtin) {
972 case SK_POSITION_BUILTIN:
973 [[fallthrough]];
974 case SK_FRAGCOORD_BUILTIN:
975 return Builtin::kPosition;
976 case SK_VERTEXID_BUILTIN:
977 return Builtin::kVertexIndex;
978 case SK_INSTANCEID_BUILTIN:
979 return Builtin::kInstanceIndex;
980 case SK_LASTFRAGCOLOR_BUILTIN:
981 return Builtin::kLastFragColor;
982 case SK_CLOCKWISE_BUILTIN:
983 // TODO(skbug.com/40044196): While `front_facing` is the corresponding built-in, it does not
984 // imply a particular winding order. We correctly compute the face orientation based
985 // on how Skia configured the render pipeline for all references to this built-in
986 // variable (see `SkSL::Program::Interface::fRTFlipUniform`).
987 return Builtin::kFrontFacing;
988 case SK_SAMPLEMASKIN_BUILTIN:
989 return Builtin::kSampleMaskIn;
990 case SK_SAMPLEMASK_BUILTIN:
991 return Builtin::kSampleMask;
992 case SK_NUMWORKGROUPS_BUILTIN:
993 return Builtin::kNumWorkgroups;
994 case SK_WORKGROUPID_BUILTIN:
995 return Builtin::kWorkgroupId;
996 case SK_LOCALINVOCATIONID_BUILTIN:
997 return Builtin::kLocalInvocationId;
998 case SK_GLOBALINVOCATIONID_BUILTIN:
999 return Builtin::kGlobalInvocationId;
1000 case SK_LOCALINVOCATIONINDEX_BUILTIN:
1001 return Builtin::kLocalInvocationIndex;
1002 default:
1003 break;
1004 }
1005 return std::nullopt;
1006 }
1007
1008 const char* delimiter_to_str(WGSLCodeGenerator::Delimiter delimiter) {
1009 using Delim = WGSLCodeGenerator::Delimiter;
1010 switch (delimiter) {
1011 case Delim::kComma:
1012 return ",";
1013 case Delim::kSemicolon:
1014 return ";";
1015 case Delim::kNone:
1016 default:
1017 break;
1018 }
1019 return "";
1020 }
1021
1022 bool all_arguments_constant(const ExpressionArray& arguments) {
1023 // Returns true if all arguments in the ExpressionArray are compile-time constants. If we are
1024 // calling an intrinsic and all of its inputs are constant, but we didn't constant-fold it, this
1025 // generally indicates that constant-folding resulted in an infinity or nan. The WGSL compiler
1026 // will reject such an expression with a compile-time error. We can dodge the error, taking on
1027 // the risk of indeterminate behavior instead, by replacing one of the constant values with a
1028 // scratch let-variable. (skbug.com/40045457)
1029 for (const std::unique_ptr<Expression>& arg : arguments) {
1030 if (!ConstantFolder::GetConstantValueOrNull(*arg)) {
1031 return false;
1032 }
1033 }
1034 return true;
1035 }
1036
1037 bool is_nontrivial_expression(const Expression& expr) {
1038 // We consider a "trivial expression" one which we can repeat multiple times in the output
1039 // without being dangerous or spammy. We avoid emitting temporary variables for very trivial
1040 // expressions: literals, unadorned variable references, or constant vectors.
1041 if (expr.is<VariableReference>() || expr.is<Literal>()) {
1042 // Variables and literals are trivial; adding a let-declaration won't simplify anything.
1043 return false;
1044 }
1045 if (expr.type().isVector() && Analysis::IsConstantExpression(expr)) {
1046 // Compile-time constant vectors are also considered trivial; they're short and sweet.
1047 return false;
1048 }
1049 return true;
1050 }
1051
1052 // FunctionDependencyResolver visits the IR tree rooted at a particular function definition and
1053 // computes that function's dependencies on pipeline stage IO parameters. These are later used to
1054 // synthesize arguments when writing out function definitions.
1055 class FunctionDependencyResolver : public ProgramVisitor {
1056 public:
1057 using Deps = WGSLFunctionDependencies;
1058 using DepsMap = WGSLCodeGenerator::ProgramRequirements::DepsMap;
1059
1060 FunctionDependencyResolver(const Program* p,
1061 const FunctionDeclaration* f,
1062 DepsMap* programDependencyMap)
1063 : fProgram(p), fFunction(f), fDependencyMap(programDependencyMap) {}
1064
1065 Deps resolve() {
1066 fDeps = WGSLFunctionDependency::kNone;
1067 this->visit(*fProgram);
1068 return fDeps;
1069 }
1070
1071 private:
1072 bool visitProgramElement(const ProgramElement& p) override {
1073 // Only visit the program that matches the requested function.
1074 if (p.is<FunctionDefinition>() && &p.as<FunctionDefinition>().declaration() == fFunction) {
1075 return ProgramVisitor::visitProgramElement(p);
1076 }
1077 // Continue visiting other program elements.
1078 return false;
1079 }
1080
1081 bool visitExpression(const Expression& e) override {
1082 if (e.is<VariableReference>()) {
1083 const VariableReference& v = e.as<VariableReference>();
1084 if (v.variable()->storage() == Variable::Storage::kGlobal) {
1085 ModifierFlags flags = v.variable()->modifierFlags();
1086 if (flags & ModifierFlag::kIn) {
1087 fDeps |= WGSLFunctionDependency::kPipelineInputs;
1088 }
1089 if (flags & ModifierFlag::kOut) {
1090 fDeps |= WGSLFunctionDependency::kPipelineOutputs;
1091 }
1092 }
1093 } else if (e.is<FunctionCall>()) {
1094 // The current function that we're processing (`fFunction`) inherits the dependencies of
1095 // functions that it makes calls to, because the pipeline stage IO parameters need to be
1096 // passed down as an argument.
1097 const FunctionCall& callee = e.as<FunctionCall>();
1098
1099 // Don't process a function again if we have already resolved it.
1100 Deps* found = fDependencyMap->find(&callee.function());
1101 if (found) {
1102 fDeps |= *found;
1103 } else {
1104 // Store the dependencies that have been discovered for the current function so far.
1105 // If `callee` directly or indirectly calls the current function, then this value
1106 // will prevent an infinite recursion.
1107 fDependencyMap->set(fFunction, fDeps);
1108
1109 // Separately traverse the called function's definition and determine its
1110 // dependencies.
1111 FunctionDependencyResolver resolver(fProgram, &callee.function(), fDependencyMap);
1112 Deps calleeDeps = resolver.resolve();
1113
1114 // Store the callee's dependencies in the global map to avoid processing
1115 // the function again for future calls.
1116 fDependencyMap->set(&callee.function(), calleeDeps);
1117
1118 // Add to the current function's dependencies.
1119 fDeps |= calleeDeps;
1120 }
1121 }
1122 return ProgramVisitor::visitExpression(e);
1123 }
1124
1125 const Program* const fProgram;
1126 const FunctionDeclaration* const fFunction;
1127 DepsMap* const fDependencyMap;
1128 Deps fDeps = WGSLFunctionDependency::kNone;
1129 };
1130
1131 WGSLCodeGenerator::ProgramRequirements resolve_program_requirements(const Program* program) {
1132 WGSLCodeGenerator::ProgramRequirements requirements;
1133
1134 for (const ProgramElement* e : program->elements()) {
1135 switch (e->kind()) {
1136 case ProgramElement::Kind::kFunction: {
1137 const FunctionDeclaration& decl = e->as<FunctionDefinition>().declaration();
1138
1139 FunctionDependencyResolver resolver(program, &decl, &requirements.fDependencies);
1140 requirements.fDependencies.set(&decl, resolver.resolve());
1141 break;
1142 }
1143 case ProgramElement::Kind::kGlobalVar: {
1144 const GlobalVarDeclaration& decl = e->as<GlobalVarDeclaration>();
1145 if (decl.varDeclaration().var()->modifierFlags().isPixelLocal()) {
1146 requirements.fPixelLocalExtension = true;
1147 }
1148 break;
1149 }
1150 default:
1151 break;
1152 }
1153 }
1154
1155 return requirements;
1156 }
1157
1158 void collect_pipeline_io_vars(const Program* program,
1159 TArray<const Variable*>* ioVars,
1160 ModifierFlag ioType) {
1161 for (const ProgramElement* e : program->elements()) {
1162 if (e->is<GlobalVarDeclaration>()) {
1163 const Variable* v = e->as<GlobalVarDeclaration>().varDeclaration().var();
1164 if (v->modifierFlags() & ioType) {
1165 ioVars->push_back(v);
1166 }
1167 } else if (e->is<InterfaceBlock>()) {
1168 const Variable* v = e->as<InterfaceBlock>().var();
1169 if (v->modifierFlags() & ioType) {
1170 ioVars->push_back(v);
1171 }
1172 }
1173 }
1174 }
1175
1176 bool is_in_global_uniforms(const Variable& var) {
1177 return var.storage() == VariableStorage::kGlobal &&
1178 var.modifierFlags().isUniform() &&
1179 !var.type().isOpaque() &&
1180 !var.interfaceBlock();
1181 }
1182
1183 } // namespace
1184
1185 class WGSLCodeGenerator::LValue {
1186 public:
1187 virtual ~LValue() = default;
1188
1189 // Returns a WGSL expression that loads from the lvalue with no side effects.
1190 // (e.g. `array[index].field`)
1191 virtual std::string load() = 0;
1192
1193 // Returns a WGSL statement that stores into the lvalue with no side effects.
1194 // (e.g. `array[index].field = the_passed_in_value_string;`)
1195 virtual std::string store(const std::string& value) = 0;
1196 };
1197
1198 class WGSLCodeGenerator::PointerLValue : public WGSLCodeGenerator::LValue {
1199 public:
1200 // `name` must be a WGSL expression with no side-effects, which we can safely take the address
1201 // of. (e.g. `array[index].field` would be valid, but `array[Func()]` or `vector.x` are not.)
1202 PointerLValue(std::string name) : fName(std::move(name)) {}
1203
1204 std::string load() override {
1205 return fName;
1206 }
1207
1208 std::string store(const std::string& value) override {
1209 return fName + " = " + value + ";";
1210 }
1211
1212 private:
1213 std::string fName;
1214 };
1215
1216 class WGSLCodeGenerator::VectorComponentLValue : public WGSLCodeGenerator::LValue {
1217 public:
1218 // `name` must be a WGSL expression with no side-effects that points to a single component of a
1219 // WGSL vector.
1220 VectorComponentLValue(std::string name) : fName(std::move(name)) {}
1221
1222 std::string load() override {
1223 return fName;
1224 }
1225
1226 std::string store(const std::string& value) override {
1227 return fName + " = " + value + ";";
1228 }
1229
1230 private:
1231 std::string fName;
1232 };
1233
1234 class WGSLCodeGenerator::SwizzleLValue : public WGSLCodeGenerator::LValue {
1235 public:
1236 // `name` must be a WGSL expression with no side-effects that points to a WGSL vector.
1237 SwizzleLValue(const Context& ctx, std::string name, const Type& t, const ComponentArray& c)
1238 : fContext(ctx)
1239 , fName(std::move(name))
1240 , fType(t)
1241 , fComponents(c) {
1242 // If the component array doesn't cover the entire value, we need to create masks for
1243 // writing back into the lvalue. For example, if the type is vec4 and the component array
1244 // holds `zx`, a GLSL assignment would look like:
1245 // name.zx = new_value;
1246 //
1247 // The equivalent WGSL assignment statement would look like:
1248 // name = vec4<f32>(new_value, name.xw).yzxw;
1249 //
1250 // This replaces name.zy with new_value.xy, and leaves name.xw at their original values.
1251 // By convention, we always put the new value first and the original values second; it might
1252 // be possible to find better arrangements which simplify the assignment overall, but we
1253 // don't attempt this.
1254 int fullSlotCount = fType.slotCount();
1255 SkASSERT(fullSlotCount <= 4);
1256
1257 // First, see which components are used.
1258 // The assignment swizzle must not reuse components.
1259 bool used[4] = {};
1260 for (int8_t component : fComponents) {
1261 SkASSERT(!used[component]);
1262 used[component] = true;
1263 }
1264
1265 // Any untouched components will need to be fetched from the original value.
1266 for (int index = 0; index < fullSlotCount; ++index) {
1267 if (!used[index]) {
1268 fUntouchedComponents.push_back(index);
1269 }
1270 }
1271
1272 // The reintegration swizzle needs to move the components back into their proper slots.
1273 fReintegrationSwizzle.resize(fullSlotCount);
1274 int reintegrateIndex = 0;
1275
1276 // This refills the untouched slots with the original values.
1277 auto refillUntouchedSlots = [&] {
1278 for (int index = 0; index < fullSlotCount; ++index) {
1279 if (!used[index]) {
1280 fReintegrationSwizzle[index] = reintegrateIndex++;
1281 }
1282 }
1283 };
1284
1285 // This places the new-value components into the proper slots.
1286 auto insertNewValuesIntoSlots = [&] {
1287 for (int index = 0; index < fComponents.size(); ++index) {
1288 fReintegrationSwizzle[fComponents[index]] = reintegrateIndex++;
1289 }
1290 };
1291
1292 // When reintegrating the untouched and new values, if the `x` slot is overwritten, we
1293 // reintegrate the new value first. Otherwise, we reintegrate the original value first.
1294 // This increases our odds of getting an identity swizzle for the reintegration.
1295 if (used[0]) {
1296 fReintegrateNewValueFirst = true;
1297 insertNewValuesIntoSlots();
1298 refillUntouchedSlots();
1299 } else {
1300 fReintegrateNewValueFirst = false;
1301 refillUntouchedSlots();
1302 insertNewValuesIntoSlots();
1303 }
1304 }
1305
1306 std::string load() override {
1307 return fName + "." + Swizzle::MaskString(fComponents);
1308 }
1309
1310 std::string store(const std::string& value) override {
1311 // `variable = `
1312 std::string result = fName;
1313 result += " = ";
1314
1315 if (fUntouchedComponents.empty()) {
1316 // `(new_value);`
1317 result += '(';
1318 result += value;
1319 result += ")";
1320 } else if (fReintegrateNewValueFirst) {
1321 // `vec4<f32>((new_value), `
1322 result += to_wgsl_type(fContext, fType);
1323 result += "((";
1324 result += value;
1325 result += "), ";
1326
1327 // `variable.yz)`
1328 result += fName;
1329 result += '.';
1330 result += Swizzle::MaskString(fUntouchedComponents);
1331 result += ')';
1332 } else {
1333 // `vec4<f32>(variable.yz`
1334 result += to_wgsl_type(fContext, fType);
1335 result += '(';
1336 result += fName;
1337 result += '.';
1338 result += Swizzle::MaskString(fUntouchedComponents);
1339
1340 // `, (new_value))`
1341 result += ", (";
1342 result += value;
1343 result += "))";
1344 }
1345
1346 if (!Swizzle::IsIdentity(fReintegrationSwizzle)) {
1347 // `.wzyx`
1348 result += '.';
1349 result += Swizzle::MaskString(fReintegrationSwizzle);
1350 }
1351
1352 return result + ';';
1353 }
1354
1355 private:
1356 const Context& fContext;
1357 std::string fName;
1358 const Type& fType;
1359 ComponentArray fComponents;
1360 ComponentArray fUntouchedComponents;
1361 ComponentArray fReintegrationSwizzle;
1362 bool fReintegrateNewValueFirst = false;
1363 };
1364
1365 class WGSLCodeGenerator::AutoConstEvalWorkaround {
1366 public:
1367 AutoConstEvalWorkaround(WGSLCodeGenerator* generator, const Expression& parent)
1368 : fGenerator(generator)
1369 , fOriginalValue(generator->fNeedsConstEvalWorkaround) {
1370 // Each scope can apply the workaround separately from the parent scope, so default to
1371 // not requiring it
1372 fGenerator->fNeedsConstEvalWorkaround = false;
1373
1374 // Intrinsic function calls and operators can be const-evaluated by the WGSL compiler,
1375 // which may cause it complain if said evaluation would produce non-finite values.
1376 if (parent.kind() == ExpressionKind::kFunctionCall) {
1377 const FunctionCall& call = parent.as<FunctionCall>();
1378 // User-defined functions can never be const-evaluated.
1379 if (call.function().isIntrinsic() && all_arguments_constant(call.arguments())) {
1380 fGenerator->fNeedsConstEvalWorkaround = true;
1381 }
1382 } else if (parent.kind() == ExpressionKind::kBinary) {
1383 const BinaryExpression& op = parent.as<BinaryExpression>();
1384 fGenerator->fNeedsConstEvalWorkaround =
1385 op_needs_workaround(*op.left(), *op.right(), op.getOperator().kind());
1386
1387 }
1388 }
1389
1390 ~AutoConstEvalWorkaround() {
1391 fGenerator->fNeedsConstEvalWorkaround = fOriginalValue;
1392 }
1393
1394 private:
1395 static bool op_needs_workaround(const Expression& l, const Expression& r, OperatorKind op) {
1396 // Only ops that produce overflows or non-finite values need to be worked round: +,-,*,/
1397 switch (op) {
1398 case Operator::Kind::MINUS:
1399 case Operator::Kind::PLUS:
1400 case Operator::Kind::STAR:
1401 case Operator::Kind::SLASH:
1402 return ConstantFolder::GetConstantValueOrNull(l) &&
1403 ConstantFolder::GetConstantValueOrNull(r);
1404 default:
1405 return false;
1406 }
1407 }
1408
1409 WGSLCodeGenerator* fGenerator;
1410 bool fOriginalValue;
1411 };
1412
1413 bool WGSLCodeGenerator::generateCode() {
1414 // The resources of a WGSL program are structured in the following way:
1415 // - Stage attribute inputs and outputs are bundled inside synthetic structs called
1416 // VSIn/VSOut/FSIn/FSOut/CSIn.
1417 // - All uniform and storage type resources are declared in global scope.
1418 this->preprocessProgram();
1419
1420 {
1421 AutoOutputStream outputToHeader(this, &fHeader, &fIndentation);
1422 this->writeEnables();
1423 this->writeStageInputStruct();
1424 this->writeStageOutputStruct();
1425 this->writeUniformsAndBuffers();
1426 this->writeNonBlockUniformsForTests();
1427 }
1428 StringStream body;
1429 {
1430 // Emit the program body.
1431 AutoOutputStream outputToBody(this, &body, &fIndentation);
1432 const FunctionDefinition* mainFunc = nullptr;
1433 for (const ProgramElement* e : fProgram.elements()) {
1434 this->writeProgramElement(*e);
1435
1436 if (e->is<FunctionDefinition>()) {
1437 const FunctionDefinition& func = e->as<FunctionDefinition>();
1438 if (func.declaration().isMain()) {
1439 mainFunc = &func;
1440 }
1441 }
1442 }
1443
1444 // At the bottom of the program body, emit the entrypoint function.
1445 // The entrypoint relies on state that has been collected while we emitted the rest of the
1446 // program, so it's important to do it last to make sure we don't miss anything.
1447 if (mainFunc) {
1448 this->writeEntryPoint(*mainFunc);
1449 }
1450 }
1451
1452 write_stringstream(fHeader, *fOut);
1453 write_stringstream(body, *fOut);
1454
1455 this->writeUniformPolyfills();
1456
1457 return fContext.fErrors->errorCount() == 0;
1458 }
1459
1460 void WGSLCodeGenerator::writeUniformPolyfills() {
1461 // If we didn't encounter any uniforms that need polyfilling, there is nothing to do.
1462 if (fFieldPolyfillMap.empty()) {
1463 return;
1464 }
1465
1466 // We store the list of polyfilled fields as pointers in a hash-map, so the order can be
1467 // inconsistent across runs. For determinism, we sort the polyfilled objects by name here.
1468 TArray<const FieldPolyfillMap::Pair*> orderedFields;
1469 orderedFields.reserve_exact(fFieldPolyfillMap.count());
1470
1471 fFieldPolyfillMap.foreach([&](const FieldPolyfillMap::Pair& pair) {
1472 orderedFields.push_back(&pair);
1473 });
1474
1475 std::sort(orderedFields.begin(),
1476 orderedFields.end(),
1477 [](const FieldPolyfillMap::Pair* a, const FieldPolyfillMap::Pair* b) {
1478 return a->second.fReplacementName < b->second.fReplacementName;
1479 });
1480
1481 THashSet<const Type*> writtenArrayElementPolyfill;
1482 bool writtenUniformMatrixPolyfill[2][5][5] = {}; // {h,f} x m[column][row] for each matrix type
1483 bool writtenUniformRowPolyfill[2][5] = {}; // {h,f} x for each matrix row-size
1484 bool anyFieldAccessed = false;
1485 for (const FieldPolyfillMap::Pair* pair : orderedFields) {
1486 const auto& [field, info] = *pair;
1487 const Type* fieldType = field->fType;
1488 const Layout* fieldLayout = &field->fLayout;
1489
1490 if (info.fIsArray) {
1491 fieldType = &fieldType->componentType();
1492 if (!writtenArrayElementPolyfill.contains(fieldType)) {
1493 writtenArrayElementPolyfill.add(fieldType);
1494 this->write("struct _skArrayElement_");
1495 this->write(fieldType->abbreviatedName());
1496 this->writeLine(" {");
1497
1498 if (info.fIsMatrix) {
1499 // Create a struct representing the array containing std140-padded matrices.
1500 this->write(" e : _skMatrix");
1501 this->write(std::to_string(fieldType->columns()));
1502 this->write(std::to_string(fieldType->rows()));
1503 this->writeLine(type_is_low_precision(*fieldType, fContext) ? "h" : "f");
1504 } else {
1505 // Create a struct representing the array with extra padding between elements.
1506 this->write(" @align(16) e : ");
1507 this->writeLine(to_wgsl_type(fContext, *fieldType, fieldLayout));
1508 }
1509 this->writeLine("};");
1510 }
1511 }
1512
1513 if (info.fIsMatrix) {
1514 // Create structs representing the matrix as an array of vectors, whether or not the
1515 // matrix is ever accessed by the SkSL. (The struct itself is mentioned in the list of
1516 // uniforms.)
1517 const bool useF16 = type_is_low_precision(*fieldType, fContext);
1518 int t = useF16 ? 0 : 1;
1519 int c = fieldType->columns();
1520 int r = fieldType->rows();
1521 if (!writtenUniformRowPolyfill[t][r]) {
1522 writtenUniformRowPolyfill[t][r] = true;
1523
1524 this->write("struct _skRow");
1525 this->write(std::to_string(r));
1526 this->write(useF16 ? "h" : "f");
1527 this->writeLine(" {");
1528 this->write(" @align(16) r : vec");
1529 this->write(std::to_string(r));
1530 this->write("<");
1531 this->write(to_wgsl_type(fContext, fieldType->componentType(), fieldLayout));
1532 this->writeLine(">");
1533 this->writeLine("};");
1534 }
1535
1536 if (!writtenUniformMatrixPolyfill[t][c][r]) {
1537 writtenUniformMatrixPolyfill[t][c][r] = true;
1538
1539 this->write("struct _skMatrix");
1540 this->write(std::to_string(c));
1541 this->write(std::to_string(r));
1542 this->write(useF16 ? "h" : "f");
1543 this->writeLine(" {");
1544 this->write(" c : array<_skRow");
1545 this->write(std::to_string(r));
1546 this->write(useF16 ? "h" : "f");
1547 this->write(", ");
1548 this->write(std::to_string(c));
1549 this->writeLine(">");
1550 this->writeLine("};");
1551 }
1552 }
1553
1554 // We create a polyfill variable only if the uniform was actually accessed.
1555 if (!info.fWasAccessed) {
1556 continue;
1557 }
1558 anyFieldAccessed = true;
1559 this->write("var<private> ");
1560 this->write(info.fReplacementName);
1561 this->write(": ");
1562
1563 const Type& interfaceBlockType = info.fInterfaceBlock->var()->type();
1564 if (interfaceBlockType.isArray()) {
1565 this->write("array<");
1566 this->write(to_wgsl_type(fContext, *field->fType, fieldLayout));
1567 this->write(", ");
1568 this->write(std::to_string(interfaceBlockType.columns()));
1569 this->write(">");
1570 } else {
1571 this->write(to_wgsl_type(fContext, *field->fType, fieldLayout));
1572 }
1573 this->writeLine(";");
1574 }
1575
1576 // If no fields were actually accessed, _skInitializePolyfilledUniforms will not be called and
1577 // we can avoid emitting an empty, dead function.
1578 if (!anyFieldAccessed) {
1579 return;
1580 }
1581
1582 this->writeLine("fn _skInitializePolyfilledUniforms() {");
1583 ++fIndentation;
1584
1585 for (const FieldPolyfillMap::Pair* pair : orderedFields) {
1586 // Only initialize a polyfill global if the uniform was actually accessed.
1587 const auto& [field, info] = *pair;
1588 if (!info.fWasAccessed) {
1589 continue;
1590 }
1591
1592 // Synthesize the name of this uniform variable
1593 std::string_view instanceName = info.fInterfaceBlock->instanceName();
1594 const Type& interfaceBlockType = info.fInterfaceBlock->var()->type();
1595 if (instanceName.empty()) {
1596 instanceName = fInterfaceBlockNameMap[&interfaceBlockType.componentType()];
1597 }
1598
1599 // Initialize the global variable associated with this uniform.
1600 // If the interface block is arrayed, the associated global will be arrayed as well.
1601 int numIBElements = interfaceBlockType.isArray() ? interfaceBlockType.columns() : 1;
1602 for (int ibIdx = 0; ibIdx < numIBElements; ++ibIdx) {
1603 this->write(info.fReplacementName);
1604 if (interfaceBlockType.isArray()) {
1605 this->write("[");
1606 this->write(std::to_string(ibIdx));
1607 this->write("]");
1608 }
1609 this->write(" = ");
1610
1611 const Type* fieldType = field->fType;
1612 const Layout* fieldLayout = &field->fLayout;
1613
1614 int numArrayElements;
1615 if (info.fIsArray) {
1616 this->write(to_wgsl_type(fContext, *fieldType, fieldLayout));
1617 this->write("(");
1618 numArrayElements = fieldType->columns();
1619 fieldType = &fieldType->componentType();
1620 } else {
1621 numArrayElements = 1;
1622 }
1623
1624 auto arraySeparator = String::Separator();
1625 for (int arrayIdx = 0; arrayIdx < numArrayElements; arrayIdx++) {
1626 this->write(arraySeparator());
1627
1628 std::string fieldName{instanceName};
1629 if (interfaceBlockType.isArray()) {
1630 fieldName += '[';
1631 fieldName += std::to_string(ibIdx);
1632 fieldName += ']';
1633 }
1634 fieldName += '.';
1635 fieldName += this->assembleName(field->fName);
1636
1637 if (info.fIsArray) {
1638 fieldName += '[';
1639 fieldName += std::to_string(arrayIdx);
1640 fieldName += "].e";
1641 }
1642
1643 if (info.fIsMatrix) {
1644 this->write(to_wgsl_type(fContext, *fieldType, fieldLayout));
1645 this->write("(");
1646 int numColumns = fieldType->columns();
1647 auto matrixSeparator = String::Separator();
1648 for (int column = 0; column < numColumns; column++) {
1649 this->write(matrixSeparator());
1650 this->write(fieldName);
1651 this->write(".c[");
1652 this->write(std::to_string(column));
1653 this->write("].r");
1654 }
1655 this->write(")");
1656 } else {
1657 this->write(fieldName);
1658 }
1659 }
1660
1661 if (info.fIsArray) {
1662 this->write(")");
1663 }
1664
1665 this->writeLine(";");
1666 }
1667 }
1668
1669 --fIndentation;
1670 this->writeLine("}");
1671 }
1672
1673
1674 void WGSLCodeGenerator::preprocessProgram() {
1675 fRequirements = resolve_program_requirements(&fProgram);
1676 collect_pipeline_io_vars(&fProgram, &fPipelineInputs, ModifierFlag::kIn);
1677 collect_pipeline_io_vars(&fProgram, &fPipelineOutputs, ModifierFlag::kOut);
1678 }
1679
1680 void WGSLCodeGenerator::write(std::string_view s) {
1681 if (s.empty()) {
1682 return;
1683 }
1684 if (fAtLineStart && fPrettyPrint == PrettyPrint::kYes) {
1685 for (int i = 0; i < fIndentation; i++) {
1686 fOut->writeText(" ");
1687 }
1688 }
1689 fOut->writeText(std::string(s).c_str());
1690 fAtLineStart = false;
1691 }
1692
1693 void WGSLCodeGenerator::writeLine(std::string_view s) {
1694 this->write(s);
1695 fOut->writeText("\n");
1696 fAtLineStart = true;
1697 }
1698
1699 void WGSLCodeGenerator::finishLine() {
1700 if (!fAtLineStart) {
1701 this->writeLine();
1702 }
1703 }
1704
1705 std::string WGSLCodeGenerator::assembleName(std::string_view name) {
1706 if (name.empty()) {
1707 // WGSL doesn't allow anonymous function parameters.
1708 return "_skAnonymous" + std::to_string(fScratchCount++);
1709 }
1710 // Add `R_` before reserved names to avoid any potential reserved-word conflict.
1711 return (skstd::starts_with(name, "_sk") ||
1712 skstd::starts_with(name, "R_") ||
1713 is_reserved_word(name))
1714 ? std::string("R_") + std::string(name)
1715 : std::string(name);
1716 }
1717
1718 void WGSLCodeGenerator::writeVariableDecl(const Layout& layout,
1719 const Type& type,
1720 std::string_view name,
1721 Delimiter delimiter) {
1722 this->write(this->assembleName(name));
1723 this->write(": " + to_wgsl_type(fContext, type, &layout));
1724 this->writeLine(delimiter_to_str(delimiter));
1725 }
1726
1727 void WGSLCodeGenerator::writePipelineIODeclaration(const Layout& layout,
1728 const Type& type,
1729 ModifierFlags modifiers,
1730 std::string_view name,
1731 Delimiter delimiter) {
1732 // In WGSL, an entry-point IO parameter is "one of either a built-in value or assigned a
1733 // location". However, some SkSL declarations, specifically sk_FragColor, can contain both a
1734 // location and a builtin modifier. In addition, WGSL doesn't have a built-in equivalent for
1735 // sk_FragColor as it relies on the user-defined location for a render target.
1736 //
1737 // Instead of special-casing sk_FragColor, we just give higher precedence to a location modifier
1738 // if a declaration happens to both have a location and it's a built-in.
1739 //
1740 // Also see:
1741 // https://www.w3.org/TR/WGSL/#input-output-locations
1742 // https://www.w3.org/TR/WGSL/#attribute-location
1743 // https://www.w3.org/TR/WGSL/#builtin-inputs-outputs
1744 if (layout.fLocation >= 0) {
1745 this->writeUserDefinedIODecl(layout, type, modifiers, name, delimiter);
1746 return;
1747 }
1748 if (layout.fBuiltin >= 0) {
1749 if (layout.fBuiltin == SK_POINTSIZE_BUILTIN) {
1750 // WebGPU does not support the point-size builtin, but we silently replace it with a
1751 // global variable when it is used, instead of reporting an error.
1752 return;
1753 }
1754 auto builtin = builtin_from_sksl_name(layout.fBuiltin);
1755 if (builtin.has_value()) {
1756 // Builtin IO parameters should only have in/out modifiers, which are then implicit in
1757 // the generated WGSL, hence why writeBuiltinIODecl does not need them passed in.
1758 SkASSERT(!(modifiers & ~(ModifierFlag::kIn | ModifierFlag::kOut)));
1759 this->writeBuiltinIODecl(type, name, *builtin, delimiter);
1760 return;
1761 }
1762 }
1763 fContext.fErrors->error(Position(), "declaration '" + std::string(name) + "' is not supported");
1764 }
1765
1766 void WGSLCodeGenerator::writeUserDefinedIODecl(const Layout& layout,
1767 const Type& type,
1768 ModifierFlags flags,
1769 std::string_view name,
1770 Delimiter delimiter) {
1771 this->write("@location(" + std::to_string(layout.fLocation) + ") ");
1772
1773 // @blend_src is only allowed when doing dual-source blending, and only on color attachment 0.
1774 if (layout.fLocation == 0 && layout.fIndex >= 0 && fProgram.fInterface.fOutputSecondaryColor) {
1775 this->write("@blend_src(" + std::to_string(layout.fIndex) + ") ");
1776 }
1777
1778 // "User-defined IO of scalar or vector integer type must always be specified as
1779 // @interpolate(flat)" (see https://www.w3.org/TR/WGSL/#interpolation)
1780 if (flags.isFlat() || type.isInteger() ||
1781 (type.isVector() && type.componentType().isInteger())) {
1782 // We can use 'either' to hint to WebGPU that we don't care about the provoking vertex and
1783 // avoid any expensive shader or data rewriting to ensure 'first'. Skia has a long-standing
1784 // policy to only use flat shading when it's constant for a primitive so the vertex doesn't
1785 // matter. See https://www.w3.org/TR/WGSL/#interpolation-sampling-either
1786 this->write("@interpolate(flat, either) ");
1787 } else if (flags & ModifierFlag::kNoPerspective) {
1788 this->write("@interpolate(linear) ");
1789 }
1790
1791 this->writeVariableDecl(layout, type, name, delimiter);
1792 }
1793
1794 void WGSLCodeGenerator::writeBuiltinIODecl(const Type& type,
1795 std::string_view name,
1796 Builtin builtin,
1797 Delimiter delimiter) {
1798 this->write(wgsl_builtin_name(builtin));
1799 this->write(" ");
1800 this->write(this->assembleName(name));
1801 this->write(": ");
1802 this->write(wgsl_builtin_type(builtin, fContext));
1803 this->writeLine(delimiter_to_str(delimiter));
1804 }
1805
1806 void WGSLCodeGenerator::writeFunction(const FunctionDefinition& f) {
1807 const FunctionDeclaration& decl = f.declaration();
1808 fHasUnconditionalReturn = false;
1809 fConditionalScopeDepth = 0;
1810
1811 SkASSERT(!fAtFunctionScope);
1812 fAtFunctionScope = true;
1813
1814 // WGSL parameters are immutable and are considered as taking no storage, but SkSL parameters
1815 // are real variables. To work around this, we make var-based copies of parameters. It's
1816 // wasteful to make a copy of every single parameter--even if the compiler can eventually
1817 // optimize them all away, that takes time and generates bloated code. So, we only make
1818 // parameter copies if the variable is actually written-to.
1819 STArray<32, bool> paramNeedsDedicatedStorage;
1820 paramNeedsDedicatedStorage.push_back_n(decl.parameters().size(), true);
1821
1822 for (size_t index = 0; index < decl.parameters().size(); ++index) {
1823 const Variable& param = *decl.parameters()[index];
1824 if (param.type().isOpaque() || param.name().empty()) {
1825 // Opaque-typed or anonymous parameters don't need dedicated storage.
1826 paramNeedsDedicatedStorage[index] = false;
1827 continue;
1828 }
1829
1830 const ProgramUsage::VariableCounts counts = fProgram.fUsage->get(param);
1831 if ((param.modifierFlags() & ModifierFlag::kOut) || counts.fWrite == 0) {
1832 // Variables which are never written-to don't need dedicated storage.
1833 // Out-parameters are passed as pointers; the pointer itself is never modified, so
1834 // it doesn't need dedicated storage.
1835 paramNeedsDedicatedStorage[index] = false;
1836 }
1837 }
1838
1839 this->writeFunctionDeclaration(decl, paramNeedsDedicatedStorage);
1840 this->writeLine(" {");
1841 ++fIndentation;
1842
1843 // The parameters were given generic names like `_skParam1`, because WGSL parameters don't have
1844 // storage and are immutable. If mutability is required, we create variables here; otherwise, we
1845 // create properly-named `let` aliases.
1846 for (size_t index = 0; index < decl.parameters().size(); ++index) {
1847 if (paramNeedsDedicatedStorage[index]) {
1848 const Variable& param = *decl.parameters()[index];
1849 this->write("var ");
1850 this->write(this->assembleName(param.mangledName()));
1851 this->write(" = _skParam");
1852 this->write(std::to_string(index));
1853 this->writeLine(";");
1854 }
1855 }
1856
1857 this->writeBlock(f.body()->as<Block>());
1858
1859 // If fConditionalScopeDepth isn't zero, we have an unbalanced +1 or -1 when updating the depth.
1860 SkASSERT(fConditionalScopeDepth == 0);
1861 if (!fHasUnconditionalReturn && !f.declaration().returnType().isVoid()) {
1862 this->write("return ");
1863 this->write(to_wgsl_type(fContext, f.declaration().returnType()));
1864 this->writeLine("();");
1865 }
1866
1867 --fIndentation;
1868 this->writeLine("}");
1869
1870 SkASSERT(fAtFunctionScope);
1871 fAtFunctionScope = false;
1872 }
1873
1874 void WGSLCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& decl,
1875 SkSpan<const bool> paramNeedsDedicatedStorage) {
1876 this->write("fn ");
1877 if (decl.isMain()) {
1878 this->write("_skslMain(");
1879 } else {
1880 this->write(this->assembleName(decl.mangledName()));
1881 this->write("(");
1882 }
1883 auto separator = SkSL::String::Separator();
1884 if (this->writeFunctionDependencyParams(decl)) {
1885 separator(); // update the separator as parameters have been written
1886 }
1887 for (size_t index = 0; index < decl.parameters().size(); ++index) {
1888 this->write(separator());
1889
1890 const Variable& param = *decl.parameters()[index];
1891 if (param.type().isOpaque()) {
1892 SkASSERT(!paramNeedsDedicatedStorage[index]);
1893 if (param.type().isSampler()) {
1894 // Create parameters for both the texture and associated sampler.
1895 this->write(param.name());
1896 this->write(kTextureSuffix);
1897 this->write(": texture_2d<f32>, ");
1898 this->write(param.name());
1899 this->write(kSamplerSuffix);
1900 this->write(": sampler");
1901 } else {
1902 // Create a parameter for the opaque object.
1903 this->write(param.name());
1904 this->write(": ");
1905 this->write(to_wgsl_type(fContext, param.type(), &param.layout()));
1906 }
1907 } else {
1908 if (paramNeedsDedicatedStorage[index] || param.name().empty()) {
1909 // Create an unnamed parameter. If the parameter needs dedicated storage, it will
1910 // later be assigned a `var` in the function body. (If it's anonymous, a var isn't
1911 // needed.)
1912 this->write("_skParam");
1913 this->write(std::to_string(index));
1914 } else {
1915 // Use the name directly from the SkSL program.
1916 this->write(this->assembleName(param.name()));
1917 }
1918 this->write(": ");
1919 if (param.type().isUnsizedArray()) {
1920 // Creates a storage address space pointer for unsized array parameters.
1921 // The buffer the array resides in must be marked `readonly` to have the array
1922 // be used in function parameters, since access modes in wgsl must exactly match.
1923 this->write("ptr<storage, ");
1924 this->write(to_wgsl_type(fContext, param.type(), &param.layout()));
1925 this->write(", read>");
1926 } else if (param.modifierFlags() & ModifierFlag::kOut) {
1927 // Declare an "out" function parameter as a pointer.
1928 this->write(to_ptr_type(fContext, param.type(), &param.layout()));
1929 } else {
1930 this->write(to_wgsl_type(fContext, param.type(), &param.layout()));
1931 }
1932 }
1933 }
1934 this->write(")");
1935 if (!decl.returnType().isVoid()) {
1936 this->write(" -> ");
1937 this->write(to_wgsl_type(fContext, decl.returnType()));
1938 }
1939 }
1940
1941 void WGSLCodeGenerator::writeEntryPoint(const FunctionDefinition& main) {
1942 SkASSERT(main.declaration().isMain());
1943 const ProgramKind programKind = fProgram.fConfig->fKind;
1944
1945 bool initPolyfill = false;
1946 for (const auto& [field, info] : fFieldPolyfillMap) {
1947 if (info.fWasAccessed) {
1948 initPolyfill = true;
1949 break;
1950 }
1951 }
1952
1953 if (fGenSyntheticCode == IncludeSyntheticCode::kYes &&
1954 ProgramConfig::IsRuntimeShader(programKind)) {
1955 // Synthesize a basic entrypoint which just calls straight through to main.
1956 // This is only used by skslc and just needs to pass the WGSL validator; Skia won't ever
1957 // emit functions like this.
1958 this->write("@fragment fn main(@location(0) _coords: vec2<f32>) -> @location(0) ");
1959 this->write(to_wgsl_type(fContext, main.declaration().returnType()));
1960 this->writeLine(" {");
1961
1962 ++fIndentation;
1963 if (initPolyfill) {
1964 this->writeLine("_skInitializePolyfilledUniforms();");
1965 }
1966 this->writeLine("return _skslMain(_coords);");
1967 --fIndentation;
1968 this->writeLine("}");
1969 return;
1970 }
1971
1972 // The input and output parameters for a vertex/fragment stage entry point function have the
1973 // FSIn/FSOut/VSIn/VSOut/CSIn struct types that have been synthesized in generateCode(). An
1974 // entrypoint always has a predictable signature and acts as a trampoline to the user-defined
1975 // main function.
1976 if (ProgramConfig::IsVertex(programKind)) {
1977 this->write("@vertex");
1978 } else if (ProgramConfig::IsFragment(programKind)) {
1979 this->write("@fragment");
1980 } else if (ProgramConfig::IsCompute(programKind)) {
1981 this->write("@compute @workgroup_size(");
1982 this->write(std::to_string(fLocalSizeX));
1983 this->write(", ");
1984 this->write(std::to_string(fLocalSizeY));
1985 this->write(", ");
1986 this->write(std::to_string(fLocalSizeZ));
1987 this->write(")");
1988 } else {
1989 fContext.fErrors->error(Position(), "program kind not supported");
1990 return;
1991 }
1992
1993 this->write(" fn main(");
1994 // The stage input struct is a parameter passed to main().
1995 if (this->needsStageInputStruct()) {
1996 this->write("_stageIn: ");
1997 this->write(pipeline_struct_prefix(programKind));
1998 this->write("In");
1999 }
2000 // The stage output struct is returned from main().
2001 if (this->needsStageOutputStruct()) {
2002 this->write(") -> ");
2003 this->write(pipeline_struct_prefix(programKind));
2004 this->writeLine("Out {");
2005 } else {
2006 this->writeLine(") {");
2007 }
2008 // Initialize polyfilled matrix uniforms if any were used.
2009 fIndentation++;
2010 if (initPolyfill) {
2011 this->writeLine("_skInitializePolyfilledUniforms();");
2012 }
2013
2014 // Declare the stage output struct.
2015 if (this->needsStageOutputStruct()) {
2016 this->write("var _stageOut: ");
2017 this->write(pipeline_struct_prefix(programKind));
2018 this->writeLine("Out;");
2019 }
2020
2021 // We are compiling a Runtime Effect as a fragment shader, for testing purposes. We assign the
2022 // result from _skslMain into sk_FragColor if the user-defined main returns a color. This
2023 // doesn't actually matter, but it is more indicative of what a real program would do.
2024 // `addImplicitFragColorWrite` from Transform::FindAndDeclareBuiltinVariables has already
2025 // injected sk_FragColor into our stage outputs even if it wasn't explicitly referenced.
2026 if (fGenSyntheticCode == IncludeSyntheticCode::kYes && ProgramConfig::IsFragment(programKind)) {
2027 if (main.declaration().returnType().matches(*fContext.fTypes.fHalf4)) {
2028 this->write("_stageOut.sk_FragColor = ");
2029 }
2030 }
2031
2032 // Generate a function call to the user-defined main.
2033 this->write("_skslMain(");
2034 auto separator = SkSL::String::Separator();
2035 WGSLFunctionDependencies* deps = fRequirements.fDependencies.find(&main.declaration());
2036 if (deps) {
2037 if (*deps & WGSLFunctionDependency::kPipelineInputs) {
2038 this->write(separator());
2039 this->write("_stageIn");
2040 }
2041 if (*deps & WGSLFunctionDependency::kPipelineOutputs) {
2042 this->write(separator());
2043 this->write("&_stageOut");
2044 }
2045 }
2046
2047 if (fGenSyntheticCode == IncludeSyntheticCode::kYes) {
2048 if (const Variable* v = main.declaration().getMainCoordsParameter()) {
2049 // We are compiling a Runtime Effect as a fragment shader, for testing purposes.
2050 // We need to synthesize a coordinates parameter, but the coordinates don't matter.
2051 SkASSERT(ProgramConfig::IsFragment(programKind));
2052 const Type& type = v->type();
2053 if (!type.matches(*fContext.fTypes.fFloat2)) {
2054 fContext.fErrors->error(
2055 main.fPosition,
2056 "main function has unsupported parameter: " + type.description());
2057 return;
2058 }
2059 this->write(separator());
2060 this->write("/*fragcoord*/ vec2<f32>()");
2061 }
2062 }
2063
2064 this->writeLine(");");
2065
2066 if (this->needsStageOutputStruct()) {
2067 // Return the stage output struct.
2068 this->writeLine("return _stageOut;");
2069 }
2070
2071 fIndentation--;
2072 this->writeLine("}");
2073 }
2074
2075 void WGSLCodeGenerator::writeStatement(const Statement& s) {
2076 switch (s.kind()) {
2077 case Statement::Kind::kBlock:
2078 this->writeBlock(s.as<Block>());
2079 break;
2080 case Statement::Kind::kBreak:
2081 this->writeLine("break;");
2082 break;
2083 case Statement::Kind::kContinue:
2084 this->writeLine("continue;");
2085 break;
2086 case Statement::Kind::kDiscard:
2087 this->writeLine("discard;");
2088 break;
2089 case Statement::Kind::kDo:
2090 this->writeDoStatement(s.as<DoStatement>());
2091 break;
2092 case Statement::Kind::kExpression:
2093 this->writeExpressionStatement(*s.as<ExpressionStatement>().expression());
2094 break;
2095 case Statement::Kind::kFor:
2096 this->writeForStatement(s.as<ForStatement>());
2097 break;
2098 case Statement::Kind::kIf:
2099 this->writeIfStatement(s.as<IfStatement>());
2100 break;
2101 case Statement::Kind::kNop:
2102 this->writeLine(";");
2103 break;
2104 case Statement::Kind::kReturn:
2105 this->writeReturnStatement(s.as<ReturnStatement>());
2106 break;
2107 case Statement::Kind::kSwitch:
2108 this->writeSwitchStatement(s.as<SwitchStatement>());
2109 break;
2110 case Statement::Kind::kSwitchCase:
2111 SkDEBUGFAIL("switch-case statements should only be present inside a switch");
2112 break;
2113 case Statement::Kind::kVarDeclaration:
2114 this->writeVarDeclaration(s.as<VarDeclaration>());
2115 break;
2116 }
2117 }
2118
2119 void WGSLCodeGenerator::writeStatements(const StatementArray& statements) {
2120 for (const auto& s : statements) {
2121 if (!s->isEmpty()) {
2122 this->writeStatement(*s);
2123 this->finishLine();
2124 }
2125 }
2126 }
2127
2128 void WGSLCodeGenerator::writeBlock(const Block& b) {
2129 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
2130 // something here to make the code valid).
2131 bool isScope = b.isScope() || b.isEmpty();
2132 if (isScope) {
2133 this->writeLine("{");
2134 fIndentation++;
2135 }
2136 this->writeStatements(b.children());
2137 if (isScope) {
2138 fIndentation--;
2139 this->writeLine("}");
2140 }
2141 }
2142
2143 void WGSLCodeGenerator::writeExpressionStatement(const Expression& expr) {
2144 // Any expression-related side effects must be emitted as separate statements when
2145 // `assembleExpression` is called.
2146 // The final result of the expression will be a variable, let-reference, or an expression with
2147 // no side effects (`foo + bar`). Discarding this result is safe, as the program never uses it.
2148 (void)this->assembleExpression(expr, Precedence::kStatement);
2149 }
2150
2151 void WGSLCodeGenerator::writeDoStatement(const DoStatement& s) {
2152 // Generate a loop structure like this:
2153 // loop {
2154 // body-statement;
2155 // continuing {
2156 // break if inverted-test-expression;
2157 // }
2158 // }
2159
2160 ++fConditionalScopeDepth;
2161
2162 std::unique_ptr<Expression> invertedTestExpr = PrefixExpression::Make(
2163 fContext, s.test()->fPosition, OperatorKind::LOGICALNOT, s.test()->clone());
2164
2165 this->writeLine("loop {");
2166 fIndentation++;
2167 this->writeStatement(*s.statement());
2168 this->finishLine();
2169
2170 this->writeLine("continuing {");
2171 fIndentation++;
2172 std::string breakIfExpr = this->assembleExpression(*invertedTestExpr, Precedence::kExpression);
2173 this->write("break if ");
2174 this->write(breakIfExpr);
2175 this->writeLine(";");
2176 fIndentation--;
2177 this->writeLine("}");
2178 fIndentation--;
2179 this->writeLine("}");
2180
2181 --fConditionalScopeDepth;
2182 }
2183
2184 void WGSLCodeGenerator::writeForStatement(const ForStatement& s) {
2185 // Generate a loop structure wrapped in an extra scope:
2186 // {
2187 // initializer-statement;
2188 // loop;
2189 // }
2190 // The outer scope is necessary to prevent the initializer-variable from leaking out into the
2191 // rest of the code. In practice, the generated code actually tends to be scoped even more
2192 // deeply, as the body-statement almost always contributes an extra block.
2193
2194 ++fConditionalScopeDepth;
2195
2196 if (s.initializer()) {
2197 this->writeLine("{");
2198 fIndentation++;
2199 this->writeStatement(*s.initializer());
2200 this->writeLine();
2201 }
2202
2203 this->writeLine("loop {");
2204 fIndentation++;
2205
2206 if (s.unrollInfo()) {
2207 if (s.unrollInfo()->fCount <= 0) {
2208 // Loops which are known to never execute don't need to be emitted at all.
2209 // (However, the front end should have already replaced this loop with a Nop.)
2210 } else {
2211 // Loops which are known to execute at least once can use this form:
2212 //
2213 // loop {
2214 // body-statement;
2215 // continuing {
2216 // next-expression;
2217 // break if inverted-test-expression;
2218 // }
2219 // }
2220
2221 this->writeStatement(*s.statement());
2222 this->finishLine();
2223 this->writeLine("continuing {");
2224 ++fIndentation;
2225
2226 if (s.next()) {
2227 this->writeExpressionStatement(*s.next());
2228 this->finishLine();
2229 }
2230
2231 if (s.test()) {
2232 std::unique_ptr<Expression> invertedTestExpr = PrefixExpression::Make(
2233 fContext, s.test()->fPosition, OperatorKind::LOGICALNOT, s.test()->clone());
2234
2235 std::string breakIfExpr =
2236 this->assembleExpression(*invertedTestExpr, Precedence::kExpression);
2237 this->write("break if ");
2238 this->write(breakIfExpr);
2239 this->writeLine(";");
2240 }
2241
2242 --fIndentation;
2243 this->writeLine("}");
2244 }
2245 } else {
2246 // Loops without a known execution count are emitted in this form:
2247 //
2248 // loop {
2249 // if test-expression {
2250 // body-statement;
2251 // } else {
2252 // break;
2253 // }
2254 // continuing {
2255 // next-expression;
2256 // }
2257 // }
2258
2259 if (s.test()) {
2260 std::string testExpr = this->assembleExpression(*s.test(), Precedence::kExpression);
2261 this->write("if ");
2262 this->write(testExpr);
2263 this->writeLine(" {");
2264
2265 fIndentation++;
2266 this->writeStatement(*s.statement());
2267 this->finishLine();
2268 fIndentation--;
2269
2270 this->writeLine("} else {");
2271
2272 fIndentation++;
2273 this->writeLine("break;");
2274 fIndentation--;
2275
2276 this->writeLine("}");
2277 }
2278 else {
2279 this->writeStatement(*s.statement());
2280 this->finishLine();
2281 }
2282
2283 if (s.next()) {
2284 this->writeLine("continuing {");
2285 fIndentation++;
2286 this->writeExpressionStatement(*s.next());
2287 this->finishLine();
2288 fIndentation--;
2289 this->writeLine("}");
2290 }
2291 }
2292
2293 // This matches an open-brace at the top of the loop.
2294 fIndentation--;
2295 this->writeLine("}");
2296
2297 if (s.initializer()) {
2298 // This matches an open-brace before the initializer-statement.
2299 fIndentation--;
2300 this->writeLine("}");
2301 }
2302
2303 --fConditionalScopeDepth;
2304 }
2305
2306 void WGSLCodeGenerator::writeIfStatement(const IfStatement& s) {
2307 ++fConditionalScopeDepth;
2308
2309 std::string testExpr = this->assembleExpression(*s.test(), Precedence::kExpression);
2310 this->write("if ");
2311 this->write(testExpr);
2312 this->writeLine(" {");
2313 fIndentation++;
2314 this->writeStatement(*s.ifTrue());
2315 this->finishLine();
2316 fIndentation--;
2317 if (s.ifFalse()) {
2318 this->writeLine("} else {");
2319 fIndentation++;
2320 this->writeStatement(*s.ifFalse());
2321 this->finishLine();
2322 fIndentation--;
2323 }
2324 this->writeLine("}");
2325
2326 --fConditionalScopeDepth;
2327 }
2328
2329 void WGSLCodeGenerator::writeReturnStatement(const ReturnStatement& s) {
2330 fHasUnconditionalReturn |= (fConditionalScopeDepth == 0);
2331
2332 std::string expr = s.expression()
2333 ? this->assembleExpression(*s.expression(), Precedence::kExpression)
2334 : std::string();
2335 this->write("return ");
2336 this->write(expr);
2337 this->write(";");
2338 }
2339
2340 void WGSLCodeGenerator::writeSwitchCaseList(SkSpan<const SwitchCase* const> cases) {
2341 auto separator = SkSL::String::Separator();
2342 for (const SwitchCase* const sc : cases) {
2343 this->write(separator());
2344 if (sc->isDefault()) {
2345 this->write("default");
2346 } else {
2347 this->write(std::to_string(sc->value()));
2348 }
2349 }
2350 }
2351
2352 void WGSLCodeGenerator::writeSwitchCases(SkSpan<const SwitchCase* const> cases) {
2353 if (!cases.empty()) {
2354 // Only the last switch-case should have a non-empty statement.
2355 SkASSERT(std::all_of(cases.begin(), std::prev(cases.end()), [](const SwitchCase* sc) {
2356 return sc->statement()->isEmpty();
2357 }));
2358
2359 // Emit the cases in a comma-separated list.
2360 this->write("case ");
2361 this->writeSwitchCaseList(cases);
2362 this->writeLine(" {");
2363 ++fIndentation;
2364
2365 // Emit the switch-case body.
2366 this->writeStatement(*cases.back()->statement());
2367 this->finishLine();
2368
2369 --fIndentation;
2370 this->writeLine("}");
2371 }
2372 }
2373
2374 void WGSLCodeGenerator::writeEmulatedSwitchFallthroughCases(SkSpan<const SwitchCase* const> cases,
2375 std::string_view switchValue) {
2376 // There's no need for fallthrough handling unless we actually have multiple case blocks.
2377 if (cases.size() < 2) {
2378 this->writeSwitchCases(cases);
2379 return;
2380 }
2381
2382 // Match against the entire case group.
2383 this->write("case ");
2384 this->writeSwitchCaseList(cases);
2385 this->writeLine(" {");
2386 ++fIndentation;
2387
2388 std::string fallthroughVar = this->writeScratchVar(*fContext.fTypes.fBool, "false");
2389 const size_t secondToLastCaseIndex = cases.size() - 2;
2390 const size_t lastCaseIndex = cases.size() - 1;
2391
2392 for (size_t index = 0; index < cases.size(); ++index) {
2393 const SwitchCase& sc = *cases[index];
2394 if (index < lastCaseIndex) {
2395 // The default case must come last in SkSL, and this case isn't the last one, so it
2396 // can't possibly be the default.
2397 SkASSERT(!sc.isDefault());
2398
2399 this->write("if ");
2400 if (index > 0) {
2401 this->write(fallthroughVar);
2402 this->write(" || ");
2403 }
2404 this->write(switchValue);
2405 this->write(" == ");
2406 this->write(std::to_string(sc.value()));
2407 this->writeLine(" {");
2408 fIndentation++;
2409
2410 // We write the entire case-block statement here, and then set `switchFallthrough`
2411 // to 1. If the case-block had a break statement in it, we break out of the outer
2412 // for-loop entirely, meaning the `switchFallthrough` assignment never occurs, nor
2413 // does any code after it inside the switch. We've forbidden `continue` statements
2414 // inside switch case-blocks entirely, so we don't need to consider their effect on
2415 // control flow; see the Finalizer in FunctionDefinition::Convert.
2416 this->writeStatement(*sc.statement());
2417 this->finishLine();
2418
2419 if (index < secondToLastCaseIndex) {
2420 // Set a variable to indicate falling through to the next block. The very last
2421 // case-block is reached by process of elimination and doesn't need this
2422 // variable, so we don't actually need to set it if we are on the second-to-last
2423 // case block.
2424 this->write(fallthroughVar);
2425 this->write(" = true; ");
2426 }
2427 #if defined(SK_DEBUG)
2428 this->writeLine("// fallthrough");
2429 #endif
2430
2431 fIndentation--;
2432 this->writeLine("}");
2433 } else {
2434 // This is the final case. Since it's always last, we can just dump in the code.
2435 // (If we didn't match any of the other values, we must have matched this one by
2436 // process of elimination. If we did match one of the other values, we either hit a
2437 // `break` statement earlier--and won't get this far--or we're falling through.)
2438 this->writeStatement(*sc.statement());
2439 this->finishLine();
2440 }
2441 }
2442
2443 --fIndentation;
2444 this->writeLine("}");
2445 }
2446
2447 void WGSLCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
2448 // WGSL supports the `switch` statement in a limited capacity. A default case must always be
2449 // specified. Each switch-case must be scoped inside braces. Fallthrough is not supported; a
2450 // trailing break is implied at the end of each switch-case block. (Explicit breaks are also
2451 // allowed.) One minor improvement over a traditional switch is that switch-cases take a list
2452 // of values to match, instead of a single value:
2453 // case 1, 2 { foo(); }
2454 // case 3, default { bar(); }
2455 //
2456 // We will use the native WGSL switch statement for any switch-cases in the SkSL which can be
2457 // made to conform to these limitations. The remaining cases which cannot conform will be
2458 // emulated with if-else blocks (similar to our GLSL ES2 switch-statement emulation path). This
2459 // should give us good performance in the common case, since most switches naturally conform.
2460
2461 // First, let's emit the switch itself.
2462 std::string valueExpr = this->assembleExpression(*s.value(), Precedence::kExpression,
2463 kUsedMultipleTimes);
2464 this->write("switch ");
2465 this->write(valueExpr);
2466 this->writeLine(" {");
2467 ++fIndentation;
2468
2469 // Now let's go through the switch-cases, and emit the ones that don't fall through.
2470 TArray<const SwitchCase*> nativeCases;
2471 TArray<const SwitchCase*> fallthroughCases;
2472 bool previousCaseFellThrough = false;
2473 bool foundNativeDefault = false;
2474 [[maybe_unused]] bool foundFallthroughDefault = false;
2475
2476 const int lastSwitchCaseIdx = s.cases().size() - 1;
2477 for (int index = 0; index <= lastSwitchCaseIdx; ++index) {
2478 const SwitchCase& sc = s.cases()[index]->as<SwitchCase>();
2479
2480 if (sc.statement()->isEmpty()) {
2481 // This is a `case X:` that immediately falls through to the next case.
2482 // If we aren't already falling through, we can handle this via a comma-separated list.
2483 if (previousCaseFellThrough) {
2484 fallthroughCases.push_back(&sc);
2485 foundFallthroughDefault |= sc.isDefault();
2486 } else {
2487 nativeCases.push_back(&sc);
2488 foundNativeDefault |= sc.isDefault();
2489 }
2490 continue;
2491 }
2492
2493 if (index == lastSwitchCaseIdx || Analysis::SwitchCaseContainsUnconditionalExit(sc)) {
2494 // This is a `case X:` that never falls through.
2495 if (previousCaseFellThrough) {
2496 // Because the previous cases fell through, we can't use a native switch-case here.
2497 fallthroughCases.push_back(&sc);
2498 foundFallthroughDefault |= sc.isDefault();
2499
2500 this->writeEmulatedSwitchFallthroughCases(fallthroughCases, valueExpr);
2501 fallthroughCases.clear();
2502
2503 // Fortunately, we're no longer falling through blocks, so we might be able to use a
2504 // native switch-case list again.
2505 previousCaseFellThrough = false;
2506 } else {
2507 // Emit a native switch-case block with a comma-separated case list.
2508 nativeCases.push_back(&sc);
2509 foundNativeDefault |= sc.isDefault();
2510
2511 this->writeSwitchCases(nativeCases);
2512 nativeCases.clear();
2513 }
2514 continue;
2515 }
2516
2517 // This case falls through, so it will need to be handled via emulation.
2518 // If we have put together a collection of "native" cases (cases that fall through with no
2519 // actual case-body), we will need to slide them over into the fallthrough-case list.
2520 fallthroughCases.push_back_n(nativeCases.size(), nativeCases.data());
2521 nativeCases.clear();
2522
2523 fallthroughCases.push_back(&sc);
2524 foundFallthroughDefault |= sc.isDefault();
2525 previousCaseFellThrough = true;
2526 }
2527
2528 // Finish out the remaining switch-cases.
2529 this->writeSwitchCases(nativeCases);
2530 nativeCases.clear();
2531
2532 this->writeEmulatedSwitchFallthroughCases(fallthroughCases, valueExpr);
2533 fallthroughCases.clear();
2534
2535 // WGSL requires a default case.
2536 if (!foundNativeDefault && !foundFallthroughDefault) {
2537 this->writeLine("case default {}");
2538 }
2539
2540 --fIndentation;
2541 this->writeLine("}");
2542 }
2543
2544 void WGSLCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl) {
2545 std::string initialValue =
2546 varDecl.value() ? this->assembleExpression(*varDecl.value(), Precedence::kAssignment)
2547 : std::string();
2548
2549 if (varDecl.var()->modifierFlags().isConst() ||
2550 (fProgram.fUsage->get(*varDecl.var()).fWrite == 1 && varDecl.value())) {
2551 // Use `const` at global scope, or if the value is a compile-time constant.
2552 SkASSERTF(varDecl.value(), "an immutable variable must specify a value");
2553 const bool useConst =
2554 !fAtFunctionScope || Analysis::IsCompileTimeConstant(*varDecl.value());
2555 this->write(useConst ? "const " : "let ");
2556 } else {
2557 this->write("var ");
2558 }
2559 this->write(this->assembleName(varDecl.var()->mangledName()));
2560 this->write(": ");
2561 this->write(to_wgsl_type(fContext, varDecl.var()->type(), &varDecl.var()->layout()));
2562
2563 if (varDecl.value()) {
2564 this->write(" = ");
2565 this->write(initialValue);
2566 }
2567
2568 this->write(";");
2569 }
2570
2571 std::unique_ptr<WGSLCodeGenerator::LValue> WGSLCodeGenerator::makeLValue(const Expression& e) {
2572 if (e.is<VariableReference>()) {
2573 return std::make_unique<PointerLValue>(
2574 this->variableReferenceNameForLValue(e.as<VariableReference>()));
2575 }
2576 if (e.is<FieldAccess>()) {
2577 return std::make_unique<PointerLValue>(this->assembleFieldAccess(e.as<FieldAccess>()));
2578 }
2579 if (e.is<IndexExpression>()) {
2580 const IndexExpression& idx = e.as<IndexExpression>();
2581 if (idx.base()->type().isVector()) {
2582 // Rewrite indexed-swizzle accesses like `myVec.zyx[i]` into an index onto `myVec`.
2583 if (std::unique_ptr<Expression> rewrite =
2584 Transform::RewriteIndexedSwizzle(fContext, idx)) {
2585 return std::make_unique<VectorComponentLValue>(
2586 this->assembleExpression(*rewrite, Precedence::kAssignment));
2587 } else {
2588 return std::make_unique<VectorComponentLValue>(this->assembleIndexExpression(idx));
2589 }
2590 } else {
2591 return std::make_unique<PointerLValue>(this->assembleIndexExpression(idx));
2592 }
2593 }
2594 if (e.is<Swizzle>()) {
2595 const Swizzle& swizzle = e.as<Swizzle>();
2596 if (swizzle.components().size() == 1) {
2597 return std::make_unique<VectorComponentLValue>(this->assembleSwizzle(swizzle));
2598 } else {
2599 return std::make_unique<SwizzleLValue>(
2600 fContext,
2601 this->assembleExpression(*swizzle.base(), Precedence::kAssignment),
2602 swizzle.base()->type(),
2603 swizzle.components());
2604 }
2605 }
2606
2607 fContext.fErrors->error(e.fPosition, "unsupported lvalue type");
2608 return nullptr;
2609 }
2610
2611 std::string WGSLCodeGenerator::assembleExpression(const Expression& e,
2612 Precedence parentPrecedence,
2613 AssembleMode mode) {
2614 // Determine if we need to introduce a scratch let for this expression. There are three
2615 // situations that require this:
2616 // 1. Explicitly requested by caller.
2617 // 2. outer context would reference it multiple reasons for *reasons*, and the expression is
2618 // not trivial
2619 // 3. skbug.com/asdf, where the first child const expression needs to be lifted to avoid
2620 // WGSL's stricter const eval rules.
2621 if (mode == kForceLet ||
2622 (mode == kUsedMultipleTimes && is_nontrivial_expression(e)) ||
2623 /* mode == kAuto && */ fNeedsConstEvalWorkaround) {
2624 // Allow the scratch let to be considered const as long as we don't have to force it to
2625 // a let for the const-eval workaround or by `mode`.
2626 const bool canBeConst = !fNeedsConstEvalWorkaround &&
2627 mode != kForceLet &&
2628 Analysis::IsCompileTimeConstant(e);
2629 // Setting this to false and not overriding the AssembleMode means this next call to
2630 // assembleExpression gives us the original expression value.
2631 fNeedsConstEvalWorkaround = false;
2632 std::string expr = this->assembleExpression(e, Precedence::kAssignment);
2633 return this->writeScratchLet(expr, canBeConst);
2634 }
2635
2636 AutoConstEvalWorkaround constEval{this, e};
2637 switch (e.kind()) {
2638 case Expression::Kind::kBinary:
2639 return this->assembleBinaryExpression(e.as<BinaryExpression>(), parentPrecedence);
2640
2641 case Expression::Kind::kConstructorCompound:
2642 return this->assembleConstructorCompound(e.as<ConstructorCompound>());
2643
2644 case Expression::Kind::kConstructorArrayCast:
2645 return this->assembleConstructorArrayCast(e.as<ConstructorArrayCast>(),
2646 parentPrecedence);
2647
2648 case Expression::Kind::kConstructorArray:
2649 case Expression::Kind::kConstructorCompoundCast:
2650 case Expression::Kind::kConstructorScalarCast:
2651 case Expression::Kind::kConstructorSplat:
2652 case Expression::Kind::kConstructorStruct:
2653 return this->assembleAnyConstructor(e.asAnyConstructor());
2654
2655 case Expression::Kind::kConstructorDiagonalMatrix:
2656 return this->assembleConstructorDiagonalMatrix(e.as<ConstructorDiagonalMatrix>());
2657
2658 case Expression::Kind::kConstructorMatrixResize:
2659 return this->assembleConstructorMatrixResize(e.as<ConstructorMatrixResize>());
2660
2661 case Expression::Kind::kEmpty:
2662 return "false";
2663
2664 case Expression::Kind::kFieldAccess:
2665 return this->assembleFieldAccess(e.as<FieldAccess>());
2666
2667 case Expression::Kind::kFunctionCall:
2668 return this->assembleFunctionCall(e.as<FunctionCall>(), parentPrecedence);
2669
2670 case Expression::Kind::kIndex:
2671 return this->assembleIndexExpression(e.as<IndexExpression>());
2672
2673 case Expression::Kind::kLiteral:
2674 return this->assembleLiteral(e.as<Literal>());
2675
2676 case Expression::Kind::kPrefix:
2677 return this->assemblePrefixExpression(e.as<PrefixExpression>(), parentPrecedence);
2678
2679 case Expression::Kind::kPostfix:
2680 return this->assemblePostfixExpression(e.as<PostfixExpression>(), parentPrecedence);
2681
2682 case Expression::Kind::kSetting:
2683 return this->assembleExpression(*e.as<Setting>().toLiteral(fCaps), parentPrecedence);
2684
2685 case Expression::Kind::kSwizzle:
2686 return this->assembleSwizzle(e.as<Swizzle>());
2687
2688 case Expression::Kind::kTernary:
2689 return this->assembleTernaryExpression(e.as<TernaryExpression>(), parentPrecedence);
2690
2691 case Expression::Kind::kVariableReference:
2692 return this->assembleVariableReference(e.as<VariableReference>());
2693
2694 default:
2695 SkDEBUGFAILF("unsupported expression:\n%s", e.description().c_str());
2696 return {};
2697 }
2698 }
2699
2700 static bool binary_op_is_ambiguous_in_wgsl(Operator op) {
2701 // WGSL always requires parentheses for some operators which are deemed to be ambiguous.
2702 // (8.19. Operator Precedence and Associativity)
2703 switch (op.kind()) {
2704 case OperatorKind::LOGICALOR:
2705 case OperatorKind::LOGICALAND:
2706 case OperatorKind::BITWISEOR:
2707 case OperatorKind::BITWISEAND:
2708 case OperatorKind::BITWISEXOR:
2709 case OperatorKind::SHL:
2710 case OperatorKind::SHR:
2711 case OperatorKind::LT:
2712 case OperatorKind::GT:
2713 case OperatorKind::LTEQ:
2714 case OperatorKind::GTEQ:
2715 return true;
2716
2717 default:
2718 return false;
2719 }
2720 }
2721
2722 bool WGSLCodeGenerator::binaryOpNeedsComponentwiseMatrixPolyfill(const Type& left,
2723 const Type& right,
2724 Operator op) {
2725 switch (op.kind()) {
2726 case OperatorKind::SLASH:
2727 case OperatorKind::SLASHEQ:
2728 // WGSL does not natively support componentwise matrix-op-matrix for division.
2729 if (left.isMatrix() && right.isMatrix()) {
2730 return true;
2731 }
2732 [[fallthrough]];
2733
2734 case OperatorKind::PLUS:
2735 case OperatorKind::PLUSEQ:
2736 case OperatorKind::MINUS:
2737 case OperatorKind::MINUSEQ:
2738 // WGSL does not natively support componentwise matrix-op-scalar or scalar-op-matrix for
2739 // addition, subtraction or division.
2740 return (left.isMatrix() && right.isScalar()) ||
2741 (left.isScalar() && right.isMatrix());
2742
2743 default:
2744 return false;
2745 }
2746 }
2747
2748 std::string WGSLCodeGenerator::assembleBinaryExpression(const BinaryExpression& b,
2749 Precedence parentPrecedence) {
2750 return this->assembleBinaryExpression(*b.left(), b.getOperator(), *b.right(), b.type(),
2751 parentPrecedence);
2752 }
2753
2754 std::string WGSLCodeGenerator::assembleBinaryExpression(const Expression& left,
2755 Operator op,
2756 const Expression& right,
2757 const Type& resultType,
2758 Precedence parentPrecedence) {
2759 // If the operator is && or ||, we need to handle short-circuiting properly. Specifically, we
2760 // sometimes need to emit extra statements to paper over functionality that WGSL lacks, like
2761 // assignment in the middle of an expression. We need to guard those extra statements, to ensure
2762 // that they don't occur if the expression evaluation is short-circuited. Converting the
2763 // expression into an if-else block keeps the short-circuit property intact even when extra
2764 // statements are involved.
2765 // If the RHS doesn't have any side effects, then it's safe to just leave the expression as-is,
2766 // since we know that any possible extra statements are non-side-effecting.
2767 std::string expr;
2768 if (op.kind() == OperatorKind::LOGICALAND && Analysis::HasSideEffects(right)) {
2769 // Converts `left_expression && right_expression` into the following block:
2770
2771 // var _skTemp1: bool;
2772 // [[ prepare left_expression ]]
2773 // if left_expression {
2774 // [[ prepare right_expression ]]
2775 // _skTemp1 = right_expression;
2776 // } else {
2777 // _skTemp1 = false;
2778 // }
2779
2780 expr = this->writeScratchVar(resultType);
2781
2782 std::string leftExpr = this->assembleExpression(left, Precedence::kExpression);
2783 this->write("if ");
2784 this->write(leftExpr);
2785 this->writeLine(" {");
2786
2787 ++fIndentation;
2788 std::string rightExpr = this->assembleExpression(right, Precedence::kAssignment);
2789 this->write(expr);
2790 this->write(" = ");
2791 this->write(rightExpr);
2792 this->writeLine(";");
2793 --fIndentation;
2794
2795 this->writeLine("} else {");
2796
2797 ++fIndentation;
2798 this->write(expr);
2799 this->writeLine(" = false;");
2800 --fIndentation;
2801
2802 this->writeLine("}");
2803 return expr;
2804 }
2805
2806 if (op.kind() == OperatorKind::LOGICALOR && Analysis::HasSideEffects(right)) {
2807 // Converts `left_expression || right_expression` into the following block:
2808
2809 // var _skTemp1: bool;
2810 // [[ prepare left_expression ]]
2811 // if left_expression {
2812 // _skTemp1 = true;
2813 // } else {
2814 // [[ prepare right_expression ]]
2815 // _skTemp1 = right_expression;
2816 // }
2817
2818 expr = this->writeScratchVar(resultType);
2819
2820 std::string leftExpr = this->assembleExpression(left, Precedence::kExpression);
2821 this->write("if ");
2822 this->write(leftExpr);
2823 this->writeLine(" {");
2824
2825 ++fIndentation;
2826 this->write(expr);
2827 this->writeLine(" = true;");
2828 --fIndentation;
2829
2830 this->writeLine("} else {");
2831
2832 ++fIndentation;
2833 std::string rightExpr = this->assembleExpression(right, Precedence::kAssignment);
2834 this->write(expr);
2835 this->write(" = ");
2836 this->write(rightExpr);
2837 this->writeLine(";");
2838 --fIndentation;
2839
2840 this->writeLine("}");
2841 return expr;
2842 }
2843
2844 // Handle comma-expressions.
2845 if (op.kind() == OperatorKind::COMMA) {
2846 // The result from the left-expression is ignored, but its side effects must occur.
2847 this->assembleExpression(left, Precedence::kStatement);
2848
2849 // Evaluate the right side normally.
2850 return this->assembleExpression(right, parentPrecedence);
2851 }
2852
2853 // Handle assignment-expressions.
2854 const bool compMatrixOp =
2855 this->binaryOpNeedsComponentwiseMatrixPolyfill(left.type(), right.type(), op);
2856
2857 if (op.isAssignment()) {
2858 std::unique_ptr<LValue> lvalue = this->makeLValue(left);
2859 if (!lvalue) {
2860 return "";
2861 }
2862
2863 if (op.kind() == OperatorKind::EQ) {
2864 // Evaluate the right-hand side of simple assignment (`a = b` --> `b`).
2865 expr = this->assembleExpression(right, Precedence::kAssignment);
2866 } else {
2867 // Evaluate the right-hand side of compound-assignment (`a += b` --> `a + b`).
2868 op = op.removeAssignment();
2869
2870 std::string lhs = lvalue->load();
2871 std::string rhs = this->assembleExpression(right, op.getBinaryPrecedence(),
2872 compMatrixOp ? kUsedMultipleTimes : kAuto);
2873
2874 if (compMatrixOp) {
2875 expr = this->assembleComponentwiseMatrixBinary(left.type(), right.type(),
2876 lhs, rhs, op);
2877 } else {
2878 expr = lhs + operator_name(op) + rhs;
2879 }
2880 }
2881
2882 // Emit the assignment statement (`a = a + b`).
2883 this->writeLine(lvalue->store(expr));
2884
2885 // Return the lvalue (`a`) as the result, since the value might be used by the caller.
2886 return lvalue->load();
2887 }
2888
2889 if (op.isEquality()) {
2890 return this->assembleEqualityExpression(left, right, op, parentPrecedence);
2891 }
2892
2893 Precedence precedence = op.getBinaryPrecedence();
2894 bool needParens = precedence >= parentPrecedence;
2895 if (binary_op_is_ambiguous_in_wgsl(op)) {
2896 precedence = Precedence::kParentheses;
2897 }
2898 if (needParens) {
2899 expr = "(";
2900 }
2901
2902 std::string lhs = this->assembleExpression(left, precedence,
2903 compMatrixOp ? kUsedMultipleTimes : kAuto);
2904 std::string rhs = this->assembleExpression(right, precedence,
2905 compMatrixOp ? kUsedMultipleTimes : kAuto);
2906 if (compMatrixOp) {
2907 expr += this->assembleComponentwiseMatrixBinary(left.type(), right.type(), lhs, rhs, op);
2908 } else {
2909 expr += lhs + operator_name(op) + rhs;
2910 }
2911
2912 if (needParens) {
2913 expr += ')';
2914 }
2915
2916 return expr;
2917 }
2918
2919 std::string WGSLCodeGenerator::assembleFieldAccess(const FieldAccess& f) {
2920 const Field* field = &f.base()->type().fields()[f.fieldIndex()];
2921 std::string expr;
2922
2923 if (FieldPolyfillInfo* polyfillInfo = fFieldPolyfillMap.find(field)) {
2924 // We found a matrix uniform. We are required to pass some matrix uniforms as array vectors,
2925 // since the std140 layout for a matrix assumes 4-column vectors for each row, and WGSL
2926 // tightly packs 2-column matrices. When emitting code, we replace the field-access
2927 // expression with a global variable which holds an unpacked version of the uniform.
2928 polyfillInfo->fWasAccessed = true;
2929
2930 // The polyfill can either be based directly onto a uniform in an interface block, or it
2931 // might be based on an index-expression onto a uniform if the interface block is arrayed.
2932 const Expression* base = f.base().get();
2933 const IndexExpression* indexExpr = nullptr;
2934 if (base->is<IndexExpression>()) {
2935 indexExpr = &base->as<IndexExpression>();
2936 base = indexExpr->base().get();
2937 }
2938
2939 SkASSERT(base->is<VariableReference>());
2940 expr = polyfillInfo->fReplacementName;
2941
2942 // If we had an index expression, we must append the index.
2943 if (indexExpr) {
2944 expr += '[';
2945 expr += this->assembleExpression(*indexExpr->index(), Precedence::kSequence);
2946 expr += ']';
2947 }
2948 return expr;
2949 }
2950
2951 switch (f.ownerKind()) {
2952 case FieldAccess::OwnerKind::kDefault:
2953 expr = this->assembleExpression(*f.base(), Precedence::kPostfix) + '.';
2954 break;
2955
2956 case FieldAccess::OwnerKind::kAnonymousInterfaceBlock:
2957 if (f.base()->is<VariableReference>() &&
2958 field->fLayout.fBuiltin != SK_POINTSIZE_BUILTIN) {
2959 expr = this->variablePrefix(*f.base()->as<VariableReference>().variable());
2960 }
2961 break;
2962 }
2963
2964 expr += this->assembleName(field->fName);
2965 return expr;
2966 }
2967
2968 std::string WGSLCodeGenerator::assembleSimpleIntrinsic(std::string_view intrinsicName,
2969 const FunctionCall& call,
2970 bool wgslOnlySupportsHighPrecision) {
2971 // Invoke the function, passing each function argument.
2972 std::string expr = std::string(intrinsicName);
2973 expr.push_back('(');
2974 const ExpressionArray& args = call.arguments();
2975 auto separator = SkSL::String::Separator();
2976 for (int index = 0; index < args.size(); ++index) {
2977 expr += separator();
2978
2979 std::string argument = this->assembleExpression(*args[index], Precedence::kSequence);
2980 if (wgslOnlySupportsHighPrecision && type_is_low_precision(args[index]->type(), fContext)) {
2981 // Add a cast to high precision
2982 SkASSERT(!args[index]->type().isAtomic());
2983 const std::string highPType = to_wgsl_type(fContext,
2984 args[index]->type(),
2985 /*layout=*/nullptr,
2986 /*forceHighPrecision=*/true);
2987 expr += highPType + "(" + argument + ")";
2988 } else if (args[index]->type().isAtomic()) {
2989 // WGSL passes atomic values to intrinsics as pointers.
2990 expr += '&';
2991 expr += argument;
2992 } else {
2993 expr += argument;
2994 }
2995 }
2996 expr.push_back(')');
2997
2998 // Wrap the call expression in a cast back to its low precision type if necessary.
2999 if (wgslOnlySupportsHighPrecision && type_is_low_precision(call.type(), fContext)) {
3000 const std::string lowPType = to_wgsl_type(fContext, call.type());
3001 expr = lowPType + "(" + expr + ")";
3002 }
3003
3004 return expr;
3005 }
3006
3007 std::string WGSLCodeGenerator::assembleVectorizedIntrinsic(std::string_view intrinsicName,
3008 const FunctionCall& call) {
3009 SkASSERT(!call.type().isVoid());
3010
3011 // Invoke the function, passing each function argument.
3012 std::string expr = std::string(intrinsicName);
3013 expr.push_back('(');
3014
3015 auto separator = SkSL::String::Separator();
3016 const ExpressionArray& args = call.arguments();
3017 bool returnsVector = call.type().isVector();
3018 for (int index = 0; index < args.size(); ++index) {
3019 expr += separator();
3020
3021 bool vectorize = returnsVector && args[index]->type().isScalar();
3022 if (vectorize) {
3023 expr += to_wgsl_type(fContext, call.type());
3024 expr.push_back('(');
3025 }
3026
3027 expr += this->assembleExpression(*args[index], Precedence::kSequence);
3028 if (vectorize) {
3029 expr.push_back(')');
3030 }
3031 }
3032 expr.push_back(')');
3033
3034 return expr;
3035 }
3036
3037 std::string WGSLCodeGenerator::assembleUnaryOpIntrinsic(Operator op,
3038 const FunctionCall& call,
3039 Precedence parentPrecedence) {
3040 SkASSERT(!call.type().isVoid());
3041
3042 bool needParens = Precedence::kPrefix >= parentPrecedence;
3043
3044 std::string expr;
3045 if (needParens) {
3046 expr.push_back('(');
3047 }
3048
3049 expr += operator_name(op);
3050 expr += this->assembleExpression(*call.arguments()[0], Precedence::kPrefix);
3051
3052 if (needParens) {
3053 expr.push_back(')');
3054 }
3055
3056 return expr;
3057 }
3058
3059 std::string WGSLCodeGenerator::assembleBinaryOpIntrinsic(Operator op,
3060 const FunctionCall& call,
3061 Precedence parentPrecedence) {
3062 SkASSERT(!call.type().isVoid());
3063
3064 Precedence precedence = op.getBinaryPrecedence();
3065 bool needParens = precedence >= parentPrecedence ||
3066 binary_op_is_ambiguous_in_wgsl(op);
3067 std::string expr;
3068 if (needParens) {
3069 expr.push_back('(');
3070 }
3071
3072 expr += this->assembleExpression(*call.arguments()[0], precedence);
3073 expr += operator_name(op);
3074 expr += this->assembleExpression(*call.arguments()[1], precedence);
3075
3076 if (needParens) {
3077 expr.push_back(')');
3078 }
3079
3080 return expr;
3081 }
3082
3083 // Rewrite a WGSL intrinsic of the form "intrinsicName(in) -> struct" to the SkSL's
3084 // "intrinsicName(in, outField) -> returnField", where outField and returnField are the names of the
3085 // fields in the struct returned by the WGSL intrinsic.
3086 std::string WGSLCodeGenerator::assembleOutAssignedIntrinsic(std::string_view intrinsicName,
3087 std::string_view returnField,
3088 std::string_view outField,
3089 const FunctionCall& call) {
3090 SkASSERT(call.type().componentType().isNumber());
3091 SkASSERT(call.arguments().size() == 2);
3092 SkASSERT(call.function().parameters()[1]->modifierFlags() & ModifierFlag::kOut);
3093
3094 // Invoke the intrinsic with the first parameter.
3095 std::string expr = std::string(intrinsicName);
3096 expr += "(";
3097 expr += this->assembleExpression(*call.arguments()[0], Precedence::kSequence);
3098 expr += ")";
3099 // In WGSL the intrinsic returns a struct; assign it to a local so that its fields can be
3100 // accessed multiple times.
3101 expr = this->writeScratchLet(expr);
3102 expr += ".";
3103
3104 // Store the outField of `expr` to the intended "out" argument
3105 std::unique_ptr<LValue> lvalue = this->makeLValue(*call.arguments()[1]);
3106 if (!lvalue) {
3107 return "";
3108 }
3109 std::string outValue = expr;
3110 outValue += outField;
3111 this->writeLine(lvalue->store(outValue));
3112
3113 // And return the expression accessing the returnField.
3114 expr += returnField;
3115 return expr;
3116 }
3117
3118 std::pair<std::string, const char*> WGSLCodeGenerator::assemblePartialSampleCall(
3119 std::string_view functionName,
3120 const Type& type,
3121 const Expression& sampler,
3122 const Expression& coords) {
3123 // This function returns `functionName(inSampler_texture, inSampler_sampler, coords` without a
3124 // terminating comma or close-parenthesis. This allows the caller to add more arguments as
3125 // needed.
3126 std::string expr = std::string(functionName) + '(';
3127 if (sampler.type().typeKind() == Type::TypeKind::kSampler) {
3128 // Split combined texture+sampler into two args with suffixes.
3129 expr += this->assembleExpression(sampler, Precedence::kSequence);
3130 expr += kTextureSuffix;
3131 expr += ", ";
3132 expr += this->assembleExpression(sampler, Precedence::kSequence);
3133 expr += kSamplerSuffix;
3134 expr += ", ";
3135 } else {
3136 SkASSERT(sampler.type().typeKind() == Type::TypeKind::kTexture);
3137 // Pass through the texture expression without any extra suffix
3138 expr += this->assembleExpression(sampler, Precedence::kSequence);
3139 expr += ", ";
3140 }
3141
3142 // Compute the sample coordinates, dividing out the Z if a vec3 was provided.
3143 SkASSERT(coords.type().isVector());
3144 if (coords.type().columns() == 3) {
3145 // The coordinates were passed as a vec3, so we need to emit `coords.xy / coords.z`.
3146 // This is a binary op applied to `coords` twice, so explicitly reapply the const eval
3147 // workaround with just it in mind.
3148 const bool coordsConst = ConstantFolder::GetConstantValueOrNull(coords);
3149 std::string vec3Coords = this->assembleExpression(coords, Precedence::kMultiplicative,
3150 coordsConst ? kForceLet
3151 : kUsedMultipleTimes);
3152 expr += vec3Coords + ".xy / " + vec3Coords + ".z";
3153 } else {
3154 // The coordinates should be a plain vec2; emit the expression as-is.
3155 SkASSERT(coords.type().columns() == 2);
3156 expr += this->assembleExpression(coords, Precedence::kSequence);
3157 }
3158
3159 // WGSL does not support f16 textures while all of SkSL's sample functions return "half4", so
3160 // add a cast back to f16 if necessary.
3161 if (type_is_low_precision(type, fContext)) {
3162 std::string lowPType = to_wgsl_type(fContext, type);
3163 return {lowPType + "(" + expr, "))"};
3164 } else {
3165 return {expr, ")"};
3166 }
3167 }
3168
3169 std::string WGSLCodeGenerator::assembleComponentwiseMatrixBinary(const Type& leftType,
3170 const Type& rightType,
3171 const std::string& left,
3172 const std::string& right,
3173 Operator op) {
3174 bool leftIsMatrix = leftType.isMatrix();
3175 bool rightIsMatrix = rightType.isMatrix();
3176 const Type& matrixType = leftIsMatrix ? leftType : rightType;
3177
3178 std::string expr = to_wgsl_type(fContext, matrixType) + '(';
3179 auto separator = String::Separator();
3180 int columns = matrixType.columns();
3181 for (int c = 0; c < columns; ++c) {
3182 expr += separator();
3183 expr += left;
3184 if (leftIsMatrix) {
3185 expr += '[';
3186 expr += std::to_string(c);
3187 expr += ']';
3188 }
3189 expr += op.operatorName();
3190 expr += right;
3191 if (rightIsMatrix) {
3192 expr += '[';
3193 expr += std::to_string(c);
3194 expr += ']';
3195 }
3196 }
3197 return expr + ')';
3198 }
3199
3200 std::string WGSLCodeGenerator::assembleIntrinsicCall(const FunctionCall& call,
3201 IntrinsicKind kind,
3202 Precedence parentPrecedence) {
3203 // Be careful: WGSL 1.0 will reject any intrinsic calls which can be constant-evaluated to
3204 // infinity or nan with a compile error. If all arguments to an intrinsic are compile-time
3205 // constants (`all_arguments_constant`), it is safest to copy one argument into a scratch-let so
3206 // that the call will be seen as runtime-evaluated, which defuses the overflow checks.
3207 // Don't worry; a competent driver should still optimize it away. This was automatically handled
3208 // in appendExpression()'s AutoConstEvalWorkaround before this was reached.
3209
3210 const ExpressionArray& arguments = call.arguments();
3211 switch (kind) {
3212 case k_atan_IntrinsicKind: {
3213 const char* name = (arguments.size() == 1) ? "atan" : "atan2";
3214 return this->assembleSimpleIntrinsic(name, call);
3215 }
3216
3217 // Derivative functions in WGSL are only defined for full precision types
3218 case k_dFdx_IntrinsicKind:
3219 return this->assembleSimpleIntrinsic("dpdx", call,
3220 /*wgslOnlySupportsHighPrecision=*/true);
3221
3222 case k_dFdy_IntrinsicKind:
3223 // WSGL is only generated for Graphite, which does not use RTFlip so there's no need
3224 // to flip the Y derivatives either.
3225 SkASSERT(fContext.fConfig->fSettings.fForceNoRTFlip);
3226 return this->assembleSimpleIntrinsic("dpdy", call,
3227 /*wgslOnlySupportsHighPrecision=*/true);
3228
3229 case k_dot_IntrinsicKind: {
3230 if (arguments[0]->type().isScalar()) {
3231 return this->assembleBinaryOpIntrinsic(OperatorKind::STAR, call, parentPrecedence);
3232 }
3233 return this->assembleSimpleIntrinsic("dot", call);
3234 }
3235 case k_equal_IntrinsicKind:
3236 return this->assembleBinaryOpIntrinsic(OperatorKind::EQEQ, call, parentPrecedence);
3237
3238 case k_faceforward_IntrinsicKind: {
3239 if (arguments[0]->type().isScalar()) {
3240 // select(-N, N, (I * Nref) < 0)
3241 fNeedsConstEvalWorkaround = false; // Disable for N, we'll handle it in I*Nref
3242 std::string N = this->assembleExpression(*arguments[0], Precedence::kPrefix,
3243 kUsedMultipleTimes);
3244 const bool INrefConst = ConstantFolder::GetConstantValueOrNull(*arguments[1]) &&
3245 ConstantFolder::GetConstantValueOrNull(*arguments[2]);
3246 std::string I = this->assembleExpression(*arguments[1],
3247 Precedence::kMultiplicative,
3248 INrefConst ? kForceLet : kAuto);
3249 std::string Nref = this->assembleExpression(*arguments[2],
3250 Precedence::kMultiplicative);
3251 return "select(-" + N + ", " + N + ", " + I + " * " + Nref + " < 0)";
3252 }
3253 return this->assembleSimpleIntrinsic("faceForward", call);
3254 }
3255 case k_frexp_IntrinsicKind:
3256 // SkSL frexp is "$genType fract = frexp($genType, out $genIType exp)" whereas WGSL
3257 // returns a struct with no out param: "let [fract, exp] = frexp($genType)".
3258 return this->assembleOutAssignedIntrinsic("frexp", "fract", "exp", call);
3259
3260 case k_greaterThan_IntrinsicKind:
3261 return this->assembleBinaryOpIntrinsic(OperatorKind::GT, call, parentPrecedence);
3262
3263 case k_greaterThanEqual_IntrinsicKind:
3264 return this->assembleBinaryOpIntrinsic(OperatorKind::GTEQ, call, parentPrecedence);
3265
3266 case k_inverse_IntrinsicKind:
3267 return this->assembleInversePolyfill(call);
3268
3269 case k_outerProduct_IntrinsicKind:
3270 return this->assembleOuterProductPolyfill(call);
3271
3272 case k_inversesqrt_IntrinsicKind:
3273 return this->assembleSimpleIntrinsic("inverseSqrt", call);
3274
3275 case k_lessThan_IntrinsicKind:
3276 return this->assembleBinaryOpIntrinsic(OperatorKind::LT, call, parentPrecedence);
3277
3278 case k_lessThanEqual_IntrinsicKind:
3279 return this->assembleBinaryOpIntrinsic(OperatorKind::LTEQ, call, parentPrecedence);
3280
3281 case k_matrixCompMult_IntrinsicKind: {
3282 std::string arg0 = this->assembleExpression(*arguments[0], Precedence::kPostfix,
3283 kUsedMultipleTimes);
3284 std::string arg1 = this->assembleExpression(*arguments[1], Precedence::kPostfix,
3285 kUsedMultipleTimes);
3286 return this->assembleComponentwiseMatrixBinary(arguments[0]->type(),
3287 arguments[1]->type(),
3288 arg0,
3289 arg1,
3290 OperatorKind::STAR);
3291 }
3292 case k_mix_IntrinsicKind: {
3293 const char* name = arguments[2]->type().componentType().isBoolean() ? "select" : "mix";
3294 return this->assembleVectorizedIntrinsic(name, call);
3295 }
3296 case k_mod_IntrinsicKind: {
3297 // WGSL has no intrinsic equivalent to `mod`. Synthesize `x - y * floor(x / y)`.
3298 // NOTE: While we are introducing a new binary op between two possible constant
3299 // expressions, it is consistent with the const-ness already handled by
3300 // AutoConstEvalWorkaround.
3301 std::string arg0 = this->assembleExpression(*arguments[0], Precedence::kAdditive,
3302 kUsedMultipleTimes);
3303 std::string arg1 = this->assembleExpression(*arguments[1], Precedence::kAdditive,
3304 kUsedMultipleTimes);
3305 return "(" + arg0 + " - " + arg1 + " * floor(" + arg0 + " / " + arg1 + "))";
3306 }
3307
3308 case k_modf_IntrinsicKind:
3309 // SkSL modf is "$genType fract = modf($genType, out $genType whole)" whereas WGSL
3310 // returns a struct with no out param: "let [fract, whole] = modf($genType)".
3311 return this->assembleOutAssignedIntrinsic("modf", "fract", "whole", call);
3312
3313 case k_normalize_IntrinsicKind: {
3314 const char* name = arguments[0]->type().isScalar() ? "sign" : "normalize";
3315 return this->assembleSimpleIntrinsic(name, call);
3316 }
3317 case k_not_IntrinsicKind:
3318 return this->assembleUnaryOpIntrinsic(OperatorKind::LOGICALNOT, call, parentPrecedence);
3319
3320 case k_notEqual_IntrinsicKind:
3321 return this->assembleBinaryOpIntrinsic(OperatorKind::NEQ, call, parentPrecedence);
3322
3323 case k_packHalf2x16_IntrinsicKind:
3324 return this->assembleSimpleIntrinsic("pack2x16float", call);
3325
3326 case k_packSnorm2x16_IntrinsicKind:
3327 return this->assembleSimpleIntrinsic("pack2x16snorm", call);
3328
3329 case k_packSnorm4x8_IntrinsicKind:
3330 return this->assembleSimpleIntrinsic("pack4x8snorm", call);
3331
3332 case k_packUnorm2x16_IntrinsicKind:
3333 return this->assembleSimpleIntrinsic("pack2x16unorm", call);
3334
3335 case k_packUnorm4x8_IntrinsicKind:
3336 return this->assembleSimpleIntrinsic("pack4x8unorm", call);
3337
3338 case k_findLSB_IntrinsicKind: {
3339 // firstTrailingBit (and firstLeadingBit) return a type matching their input, but
3340 // findLSB and findMSB in SkSL return signed types. Add a cast if needed.
3341 std::string lsb = this->assembleSimpleIntrinsic("firstTrailingBit", call);
3342 return arguments[0]->type().componentType().isSigned() ? lsb :
3343 (to_wgsl_type(fContext, call.type()) + "(" + lsb + ")");
3344 }
3345
3346 case k_findMSB_IntrinsicKind: {
3347 std::string msb = this->assembleSimpleIntrinsic("firstLeadingBit", call);
3348 return arguments[0]->type().componentType().isSigned() ? msb :
3349 (to_wgsl_type(fContext, call.type()) + "(" + msb + ")");
3350 }
3351
3352 case k_bitCount_IntrinsicKind: {
3353 // countOneBits returns a type matching its input, but bitCount in SkSL returns a
3354 // signed type. Add a cast if needed.
3355 std::string bitCount = this->assembleSimpleIntrinsic("countOneBits", call);
3356 return arguments[0]->type().componentType().isSigned() ? bitCount :
3357 (to_wgsl_type(fContext, call.type()) + "(" + bitCount + ")");
3358 }
3359
3360 case k_floatBitsToInt_IntrinsicKind:
3361 case k_floatBitsToUint_IntrinsicKind:
3362 case k_intBitsToFloat_IntrinsicKind:
3363 case k_uintBitsToFloat_IntrinsicKind: {
3364 std::string outputType = to_wgsl_type(fContext, call.type());
3365 return this->assembleSimpleIntrinsic("bitcast<" + outputType + ">", call);
3366 }
3367
3368 case k_roundEven_IntrinsicKind:
3369 case k_round_IntrinsicKind:
3370 // WGSL has no built-in roundEven(), but its round() is defined as:
3371 // "When e lies halfway between integers k and k + 1, the result is k when k is
3372 // even, and k + 1 when k is odd."
3373 // This is equivalent to GLSL's roundEven(). GLSL's round() is allowed to just match
3374 // roundEven().
3375 return this->assembleSimpleIntrinsic("round", call);
3376
3377 case k_reflect_IntrinsicKind:
3378 if (arguments[0]->type().isScalar()) {
3379 // I - 2 * N * I * N
3380 // Manually override the auto const-eval workaround since both I and N are used
3381 // multiple times in new binary expressions.
3382 fNeedsConstEvalWorkaround = false;
3383 std::string I = this->assembleExpression(*arguments[0], Precedence::kMultiplicative,
3384 kUsedMultipleTimes);
3385 // We force N into a let when it is constant, ensuring (2*N), (N*I), and (I*N)
3386 // avoid issues with const eval compilation failures. Technically if we were already
3387 // lifting I to a let, we could skip lifting N if we knew (2*N) would not overflow,
3388 // but this keeps logic simpler.
3389 AssembleMode mode = ConstantFolder::GetConstantValueOrNull(*arguments[1]) ?
3390 kForceLet : kUsedMultipleTimes;
3391 std::string N = this->assembleExpression(*arguments[1], Precedence::kMultiplicative,
3392 mode);
3393 return String::printf("(%s - 2 * %s * %s * %s)",
3394 I.c_str(), N.c_str(),
3395 I.c_str(), N.c_str());
3396 }
3397 return this->assembleSimpleIntrinsic("reflect", call);
3398
3399 case k_refract_IntrinsicKind:
3400 if (arguments[0]->type().isScalar()) {
3401 // WGSL only implements refract for vectors; rather than reimplementing refract from
3402 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
3403 std::string I = this->assembleExpression(*arguments[0], Precedence::kSequence);
3404 std::string N = this->assembleExpression(*arguments[1], Precedence::kSequence);
3405 std::string Eta = this->assembleExpression(*arguments[2], Precedence::kSequence);
3406 return String::printf("refract(vec2<%s>(%s, 0), vec2<%s>(%s, 0), %s).x",
3407 to_wgsl_type(fContext, arguments[0]->type()).c_str(),
3408 I.c_str(),
3409 to_wgsl_type(fContext, arguments[1]->type()).c_str(),
3410 N.c_str(),
3411 Eta.c_str());
3412 }
3413 return this->assembleSimpleIntrinsic("refract", call);
3414
3415 case k_sample_IntrinsicKind: {
3416 // Determine if a bias argument was passed in.
3417 SkASSERT(arguments.size() == 2 || arguments.size() == 3);
3418 bool callIncludesBias = (arguments.size() == 3);
3419 std::string expr;
3420 const char* close;
3421 if (fProgram.fConfig->fSettings.fSharpenTextures || callIncludesBias) {
3422 // We need to supply a bias argument; this is a separate intrinsic in WGSL.
3423 std::tie(expr, close) = this->assemblePartialSampleCall("textureSampleBias",
3424 call.type(),
3425 *arguments[0],
3426 *arguments[1]);
3427 expr += ", ";
3428 if (callIncludesBias) {
3429 expr += this->assembleExpression(*arguments[2], Precedence::kAdditive) +
3430 " + ";
3431 }
3432 expr += skstd::to_string(fProgram.fConfig->fSettings.fSharpenTextures
3433 ? kSharpenTexturesBias
3434 : 0.0f);
3435 } else {
3436 // No bias is necessary, so we can call `textureSample` directly.
3437 std::tie(expr, close) = this->assemblePartialSampleCall("textureSample",
3438 call.type(),
3439 *arguments[0],
3440 *arguments[1]);
3441
3442 }
3443
3444 return expr + close;
3445 }
3446 case k_sampleLod_IntrinsicKind: {
3447 auto [expr, close] = this->assemblePartialSampleCall("textureSampleLevel",
3448 call.type(),
3449 *arguments[0],
3450 *arguments[1]);
3451 expr += ", " + this->assembleExpression(*arguments[2], Precedence::kSequence);
3452
3453 return expr + close;
3454 }
3455 case k_sampleGrad_IntrinsicKind: {
3456 auto [expr, close] = this->assemblePartialSampleCall("textureSampleGrad",
3457 call.type(),
3458 *arguments[0],
3459 *arguments[1]);
3460
3461 expr += ", " + this->assembleExpression(*arguments[2], Precedence::kSequence);
3462 expr += ", " + this->assembleExpression(*arguments[3], Precedence::kSequence);
3463 return expr + close;
3464 }
3465 case k_textureHeight_IntrinsicKind:
3466 return this->assembleSimpleIntrinsic("textureDimensions", call) + ".y";
3467
3468 case k_textureRead_IntrinsicKind: {
3469 // We need to inject an extra argument for the mip-level. We don't plan on using mipmaps
3470 // in our storage textures, so we can just pass zero.
3471 auto [expr, close] = this->assemblePartialSampleCall("textureLoad",
3472 call.type(),
3473 *arguments[0],
3474 *arguments[1]);
3475 expr += ", 0";
3476 return expr + close;
3477 }
3478 case k_textureWidth_IntrinsicKind:
3479 return this->assembleSimpleIntrinsic("textureDimensions", call) + ".x";
3480
3481 case k_textureWrite_IntrinsicKind:
3482 return this->assembleSimpleIntrinsic("textureStore", call,
3483 /*wgslOnlySupportsHighPrecision=*/true);
3484
3485 case k_unpackHalf2x16_IntrinsicKind:
3486 return this->assembleSimpleIntrinsic("unpack2x16float", call);
3487
3488 case k_unpackSnorm2x16_IntrinsicKind:
3489 return this->assembleSimpleIntrinsic("unpack2x16snorm", call);
3490
3491 case k_unpackSnorm4x8_IntrinsicKind:
3492 return this->assembleSimpleIntrinsic("unpack4x8snorm", call);
3493
3494 case k_unpackUnorm2x16_IntrinsicKind:
3495 return this->assembleSimpleIntrinsic("unpack2x16unorm", call);
3496
3497 case k_unpackUnorm4x8_IntrinsicKind:
3498 return this->assembleSimpleIntrinsic("unpack4x8unorm", call);
3499
3500 case k_clamp_IntrinsicKind:
3501 case k_max_IntrinsicKind:
3502 case k_min_IntrinsicKind:
3503 case k_smoothstep_IntrinsicKind:
3504 case k_step_IntrinsicKind:
3505 return this->assembleVectorizedIntrinsic(call.function().name(), call);
3506
3507 case k_abs_IntrinsicKind:
3508 case k_acos_IntrinsicKind:
3509 case k_all_IntrinsicKind:
3510 case k_any_IntrinsicKind:
3511 case k_asin_IntrinsicKind:
3512 case k_atomicAdd_IntrinsicKind:
3513 case k_atomicLoad_IntrinsicKind:
3514 case k_atomicStore_IntrinsicKind:
3515 case k_ceil_IntrinsicKind:
3516 case k_cos_IntrinsicKind:
3517 case k_cross_IntrinsicKind:
3518 case k_degrees_IntrinsicKind:
3519 case k_distance_IntrinsicKind:
3520 case k_exp_IntrinsicKind:
3521 case k_exp2_IntrinsicKind:
3522 case k_floor_IntrinsicKind:
3523 case k_fract_IntrinsicKind:
3524 case k_length_IntrinsicKind:
3525 case k_log_IntrinsicKind:
3526 case k_log2_IntrinsicKind:
3527 case k_radians_IntrinsicKind:
3528 case k_pow_IntrinsicKind:
3529 case k_saturate_IntrinsicKind:
3530 case k_sign_IntrinsicKind:
3531 case k_sin_IntrinsicKind:
3532 case k_sqrt_IntrinsicKind:
3533 case k_storageBarrier_IntrinsicKind:
3534 case k_tan_IntrinsicKind:
3535 case k_workgroupBarrier_IntrinsicKind:
3536 default:
3537 return this->assembleSimpleIntrinsic(call.function().name(), call);
3538 }
3539 }
3540
3541 static std::string generate_inverse2x2(const char* scalarName, const char* suffix) {
3542 return SkSL::String::printf(
3543 "fn inverse_2x2%s(m: mat2x2<%s>) -> mat2x2<%s> {\n"
3544 "return mat2x2<%s>(m[1].y, -m[0].y, -m[1].x, m[0].x) * (1/determinant(m));\n"
3545 "}\n", suffix, scalarName, scalarName, scalarName);
3546 }
3547
3548 static std::string generate_inverse3x3(const char* scalarName, const char* suffix) {
3549 return SkSL::String::printf(
3550 "fn inverse_3x3%s(m: mat3x3<%s>) -> mat3x3<%s> {\n"
3551 "let a00 = m[0].x; let a01 = m[0].y; let a02 = m[0].z;\n"
3552 "let a10 = m[1].x; let a11 = m[1].y; let a12 = m[1].z;\n"
3553 "let a20 = m[2].x; let a21 = m[2].y; let a22 = m[2].z;\n"
3554 "let b01 = a22*a11 - a12*a21;\n"
3555 "let b11 = -a22*a10 + a12*a20;\n"
3556 "let b21 = a21*a10 - a11*a20;\n"
3557 "let det = a00*b01 + a01*b11 + a02*b21;\n"
3558 "return mat3x3<%s>(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),\n"
3559 "b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),\n"
3560 "b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);\n"
3561 "}\n", suffix, scalarName, scalarName, scalarName);
3562 }
3563
3564 static std::string generate_inverse4x4(const char* scalarName, const char* suffix) {
3565 return SkSL::String::printf(
3566 "fn inverse_4x4%s(m: mat4x4<%s>) -> mat4x4<%s>{\n"
3567 "let a00 = m[0].x; let a01 = m[0].y; let a02 = m[0].z; let a03 = m[0].w;\n"
3568 "let a10 = m[1].x; let a11 = m[1].y; let a12 = m[1].z; let a13 = m[1].w;\n"
3569 "let a20 = m[2].x; let a21 = m[2].y; let a22 = m[2].z; let a23 = m[2].w;\n"
3570 "let a30 = m[3].x; let a31 = m[3].y; let a32 = m[3].z; let a33 = m[3].w;\n"
3571 "let b00 = a00*a11 - a01*a10;\n"
3572 "let b01 = a00*a12 - a02*a10;\n"
3573 "let b02 = a00*a13 - a03*a10;\n"
3574 "let b03 = a01*a12 - a02*a11;\n"
3575 "let b04 = a01*a13 - a03*a11;\n"
3576 "let b05 = a02*a13 - a03*a12;\n"
3577 "let b06 = a20*a31 - a21*a30;\n"
3578 "let b07 = a20*a32 - a22*a30;\n"
3579 "let b08 = a20*a33 - a23*a30;\n"
3580 "let b09 = a21*a32 - a22*a31;\n"
3581 "let b10 = a21*a33 - a23*a31;\n"
3582 "let b11 = a22*a33 - a23*a32;\n"
3583 "let det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;\n"
3584 "return mat4x4<%s>(a11*b11 - a12*b10 + a13*b09,\n"
3585 "a02*b10 - a01*b11 - a03*b09,\n"
3586 "a31*b05 - a32*b04 + a33*b03,\n"
3587 "a22*b04 - a21*b05 - a23*b03,\n"
3588 "a12*b08 - a10*b11 - a13*b07,\n"
3589 "a00*b11 - a02*b08 + a03*b07,\n"
3590 "a32*b02 - a30*b05 - a33*b01,\n"
3591 "a20*b05 - a22*b02 + a23*b01,\n"
3592 "a10*b10 - a11*b08 + a13*b06,\n"
3593 "a01*b08 - a00*b10 - a03*b06,\n"
3594 "a30*b04 - a31*b02 + a33*b00,\n"
3595 "a21*b02 - a20*b04 - a23*b00,\n"
3596 "a11*b07 - a10*b09 - a12*b06,\n"
3597 "a00*b09 - a01*b07 + a02*b06,\n"
3598 "a31*b01 - a30*b03 - a32*b00,\n"
3599 "a20*b03 - a21*b01 + a22*b00) * (1/det);\n"
3600 "}\n", suffix, scalarName, scalarName, scalarName);
3601 }
3602
3603 // Generates outer_product_$Cx$R(vec$R<f32}>, vec$C<f32>) -> mat$Cx$R<f32> or its f16 variant.
3604 static std::string gen_outer_product_fn(const char* scalarName, const char* suffix, int c, int r) {
3605 return String::printf(
3606 "fn outer_product_%dx%d%s(a: vec%d<%s>, b: vec%d<%s>) -> mat%dx%d<%s> {\n"
3607 "var m : mat%dx%d<%s>;\n"
3608 "for (var c = 0; c < %d; c++) { m[c] = a * b[c]; }\n"
3609 "return m;\n"
3610 "}\n",
3611 /* outer_product_$Cx$R$s */ c, r, suffix,
3612 /* vec$R */ r, scalarName,
3613 /* vec$C */ c, scalarName,
3614 /* mat$Cx$R */ c, r, scalarName,
3615 /* mat$Cx$R */ c, r, scalarName,
3616 /* c < $C */ c);
3617 }
3618
3619 std::string WGSLCodeGenerator::assembleInversePolyfill(const FunctionCall& call) {
3620 const ExpressionArray& arguments = call.arguments();
3621 const Type& type = arguments.front()->type();
3622
3623 // The `inverse` intrinsic should only accept a single-argument square matrix.
3624 // Once we implement f16 support, these polyfills will need to be updated to support `hmat`;
3625 // for the time being, all floats in WGSL are f32, so we don't need to worry about precision.
3626 SkASSERT(arguments.size() == 1);
3627 SkASSERT(type.isMatrix());
3628 SkASSERT(type.rows() == type.columns());
3629
3630 const bool useF16 = type_is_low_precision(type, fContext);
3631 WrittenPolyfills* polyfill = useF16 ? &fF16Polyfills : &fF32Polyfills;
3632 const char* typeName = useF16 ? "f16" : "f32";
3633 const char* suffix = useF16 ? "h" : "f";
3634
3635 const int idx = type.rows() - 2;
3636 if (!polyfill->fInverse[idx]) {
3637 using InverseGenFn = std::string(*)(const char*, const char*);
3638 static constexpr std::array<InverseGenFn, 3> kTemplates{generate_inverse2x2,
3639 generate_inverse3x3,
3640 generate_inverse4x4};
3641 polyfill->fInverse[idx] = true;
3642 fHeader.writeText(kTemplates[idx](typeName, suffix).c_str());
3643 }
3644 return this->assembleSimpleIntrinsic(String::printf("inverse_%dx%d%s",
3645 type.rows(), type.columns(), suffix), call);
3646 }
3647
3648 std::string WGSLCodeGenerator::assembleOuterProductPolyfill(const FunctionCall& call) {
3649 // The outer product should take two vector arguments, with the first type's component count
3650 // defining R and the second type's component count defining C.
3651 const ExpressionArray& arguments = call.arguments();
3652 SkASSERT(arguments.size() == 2);
3653 SkASSERT(arguments[0]->type().isVector() && arguments[1]->type().isVector());
3654 SkASSERT(call.type().isMatrix());
3655
3656 const int r = arguments[0]->type().columns();
3657 const int c = arguments[1]->type().columns();
3658 SkASSERT(r == call.type().rows() && c == call.type().columns());
3659
3660 const bool useF16 = type_is_low_precision(call.type(), fContext);
3661 WrittenPolyfills* polyfill = useF16 ? &fF16Polyfills : &fF32Polyfills;
3662 const char* typeName = useF16 ? "f16" : "f32";
3663 const char* suffix = useF16 ? "h" : "f";
3664
3665 const int cIdx = c - 2;
3666 const int rIdx = r - 2;
3667 if (!polyfill->fOuterProduct[cIdx][rIdx]) {
3668 polyfill->fOuterProduct[cIdx][rIdx] = true;
3669 fHeader.writeText(gen_outer_product_fn(typeName, suffix, c, r).c_str());
3670 }
3671
3672 return this->assembleSimpleIntrinsic(String::printf("outer_product_%dx%d%s",
3673 c, r, suffix), call);
3674 }
3675
3676 std::string WGSLCodeGenerator::assembleFunctionCall(const FunctionCall& call,
3677 Precedence parentPrecedence) {
3678 const FunctionDeclaration& func = call.function();
3679 std::string result;
3680
3681 // Helper for wrapping user and intrinsic function calls that might have side effects.
3682 auto emitCall = [&](const std::string& expr, bool forceLet=false) {
3683 if (call.type().isVoid() || parentPrecedence >= Precedence::kStatement) {
3684 // If this is true, the assembled expression won't be used directly by the caller, so we
3685 // need to write it out as its own statement to preserve any side effects.
3686 SkASSERT(parentPrecedence >= Precedence::kSequence);
3687 this->write(expr);
3688 this->writeLine(";");
3689 return std::string(); // Will be unused
3690 } else if (forceLet) {
3691 // The function call is used by the caller, but we need to write the actual call *now*
3692 // before additional statements.
3693 return this->writeScratchLet(expr);
3694 } else {
3695 // Can inline the call's expression into the caller's expression
3696 return expr;
3697 }
3698 };
3699
3700 // Many intrinsics need to be rewritten in WGSL.
3701 if (func.isIntrinsic()) {
3702 return emitCall(this->assembleIntrinsicCall(call, func.intrinsicKind(), parentPrecedence));
3703 }
3704
3705 // We implement function out-parameters by declaring them as pointers. SkSL follows GLSL's
3706 // out-parameter semantics, in which out-parameters are only written back to the original
3707 // variable after the function's execution is complete (see
3708 // https://www.khronos.org/opengl/wiki/Core_Language_(GLSL)#Parameters).
3709 //
3710 // In addition, SkSL supports swizzles and array index expressions to be passed into
3711 // out-parameters; however, WGSL does not allow taking their address into a pointer.
3712 //
3713 // We support these by using LValues to create temporary copies and then pass pointers to the
3714 // copies. Once the function returns, we copy the values back to the LValue.
3715
3716 // First detect which arguments are passed to out-parameters.
3717 // TODO: rewrite this method in terms of LValues.
3718 const ExpressionArray& args = call.arguments();
3719 SkSpan<Variable* const> params = func.parameters();
3720 SkASSERT(SkToSizeT(args.size()) == params.size());
3721
3722 STArray<16, std::unique_ptr<LValue>> writeback;
3723 STArray<16, std::string> substituteArgument;
3724 writeback.reserve_exact(args.size());
3725 substituteArgument.reserve_exact(args.size());
3726
3727 bool needsWriteback = false;
3728 for (int index = 0; index < args.size(); ++index) {
3729 if (params[index]->modifierFlags() & ModifierFlag::kOut) {
3730 std::unique_ptr<LValue> lvalue = this->makeLValue(*args[index]);
3731 if (params[index]->modifierFlags() & ModifierFlag::kIn) {
3732 // Load the lvalue's contents into the substitute argument.
3733 substituteArgument.push_back(this->writeScratchVar(args[index]->type(),
3734 lvalue->load()));
3735 } else {
3736 // Create a substitute argument, but leave it uninitialized.
3737 substituteArgument.push_back(this->writeScratchVar(args[index]->type()));
3738 }
3739 writeback.push_back(std::move(lvalue));
3740 needsWriteback = true;
3741 } else {
3742 substituteArgument.push_back(std::string());
3743 writeback.push_back(nullptr);
3744 }
3745 }
3746
3747 std::string expr = this->assembleName(func.mangledName());
3748 expr.push_back('(');
3749 auto separator = SkSL::String::Separator();
3750
3751 if (std::string funcDepArgs = this->functionDependencyArgs(func); !funcDepArgs.empty()) {
3752 expr += funcDepArgs;
3753 separator();
3754 }
3755
3756 // Pass the function arguments, or any substitutes as needed.
3757 for (int index = 0; index < args.size(); ++index) {
3758 expr += separator();
3759 if (!substituteArgument[index].empty()) {
3760 // We need to take the address of the variable and pass it down as a pointer.
3761 expr += '&' + substituteArgument[index];
3762 } else if (args[index]->type().isSampler()) {
3763 // If the argument is a sampler, we need to pass the texture _and_ its associated
3764 // sampler. (Function parameter lists also convert sampler parameters into a matching
3765 // texture/sampler parameter pair.)
3766 expr += this->assembleExpression(*args[index], Precedence::kSequence);
3767 expr += kTextureSuffix;
3768 expr += ", ";
3769 expr += this->assembleExpression(*args[index], Precedence::kSequence);
3770 expr += kSamplerSuffix;
3771 } else if (args[index]->type().isUnsizedArray()) {
3772 // If the array is in the parameter storage space then manually just pass it through
3773 // since it is already a pointer.
3774 if (args[index]->is<VariableReference>()) {
3775 const Variable* v = args[index]->as<VariableReference>().variable();
3776 // A variable reference to an unsized array should always be a parameter,
3777 // because unsized arrays coming from uniforms will have the `FieldAccess`
3778 // expression type.
3779 SkASSERT(v->storage() == Variable::Storage::kParameter);
3780 expr += this->assembleName(v->mangledName());
3781 } else {
3782 expr += "&(" + this->assembleExpression(*args[index], Precedence::kSequence) + ")";
3783 }
3784 } else {
3785 expr += this->assembleExpression(*args[index], Precedence::kSequence);
3786 }
3787 }
3788 expr += ')';
3789
3790 // If we have to write substitutions after the function call, we have to force the function call
3791 // into a scratch let so that variable can be returned as the expression.
3792 result = emitCall(expr, /*forceLet=*/needsWriteback);
3793
3794 if (needsWriteback) {
3795 for (int index = 0; index < args.size(); ++index) {
3796 if (!substituteArgument[index].empty()) {
3797 this->writeLine(writeback[index]->store(substituteArgument[index]));
3798 }
3799 }
3800 }
3801
3802 // Return the result of invoking the function.
3803 return result;
3804 }
3805
3806 std::string WGSLCodeGenerator::assembleIndexExpression(const IndexExpression& i) {
3807 // Put the index value into a let-expression.
3808 std::string idx = this->assembleExpression(*i.index(), Precedence::kExpression,
3809 kUsedMultipleTimes);
3810 return this->assembleExpression(*i.base(), Precedence::kPostfix) + "[" + idx + "]";
3811 }
3812
3813 std::string WGSLCodeGenerator::assembleLiteral(const Literal& l) {
3814 const Type& type = l.type();
3815 if (type.isFloat() || type.isBoolean()) {
3816 std::string value = l.description(OperatorPrecedence::kExpression);
3817 if (type_is_low_precision(type, fContext)) {
3818 SkASSERT(type.isFloat());
3819 value += "h";
3820 }
3821 return value;
3822 }
3823 SkASSERT(type.isInteger());
3824 if (type.matches(*fContext.fTypes.fUInt)) {
3825 return std::to_string(l.intValue() & 0xffffffff) + "u";
3826 } else if (type.matches(*fContext.fTypes.fUShort)) {
3827 return std::to_string(l.intValue() & 0xffff) + "u";
3828 } else {
3829 return std::to_string(l.intValue());
3830 }
3831 }
3832
3833 std::string WGSLCodeGenerator::assembleIncrementExpr(const Type& type) {
3834 // `type(`
3835 std::string expr = to_wgsl_type(fContext, type);
3836 expr.push_back('(');
3837
3838 // `1, 1, 1...)`
3839 auto separator = SkSL::String::Separator();
3840 for (int slots = type.slotCount(); slots > 0; --slots) {
3841 expr += separator();
3842 expr += "1";
3843 }
3844 expr.push_back(')');
3845 return expr;
3846 }
3847
3848 std::string WGSLCodeGenerator::assemblePrefixExpression(const PrefixExpression& p,
3849 Precedence parentPrecedence) {
3850 // Unary + does nothing, so we omit it from the output.
3851 Operator op = p.getOperator();
3852 if (op.kind() == Operator::Kind::PLUS) {
3853 return this->assembleExpression(*p.operand(), Precedence::kPrefix);
3854 }
3855
3856 // Pre-increment/decrement expressions have no direct equivalent in WGSL.
3857 if (op.kind() == Operator::Kind::PLUSPLUS || op.kind() == Operator::Kind::MINUSMINUS) {
3858 std::unique_ptr<LValue> lvalue = this->makeLValue(*p.operand());
3859 if (!lvalue) {
3860 return "";
3861 }
3862
3863 // Generate the new value: `lvalue + type(1, 1, 1...)`.
3864 std::string newValue =
3865 lvalue->load() +
3866 (p.getOperator().kind() == Operator::Kind::PLUSPLUS ? " + " : " - ") +
3867 this->assembleIncrementExpr(p.operand()->type());
3868 this->writeLine(lvalue->store(newValue));
3869 return lvalue->load();
3870 }
3871
3872 // WGSL natively supports unary negation/not expressions (!,~,-).
3873 SkASSERT(op.kind() == OperatorKind::LOGICALNOT ||
3874 op.kind() == OperatorKind::BITWISENOT ||
3875 op.kind() == OperatorKind::MINUS);
3876
3877 // The unary negation operator only applies to scalars and vectors. For other mathematical
3878 // objects (such as matrices) we can express it as a multiplication by -1.
3879 std::string expr;
3880 const bool needsNegation = op.kind() == Operator::Kind::MINUS &&
3881 !p.operand()->type().isScalar() && !p.operand()->type().isVector();
3882 const bool needParens = needsNegation || Precedence::kPrefix >= parentPrecedence;
3883
3884 if (needParens) {
3885 expr.push_back('(');
3886 }
3887
3888 if (needsNegation) {
3889 expr += "-1.0 * ";
3890 expr += this->assembleExpression(*p.operand(), Precedence::kMultiplicative);
3891 } else {
3892 expr += p.getOperator().tightOperatorName();
3893 expr += this->assembleExpression(*p.operand(), Precedence::kPrefix);
3894 }
3895
3896 if (needParens) {
3897 expr.push_back(')');
3898 }
3899
3900 return expr;
3901 }
3902
3903 std::string WGSLCodeGenerator::assemblePostfixExpression(const PostfixExpression& p,
3904 Precedence parentPrecedence) {
3905 SkASSERT(p.getOperator().kind() == Operator::Kind::PLUSPLUS ||
3906 p.getOperator().kind() == Operator::Kind::MINUSMINUS);
3907
3908 // Post-increment/decrement expressions have no direct equivalent in WGSL; they do exist as a
3909 // standalone statement for convenience, but these aren't the same as SkSL's post-increments.
3910 std::unique_ptr<LValue> lvalue = this->makeLValue(*p.operand());
3911 if (!lvalue) {
3912 return "";
3913 }
3914
3915 // If the expression is used, create a let-copy of the original value.
3916 // (At statement-level precedence, we know the value is unused and can skip this let-copy.)
3917 std::string originalValue;
3918 if (parentPrecedence != Precedence::kStatement) {
3919 originalValue = this->writeScratchLet(lvalue->load());
3920 }
3921 // Generate the new value: `lvalue + type(1, 1, 1...)`.
3922 std::string newValue = lvalue->load() +
3923 (p.getOperator().kind() == Operator::Kind::PLUSPLUS ? " + " : " - ") +
3924 this->assembleIncrementExpr(p.operand()->type());
3925 this->writeLine(lvalue->store(newValue));
3926
3927 return originalValue;
3928 }
3929
3930 std::string WGSLCodeGenerator::assembleSwizzle(const Swizzle& swizzle) {
3931 return this->assembleExpression(*swizzle.base(), Precedence::kPostfix) + "." +
3932 Swizzle::MaskString(swizzle.components());
3933 }
3934
3935 std::string WGSLCodeGenerator::writeScratchVar(const Type& type, const std::string& value) {
3936 std::string scratchVarName = "_skTemp" + std::to_string(fScratchCount++);
3937 this->write("var ");
3938 this->write(scratchVarName);
3939 this->write(": ");
3940 this->write(to_wgsl_type(fContext, type));
3941 if (!value.empty()) {
3942 this->write(" = ");
3943 this->write(value);
3944 }
3945 this->writeLine(";");
3946 return scratchVarName;
3947 }
3948
3949 std::string WGSLCodeGenerator::writeScratchLet(const std::string& expr,
3950 bool isCompileTimeConstant) {
3951 std::string scratchVarName = "_skTemp" + std::to_string(fScratchCount++);
3952 this->write(fAtFunctionScope && !isCompileTimeConstant ? "let " : "const ");
3953 this->write(scratchVarName);
3954 this->write(" = ");
3955 this->write(expr);
3956 this->writeLine(";");
3957 return scratchVarName;
3958 }
3959
3960 std::string WGSLCodeGenerator::assembleTernaryExpression(const TernaryExpression& t,
3961 Precedence parentPrecedence) {
3962 std::string expr;
3963
3964 // The trivial case is when neither branch has side effects and evaluate to a scalar or vector
3965 // type. This can be represented with a call to the WGSL `select` intrinsic. Select doesn't
3966 // support short-circuiting, so we should only use it when both the true- and false-expressions
3967 // are trivial to evaluate.
3968 if ((t.type().isScalar() || t.type().isVector()) &&
3969 !Analysis::HasSideEffects(*t.test()) &&
3970 Analysis::IsTrivialExpression(*t.ifTrue()) &&
3971 Analysis::IsTrivialExpression(*t.ifFalse())) {
3972
3973 bool needParens = Precedence::kTernary >= parentPrecedence;
3974 if (needParens) {
3975 expr.push_back('(');
3976 }
3977 expr += "select(";
3978 expr += this->assembleExpression(*t.ifFalse(), Precedence::kSequence);
3979 expr += ", ";
3980 expr += this->assembleExpression(*t.ifTrue(), Precedence::kSequence);
3981 expr += ", ";
3982
3983 bool isVector = t.type().isVector();
3984 if (isVector) {
3985 // Splat the condition expression into a vector.
3986 expr += String::printf("vec%d<bool>(", t.type().columns());
3987 }
3988 expr += this->assembleExpression(*t.test(), Precedence::kSequence);
3989 if (isVector) {
3990 expr.push_back(')');
3991 }
3992 expr.push_back(')');
3993 if (needParens) {
3994 expr.push_back(')');
3995 }
3996 } else {
3997 // WGSL does not support ternary expressions. Instead, we hoist the expression out into the
3998 // surrounding block, convert it into an if statement, and write the result to a synthesized
3999 // variable. Instead of the original expression, we return that variable.
4000 expr = this->writeScratchVar(t.ifTrue()->type());
4001
4002 std::string testExpr = this->assembleExpression(*t.test(), Precedence::kExpression);
4003 this->write("if ");
4004 this->write(testExpr);
4005 this->writeLine(" {");
4006
4007 ++fIndentation;
4008 std::string trueExpr = this->assembleExpression(*t.ifTrue(), Precedence::kAssignment);
4009 this->write(expr);
4010 this->write(" = ");
4011 this->write(trueExpr);
4012 this->writeLine(";");
4013 --fIndentation;
4014
4015 this->writeLine("} else {");
4016
4017 ++fIndentation;
4018 std::string falseExpr = this->assembleExpression(*t.ifFalse(), Precedence::kAssignment);
4019 this->write(expr);
4020 this->write(" = ");
4021 this->write(falseExpr);
4022 this->writeLine(";");
4023 --fIndentation;
4024
4025 this->writeLine("}");
4026 }
4027 return expr;
4028 }
4029
4030 std::string WGSLCodeGenerator::variablePrefix(const Variable& v) {
4031 if (v.storage() == Variable::Storage::kGlobal) {
4032 // If the field refers to a pipeline IO parameter, then we access it via the synthesized IO
4033 // structs. We make an explicit exception for `sk_PointSize` which we declare as a
4034 // placeholder variable in global scope as it is not supported by WebGPU as a pipeline IO
4035 // parameter (see comments in `writeStageOutputStruct`).
4036 if (v.modifierFlags() & ModifierFlag::kIn) {
4037 return "_stageIn.";
4038 }
4039 if (v.modifierFlags() & ModifierFlag::kOut) {
4040 return "(*_stageOut).";
4041 }
4042
4043 // If the field refers to an anonymous-interface-block structure, access it via the
4044 // synthesized `_uniform0` or `_storage1` global.
4045 if (const InterfaceBlock* ib = v.interfaceBlock()) {
4046 const Type& ibType = ib->var()->type().componentType();
4047 if (const std::string* ibName = fInterfaceBlockNameMap.find(&ibType)) {
4048 return *ibName + '.';
4049 }
4050 }
4051
4052 // If the field refers to an top-level uniform, access it via the synthesized
4053 // `_globalUniforms` global. (Note that this should only occur in test code; Skia will
4054 // always put uniforms in an interface block.)
4055 if (is_in_global_uniforms(v)) {
4056 return "_globalUniforms.";
4057 }
4058 }
4059
4060 return "";
4061 }
4062
4063 std::string WGSLCodeGenerator::variableReferenceNameForLValue(const VariableReference& r) {
4064 const Variable& v = *r.variable();
4065
4066 if (v.storage() == Variable::Storage::kParameter &&
4067 (v.modifierFlags() & ModifierFlag::kOut || v.type().isUnsizedArray())) {
4068 // This is an out-parameter or unsized array parameter; it's pointer-typed, so we need to
4069 // dereference it. We wrap the dereference in parentheses, in case the value is used in an
4070 // access expression later.
4071 return "(*" + this->assembleName(v.mangledName()) + ')';
4072 }
4073
4074 if (is_in_global_uniforms(v)) {
4075 // Assemble polyfill access (see assembleFieldAccess)
4076 SkASSERT(fSyntheticGlobalUniformsBlock);
4077 FieldPolyfillInfo* polyfillInfo = nullptr;
4078 const Type& globalStruct = fSyntheticGlobalUniformsBlock->var()->type().componentType();
4079 for (const Field& f : globalStruct.fields()) {
4080 if (f.fName == v.name()) {
4081 polyfillInfo = fFieldPolyfillMap.find(&f);
4082 SkASSERT(polyfillInfo);
4083 break;
4084 }
4085 }
4086
4087 if (polyfillInfo) {
4088 // We found a global variable declaration that had to be polyfilled, so switch to its
4089 // replacement expression. This is simpler than assembleFieldAccess() because we don't
4090 // need to worry about index expressions.
4091 polyfillInfo->fWasAccessed = true;
4092 return polyfillInfo->fReplacementName;
4093 }
4094
4095 // Fall through for a regular global variable access
4096 }
4097
4098 return this->variablePrefix(v) + this->assembleName(v.mangledName());
4099 }
4100
4101 std::string WGSLCodeGenerator::assembleVariableReference(const VariableReference& r) {
4102 // TODO(b/294274678): Correctly handle RTFlip for built-ins.
4103 const Variable& v = *r.variable();
4104
4105 // Insert a conversion expression if this is a built-in variable whose type differs from the
4106 // SkSL.
4107 std::string expr;
4108 std::optional<std::string_view> conversion = needs_builtin_type_conversion(v);
4109 if (conversion.has_value()) {
4110 expr += *conversion;
4111 expr.push_back('(');
4112 }
4113
4114 expr += this->variableReferenceNameForLValue(r);
4115
4116 if (conversion.has_value()) {
4117 expr.push_back(')');
4118 }
4119
4120 return expr;
4121 }
4122
4123 std::string WGSLCodeGenerator::assembleAnyConstructor(const AnyConstructor& c) {
4124 std::string expr = to_wgsl_type(fContext, c.type());
4125 expr.push_back('(');
4126 auto separator = SkSL::String::Separator();
4127 for (const auto& e : c.argumentSpan()) {
4128 expr += separator();
4129 expr += this->assembleExpression(*e, Precedence::kSequence);
4130 }
4131 expr.push_back(')');
4132 return expr;
4133 }
4134
4135 std::string WGSLCodeGenerator::assembleConstructorCompound(const ConstructorCompound& c) {
4136 if (c.type().isVector()) {
4137 return this->assembleConstructorCompoundVector(c);
4138 } else if (c.type().isMatrix()) {
4139 return this->assembleConstructorCompoundMatrix(c);
4140 } else {
4141 fContext.fErrors->error(c.fPosition, "unsupported compound constructor");
4142 return {};
4143 }
4144 }
4145
4146 std::string WGSLCodeGenerator::assembleConstructorCompoundVector(const ConstructorCompound& c) {
4147 // WGSL supports constructing vectors from a mix of scalars and vectors but
4148 // not matrices (see https://www.w3.org/TR/WGSL/#type-constructor-expr).
4149 //
4150 // SkSL supports vec4(mat2x2) which we handle specially.
4151 if (c.type().columns() == 4 && c.argumentSpan().size() == 1) {
4152 const Expression& arg = *c.argumentSpan().front();
4153 if (arg.type().isMatrix()) {
4154 SkASSERT(arg.type().columns() == 2);
4155 SkASSERT(arg.type().rows() == 2);
4156
4157 std::string matrix = this->assembleExpression(arg, Precedence::kPostfix,
4158 kUsedMultipleTimes);
4159 return String::printf("%s(%s[0], %s[1])", to_wgsl_type(fContext, c.type()).c_str(),
4160 matrix.c_str(),
4161 matrix.c_str());
4162 }
4163 }
4164 return this->assembleAnyConstructor(c);
4165 }
4166
4167 std::string WGSLCodeGenerator::assembleConstructorCompoundMatrix(const ConstructorCompound& ctor) {
4168 SkASSERT(ctor.type().isMatrix());
4169
4170 std::string expr = to_wgsl_type(fContext, ctor.type()) + '(';
4171 auto separator = String::Separator();
4172 for (const std::unique_ptr<Expression>& arg : ctor.arguments()) {
4173 SkASSERT(arg->type().isScalar() || arg->type().isVector());
4174
4175 if (arg->type().isScalar()) {
4176 expr += separator();
4177 expr += this->assembleExpression(*arg, Precedence::kSequence);
4178 } else {
4179 std::string inner = this->assembleExpression(*arg, Precedence::kSequence,
4180 kUsedMultipleTimes);
4181 int numSlots = arg->type().slotCount();
4182 for (int slot = 0; slot < numSlots; ++slot) {
4183 String::appendf(&expr, "%s%s[%d]", separator().c_str(), inner.c_str(), slot);
4184 }
4185 }
4186 }
4187 return expr + ')';
4188 }
4189
4190 std::string WGSLCodeGenerator::assembleConstructorDiagonalMatrix(
4191 const ConstructorDiagonalMatrix& c) {
4192 const Type& type = c.type();
4193 SkASSERT(type.isMatrix());
4194 SkASSERT(c.argument()->type().isScalar());
4195
4196 // Evaluate the inner-expression, creating a scratch variable if necessary.
4197 std::string inner = this->assembleExpression(*c.argument(), Precedence::kAssignment,
4198 kUsedMultipleTimes);
4199
4200 // Assemble a diagonal-matrix expression.
4201 std::string expr = to_wgsl_type(fContext, type) + '(';
4202 auto separator = String::Separator();
4203 for (int col = 0; col < type.columns(); ++col) {
4204 for (int row = 0; row < type.rows(); ++row) {
4205 expr += separator();
4206 if (col == row) {
4207 expr += inner;
4208 } else {
4209 expr += "0.0";
4210 }
4211 }
4212 }
4213 return expr + ')';
4214 }
4215
4216 std::string WGSLCodeGenerator::assembleConstructorMatrixResize(
4217 const ConstructorMatrixResize& ctor) {
4218 std::string source = this->assembleExpression(*ctor.argument(), Precedence::kSequence,
4219 kUsedMultipleTimes);
4220 int columns = ctor.type().columns();
4221 int rows = ctor.type().rows();
4222 int sourceColumns = ctor.argument()->type().columns();
4223 int sourceRows = ctor.argument()->type().rows();
4224 auto separator = String::Separator();
4225 std::string expr = to_wgsl_type(fContext, ctor.type()) + '(';
4226
4227 for (int c = 0; c < columns; ++c) {
4228 for (int r = 0; r < rows; ++r) {
4229 expr += separator();
4230 if (c < sourceColumns && r < sourceRows) {
4231 String::appendf(&expr, "%s[%d][%d]", source.c_str(), c, r);
4232 } else if (r == c) {
4233 expr += "1.0";
4234 } else {
4235 expr += "0.0";
4236 }
4237 }
4238 }
4239
4240 return expr + ')';
4241 }
4242
4243 std::string WGSLCodeGenerator::assembleConstructorArrayCast(const ConstructorArrayCast& ctor,
4244 Precedence parentPrecedence) {
4245 SkASSERT(!ctor.type().isUnsizedArray()); // Can't iterate over unbounded elements
4246
4247 // Our SkSL -> WGSL conversion only distinguishes f16 and f32, so any other array cast turns
4248 // into equivalent types in WGSL. Check the component type of the ctor and arg, since those are
4249 // both array types, which has to be peeled away.
4250 if (to_wgsl_type(fContext, ctor.type().componentType()) ==
4251 to_wgsl_type(fContext, ctor.argument()->type().componentType())) {
4252 return this->assembleExpression(*ctor.argument(), parentPrecedence);
4253 }
4254
4255 // Construct a new array of the ctor's type
4256 std::string expr = to_wgsl_type(fContext, ctor.type());
4257 expr += "(";
4258
4259 std::string elemType = to_wgsl_type(fContext, ctor.type().componentType());
4260 std::string arrayArg = this->assembleExpression(*ctor.argument(),
4261 Precedence::kPostfix,
4262 AssembleMode::kUsedMultipleTimes);
4263
4264 // Each value of the new array is a cast of an element from the ctor's argument.
4265 int arrayLen = ctor.type().columns();
4266 auto separator = String::Separator();
4267 for (int i = 0; i < arrayLen; ++i) {
4268 expr += separator();
4269 String::appendf(&expr, "%s(%s[%d])", elemType.c_str(), arrayArg.c_str(), i);
4270 }
4271
4272 expr += ")";
4273 return expr;
4274 }
4275
4276 std::string WGSLCodeGenerator::assembleEqualityExpression(const Type& left,
4277 const std::string& leftName,
4278 const Type& right,
4279 const std::string& rightName,
4280 Operator op,
4281 Precedence parentPrecedence) {
4282 SkASSERT(op.kind() == OperatorKind::EQEQ || op.kind() == OperatorKind::NEQ);
4283
4284 std::string expr;
4285 bool isEqual = (op.kind() == Operator::Kind::EQEQ);
4286 const char* const combiner = isEqual ? " && " : " || ";
4287
4288 if (left.isMatrix()) {
4289 // Each matrix column must be compared as if it were an individual vector.
4290 SkASSERT(right.isMatrix());
4291 SkASSERT(left.rows() == right.rows());
4292 SkASSERT(left.columns() == right.columns());
4293 int columns = left.columns();
4294 const Type& vecType = left.columnType(fContext);
4295 const char* separator = "(";
4296 for (int index = 0; index < columns; ++index) {
4297 expr += separator;
4298 std::string suffix = '[' + std::to_string(index) + ']';
4299 expr += this->assembleEqualityExpression(vecType, leftName + suffix,
4300 vecType, rightName + suffix,
4301 op, Precedence::kParentheses);
4302 separator = combiner;
4303 }
4304 return expr + ')';
4305 }
4306
4307 if (left.isArray()) {
4308 SkASSERT(right.matches(left));
4309 const Type& indexedType = left.componentType();
4310 const char* separator = "(";
4311 for (int index = 0; index < left.columns(); ++index) {
4312 expr += separator;
4313 std::string suffix = '[' + std::to_string(index) + ']';
4314 expr += this->assembleEqualityExpression(indexedType, leftName + suffix,
4315 indexedType, rightName + suffix,
4316 op, Precedence::kParentheses);
4317 separator = combiner;
4318 }
4319 return expr + ')';
4320 }
4321
4322 if (left.isStruct()) {
4323 // Recursively compare every field in the struct.
4324 SkASSERT(right.matches(left));
4325 SkSpan<const Field> fields = left.fields();
4326
4327 const char* separator = "(";
4328 for (const Field& field : fields) {
4329 expr += separator;
4330 expr += this->assembleEqualityExpression(
4331 *field.fType, leftName + '.' + this->assembleName(field.fName),
4332 *field.fType, rightName + '.' + this->assembleName(field.fName),
4333 op, Precedence::kParentheses);
4334 separator = combiner;
4335 }
4336 return expr + ')';
4337 }
4338
4339 if (left.isVector()) {
4340 // Compare vectors via `all(x == y)` or `any(x != y)`.
4341 SkASSERT(right.isVector());
4342 SkASSERT(left.slotCount() == right.slotCount());
4343
4344 expr += isEqual ? "all(" : "any(";
4345 expr += leftName;
4346 expr += operator_name(op);
4347 expr += rightName;
4348 return expr + ')';
4349 }
4350
4351 // Compare scalars via `x == y`.
4352 SkASSERT(right.isScalar());
4353 if (parentPrecedence < Precedence::kSequence) {
4354 expr = '(';
4355 }
4356 expr += leftName;
4357 expr += operator_name(op);
4358 expr += rightName;
4359 if (parentPrecedence < Precedence::kSequence) {
4360 expr += ')';
4361 }
4362 return expr;
4363 }
4364
4365 std::string WGSLCodeGenerator::assembleEqualityExpression(const Expression& left,
4366 const Expression& right,
4367 Operator op,
4368 Precedence parentPrecedence) {
4369 // WGSL supports scalar and vector comparisons natively. We know the expressions will only
4370 // be emitted once in that case. Every other case will be poly-filled, resulting in referencing
4371 // the left and right expressions multiple times.
4372 AssembleMode mode = !left.type().isScalar() && !left.type().isVector() ?
4373 kUsedMultipleTimes : kAuto;
4374 std::string leftName = this->assembleExpression(left, Precedence::kParentheses, mode);
4375 std::string rightName = this->assembleExpression(right, Precedence::kParentheses, mode);
4376 return this->assembleEqualityExpression(left.type(), leftName, right.type(), rightName,
4377 op, parentPrecedence);
4378 }
4379
4380 void WGSLCodeGenerator::writeProgramElement(const ProgramElement& e) {
4381 switch (e.kind()) {
4382 case ProgramElement::Kind::kExtension:
4383 // TODO(skbug.com/40044196): WGSL supports extensions via the "enable" directive
4384 // (https://www.w3.org/TR/WGSL/#enable-extensions-sec ). While we could easily emit this
4385 // directive, we should first ensure that all possible SkSL extension names are
4386 // converted to their appropriate WGSL extension.
4387 break;
4388 case ProgramElement::Kind::kGlobalVar:
4389 this->writeGlobalVarDeclaration(e.as<GlobalVarDeclaration>());
4390 break;
4391 case ProgramElement::Kind::kInterfaceBlock:
4392 // All interface block declarations are handled explicitly as the "program header" in
4393 // generateCode().
4394 break;
4395 case ProgramElement::Kind::kStructDefinition:
4396 this->writeStructDefinition(e.as<StructDefinition>());
4397 break;
4398 case ProgramElement::Kind::kFunctionPrototype:
4399 // A WGSL function declaration must contain its body and the function name is in scope
4400 // for the entire program (see https://www.w3.org/TR/WGSL/#function-declaration and
4401 // https://www.w3.org/TR/WGSL/#declaration-and-scope).
4402 //
4403 // As such, we don't emit function prototypes.
4404 break;
4405 case ProgramElement::Kind::kFunction:
4406 this->writeFunction(e.as<FunctionDefinition>());
4407 break;
4408 case ProgramElement::Kind::kModifiers:
4409 this->writeModifiersDeclaration(e.as<ModifiersDeclaration>());
4410 break;
4411 default:
4412 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
4413 break;
4414 }
4415 }
4416
4417 void WGSLCodeGenerator::writeTextureOrSampler(const Variable& var,
4418 int bindingLocation,
4419 std::string_view suffix,
4420 std::string_view wgslType) {
4421 if (var.type().dimensions() != SpvDim2D) {
4422 // Skia currently only uses 2D textures.
4423 fContext.fErrors->error(var.varDeclaration()->position(), "unsupported texture dimensions");
4424 return;
4425 }
4426
4427 this->write("@group(");
4428 this->write(std::to_string(std::max(0, var.layout().fSet)));
4429 this->write(") @binding(");
4430 this->write(std::to_string(bindingLocation));
4431 this->write(") var ");
4432 this->write(this->assembleName(var.mangledName()));
4433 this->write(suffix);
4434 this->write(": ");
4435 this->write(wgslType);
4436 this->writeLine(";");
4437 }
4438
4439 void WGSLCodeGenerator::writeGlobalVarDeclaration(const GlobalVarDeclaration& d) {
4440 const VarDeclaration& decl = d.varDeclaration();
4441 const Variable& var = *decl.var();
4442 if ((var.modifierFlags() & (ModifierFlag::kIn | ModifierFlag::kOut)) ||
4443 is_in_global_uniforms(var)) {
4444 // Pipeline stage I/O parameters and top-level (non-block) uniforms are handled specially
4445 // in generateCode().
4446 return;
4447 }
4448
4449 const Type::TypeKind varKind = var.type().typeKind();
4450 if (varKind == Type::TypeKind::kSampler) {
4451 // If the sampler binding was unassigned, provide a scratch value; this will make
4452 // golden-output tests pass, but will not actually be usable for drawing.
4453 int samplerLocation = var.layout().fSampler >= 0 ? var.layout().fSampler
4454 : 10000 + fScratchCount++;
4455 this->writeTextureOrSampler(var, samplerLocation, kSamplerSuffix, "sampler");
4456
4457 // If the texture binding was unassigned, provide a scratch value (for golden-output tests).
4458 int textureLocation = var.layout().fTexture >= 0 ? var.layout().fTexture
4459 : 10000 + fScratchCount++;
4460 this->writeTextureOrSampler(var, textureLocation, kTextureSuffix, "texture_2d<f32>");
4461 return;
4462 }
4463
4464 if (varKind == Type::TypeKind::kTexture) {
4465 // If a binding location was unassigned, provide a scratch value (for golden-output tests).
4466 int textureLocation = var.layout().fBinding >= 0 ? var.layout().fBinding
4467 : 10000 + fScratchCount++;
4468 // For a texture without an associated sampler, we don't apply a suffix.
4469 this->writeTextureOrSampler(var, textureLocation, /*suffix=*/"",
4470 to_wgsl_type(fContext, var.type(), &var.layout()));
4471 return;
4472 }
4473
4474 std::string initializer;
4475 if (decl.value()) {
4476 // We assume here that the initial-value expression will not emit any helper statements.
4477 // Initial-value expressions are required to pass IsConstantExpression, which limits the
4478 // blast radius to constructors, literals, and other constant values/variables.
4479 initializer += " = ";
4480 initializer += this->assembleExpression(*decl.value(), Precedence::kAssignment);
4481 }
4482
4483 if (var.modifierFlags().isConst()) {
4484 this->write("const ");
4485 } else if (var.modifierFlags().isWorkgroup()) {
4486 this->write("var<workgroup> ");
4487 } else if (var.modifierFlags().isPixelLocal()) {
4488 this->write("var<pixel_local> ");
4489 } else {
4490 this->write("var<private> ");
4491 }
4492 this->write(this->assembleName(var.mangledName()));
4493 this->write(": " + to_wgsl_type(fContext, var.type(), &var.layout()));
4494 this->write(initializer);
4495 this->writeLine(";");
4496 }
4497
4498 void WGSLCodeGenerator::writeStructDefinition(const StructDefinition& s) {
4499 const Type& type = s.type();
4500 this->writeLine("struct " + type.displayName() + " {");
4501 this->writeFields(type.fields(), /*memoryLayout=*/nullptr);
4502 this->writeLine("};");
4503 }
4504
4505 void WGSLCodeGenerator::writeModifiersDeclaration(const ModifiersDeclaration& modifiers) {
4506 LayoutFlags flags = modifiers.layout().fFlags;
4507 flags &= ~(LayoutFlag::kLocalSizeX | LayoutFlag::kLocalSizeY | LayoutFlag::kLocalSizeZ);
4508 if (flags != LayoutFlag::kNone) {
4509 fContext.fErrors->error(modifiers.position(), "unsupported declaration");
4510 return;
4511 }
4512
4513 if (modifiers.layout().fLocalSizeX >= 0) {
4514 fLocalSizeX = modifiers.layout().fLocalSizeX;
4515 }
4516 if (modifiers.layout().fLocalSizeY >= 0) {
4517 fLocalSizeY = modifiers.layout().fLocalSizeY;
4518 }
4519 if (modifiers.layout().fLocalSizeZ >= 0) {
4520 fLocalSizeZ = modifiers.layout().fLocalSizeZ;
4521 }
4522 }
4523
4524 void WGSLCodeGenerator::writeFields(SkSpan<const Field> fields, const MemoryLayout* memoryLayout) {
4525 fIndentation++;
4526
4527 for (size_t index = 0; index < fields.size(); ++index) {
4528 const Field& field = fields[index];
4529 if (memoryLayout && !memoryLayout->isSupported(*field.fType)) {
4530 // Reject types that aren't supported by the memory layout.
4531 fContext.fErrors->error(field.fPosition, "type '" + std::string(field.fType->name()) +
4532 "' is not permitted here");
4533 return;
4534 }
4535
4536 // Prepend @size(n) to enforce the offsets from the SkSL layout. (This is effectively
4537 // a gadget that we can use to insert padding between elements.)
4538 if (index < fields.size() - 1) {
4539 int thisFieldOffset = field.fLayout.fOffset;
4540 int nextFieldOffset = fields[index + 1].fLayout.fOffset;
4541 if (index == 0 && thisFieldOffset > 0) {
4542 fContext.fErrors->error(field.fPosition, "field must have an offset of zero");
4543 return;
4544 }
4545 if (thisFieldOffset >= 0 && nextFieldOffset > thisFieldOffset) {
4546 this->write("@size(");
4547 this->write(std::to_string(nextFieldOffset - thisFieldOffset));
4548 this->write(") ");
4549 }
4550 }
4551
4552 this->write(this->assembleName(field.fName));
4553 this->write(": ");
4554 if (const FieldPolyfillInfo* info = fFieldPolyfillMap.find(&field)) {
4555 if (info->fIsArray) {
4556 // This properly handles arrays of matrices, as well as arrays of other primitives.
4557 SkASSERT(field.fType->isArray());
4558 this->write("array<_skArrayElement_");
4559 this->write(field.fType->abbreviatedName());
4560 this->write(", ");
4561 this->write(std::to_string(field.fType->columns()));
4562 this->write(">");
4563 } else if (info->fIsMatrix) {
4564 this->write("_skMatrix");
4565 this->write(std::to_string(field.fType->columns()));
4566 this->write(std::to_string(field.fType->rows()));
4567 this->write(type_is_low_precision(*field.fType, fContext) ? "h" : "f");
4568 } else {
4569 SkDEBUGFAILF("need polyfill for %s", info->fReplacementName.c_str());
4570 }
4571 } else {
4572 this->write(to_wgsl_type(fContext, *field.fType, &field.fLayout));
4573 }
4574 this->writeLine(",");
4575 }
4576
4577 fIndentation--;
4578 }
4579
4580 void WGSLCodeGenerator::writeEnables() {
4581 this->writeLine("diagnostic(off, derivative_uniformity);");
4582 this->writeLine("diagnostic(off, chromium.unreachable_code);");
4583
4584 if (!fContext.fConfig->fSettings.fForceHighPrecision) {
4585 // Always turn on f16, even if technically a given program might not use half values.
4586 this->writeLine("enable f16;");
4587 }
4588 if (fRequirements.fPixelLocalExtension) {
4589 this->writeLine("enable chromium_experimental_pixel_local;");
4590 }
4591 if (fProgram.fInterface.fUseLastFragColor) {
4592 this->writeLine("enable chromium_experimental_framebuffer_fetch;");
4593 }
4594 if (fProgram.fInterface.fOutputSecondaryColor) {
4595 this->writeLine("enable dual_source_blending;");
4596 }
4597 }
4598
4599 bool WGSLCodeGenerator::needsStageInputStruct() const {
4600 // It is illegal to declare a struct with no members; we can't emit a placeholder empty stage
4601 // input struct.
4602 return !fPipelineInputs.empty();
4603 }
4604
4605 void WGSLCodeGenerator::writeStageInputStruct() {
4606 if (!this->needsStageInputStruct()) {
4607 return;
4608 }
4609
4610 std::string_view structNamePrefix = pipeline_struct_prefix(fProgram.fConfig->fKind);
4611 SkASSERT(!structNamePrefix.empty());
4612
4613 this->write("struct ");
4614 this->write(structNamePrefix);
4615 this->writeLine("In {");
4616 fIndentation++;
4617
4618 for (const Variable* v : fPipelineInputs) {
4619 if (v->type().isInterfaceBlock()) {
4620 for (const Field& f : v->type().fields()) {
4621 this->writePipelineIODeclaration(f.fLayout, *f.fType, f.fModifierFlags, f.fName,
4622 Delimiter::kComma);
4623 }
4624 } else {
4625 this->writePipelineIODeclaration(v->layout(), v->type(), v->modifierFlags(),
4626 v->mangledName(), Delimiter::kComma);
4627 }
4628 }
4629
4630 fIndentation--;
4631 this->writeLine("};");
4632 }
4633
4634 bool WGSLCodeGenerator::needsStageOutputStruct() const {
4635 // It is illegal to declare a struct with no members. However, vertex programs will _always_
4636 // have an output stage in WGSL, because the spec requires them to emit `@builtin(position)`.
4637 // So we always synthesize a reference to `sk_Position` even if the program doesn't need it.
4638 return !fPipelineOutputs.empty() || ProgramConfig::IsVertex(fProgram.fConfig->fKind);
4639 }
4640
4641 void WGSLCodeGenerator::writeStageOutputStruct() {
4642 if (!this->needsStageOutputStruct()) {
4643 return;
4644 }
4645
4646 std::string_view structNamePrefix = pipeline_struct_prefix(fProgram.fConfig->fKind);
4647 SkASSERT(!structNamePrefix.empty());
4648
4649 this->write("struct ");
4650 this->write(structNamePrefix);
4651 this->writeLine("Out {");
4652 fIndentation++;
4653
4654 bool declaredPositionBuiltin = false;
4655 bool requiresPointSizeBuiltin = false;
4656 for (const Variable* v : fPipelineOutputs) {
4657 if (v->type().isInterfaceBlock()) {
4658 for (const auto& f : v->type().fields()) {
4659 this->writePipelineIODeclaration(f.fLayout, *f.fType, f.fModifierFlags, f.fName,
4660 Delimiter::kComma);
4661 if (f.fLayout.fBuiltin == SK_POSITION_BUILTIN) {
4662 declaredPositionBuiltin = true;
4663 } else if (f.fLayout.fBuiltin == SK_POINTSIZE_BUILTIN) {
4664 // sk_PointSize is explicitly not supported by `builtin_from_sksl_name` so
4665 // writePipelineIODeclaration will never write it. We mark it here if the
4666 // declaration is needed so we can synthesize it below.
4667 requiresPointSizeBuiltin = true;
4668 }
4669 }
4670 } else {
4671 this->writePipelineIODeclaration(v->layout(), v->type(), v->modifierFlags(),
4672 v->mangledName(), Delimiter::kComma);
4673 }
4674 }
4675
4676 // A vertex program must include the `position` builtin in its entrypoint's return type.
4677 const bool positionBuiltinRequired = ProgramConfig::IsVertex(fProgram.fConfig->fKind);
4678 if (positionBuiltinRequired && !declaredPositionBuiltin) {
4679 this->writeLine("@builtin(position) sk_Position: vec4<f32>,");
4680 }
4681
4682 fIndentation--;
4683 this->writeLine("};");
4684
4685 // In WebGPU/WGSL, the vertex stage does not support a point-size output and the size
4686 // of a point primitive is always 1 pixel (see https://github.com/gpuweb/gpuweb/issues/332).
4687 //
4688 // There isn't anything we can do to emulate this correctly at this stage so we synthesize a
4689 // placeholder global variable that has no effect. Programs should not rely on sk_PointSize when
4690 // using the Dawn backend.
4691 if (ProgramConfig::IsVertex(fProgram.fConfig->fKind) && requiresPointSizeBuiltin) {
4692 this->writeLine("/* unsupported */ var<private> sk_PointSize: f32;");
4693 }
4694 }
4695
4696 void WGSLCodeGenerator::prepareUniformPolyfillsForInterfaceBlock(
4697 const InterfaceBlock* interfaceBlock,
4698 std::string_view instanceName,
4699 MemoryLayout::Standard nativeLayout) {
4700 SkSL::MemoryLayout std140(MemoryLayout::Standard::k140);
4701 SkSL::MemoryLayout native(nativeLayout);
4702
4703 const Type& structType = interfaceBlock->var()->type().componentType();
4704 for (const Field& field : structType.fields()) {
4705 const Type* type = field.fType;
4706 bool needsArrayPolyfill = false;
4707 bool needsMatrixPolyfill = false;
4708
4709 auto isPolyfillableMatrixType = [&](const Type* type) {
4710 return type->isMatrix() && std140.stride(*type) != native.stride(*type);
4711 };
4712
4713 if (isPolyfillableMatrixType(type)) {
4714 // Matrices will be represented as 16-byte aligned arrays in std140, and reconstituted
4715 // into proper matrices as they are later accessed. We need to synthesize polyfill.
4716 needsMatrixPolyfill = true;
4717 } else if (type->isArray() && !type->isUnsizedArray() &&
4718 !type->componentType().isOpaque()) {
4719 const Type* innerType = &type->componentType();
4720 if (isPolyfillableMatrixType(innerType)) {
4721 // Use a polyfill when the array contains a matrix that requires polyfill.
4722 needsArrayPolyfill = true;
4723 needsMatrixPolyfill = true;
4724 } else if (native.size(*innerType) < 16) {
4725 // Use a polyfill when the array elements are smaller than 16 bytes, since std140
4726 // will pad elements to a 16-byte stride.
4727 needsArrayPolyfill = true;
4728 }
4729 }
4730
4731 if (needsArrayPolyfill || needsMatrixPolyfill) {
4732 // Add a polyfill for this matrix type.
4733 FieldPolyfillInfo info;
4734 info.fInterfaceBlock = interfaceBlock;
4735 info.fReplacementName = "_skUnpacked_" + std::string(instanceName) + '_' +
4736 this->assembleName(field.fName);
4737 info.fIsArray = needsArrayPolyfill;
4738 info.fIsMatrix = needsMatrixPolyfill;
4739 fFieldPolyfillMap.set(&field, info);
4740 }
4741 }
4742 }
4743
4744 void WGSLCodeGenerator::writeUniformsAndBuffers() {
4745 for (const ProgramElement* e : fProgram.elements()) {
4746 // Iterate through the interface blocks.
4747 if (!e->is<InterfaceBlock>()) {
4748 continue;
4749 }
4750 this->writeInterfaceBlock(e->as<InterfaceBlock>());
4751 }
4752 }
4753
4754 void WGSLCodeGenerator::writeInterfaceBlock(const InterfaceBlock& ib) {
4755 // Determine if this interface block holds uniforms, buffers, or something else (skip it).
4756 std::string_view addressSpace;
4757 std::string_view accessMode;
4758 MemoryLayout::Standard nativeLayout;
4759 const bool isPushConstant =
4760 static_cast<bool>(ib.var()->layout().fFlags & LayoutFlag::kPushConstant);
4761 if (ib.var()->modifierFlags().isUniform()) {
4762 if (isPushConstant) {
4763 addressSpace = "immediate";
4764 } else {
4765 addressSpace = "uniform";
4766 }
4767 nativeLayout = fContext.fConfig->fSettings.fForceHighPrecision
4768 ? MemoryLayout::Standard::kWGSLUniform_Base
4769 : MemoryLayout::Standard::kWGSLUniform_EnableF16;
4770 } else if (ib.var()->modifierFlags().isBuffer()) {
4771 addressSpace = "storage";
4772 nativeLayout = fContext.fConfig->fSettings.fForceHighPrecision
4773 ? MemoryLayout::Standard::kWGSLStorage_Base
4774 : MemoryLayout::Standard::kWGSLStorage_EnableF16;
4775 accessMode = ib.var()->modifierFlags().isReadOnly() ? ", read" : ", read_write";
4776 } else {
4777 return;
4778 }
4779
4780 // If we have an anonymous interface block, assign a name like `_uniform0` or `_storage1`.
4781 std::string instanceName;
4782 if (ib.instanceName().empty()) {
4783 instanceName = "_" + std::string(addressSpace) + std::to_string(fScratchCount++);
4784 fInterfaceBlockNameMap[&ib.var()->type().componentType()] = instanceName;
4785 } else {
4786 instanceName = std::string(ib.instanceName());
4787 }
4788
4789 this->prepareUniformPolyfillsForInterfaceBlock(&ib, instanceName, nativeLayout);
4790
4791 // Create a struct to hold all of the fields from this InterfaceBlock.
4792 SkASSERT(!ib.typeName().empty());
4793 this->write("struct ");
4794 this->write(ib.typeName());
4795 this->writeLine(" {");
4796
4797 // Find the struct type and fields used by this interface block.
4798 const Type& ibType = ib.var()->type().componentType();
4799 SkASSERT(ibType.isStruct());
4800
4801 SkSpan<const Field> ibFields = ibType.fields();
4802 SkASSERT(!ibFields.empty());
4803
4804 MemoryLayout layout(MemoryLayout::Standard::k140);
4805 this->writeFields(ibFields, &layout);
4806 this->writeLine("};");
4807 if (!isPushConstant) {
4808 this->write("@group(");
4809 this->write(std::to_string(std::max(0, ib.var()->layout().fSet)));
4810 this->write(") @binding(");
4811 this->write(std::to_string(std::max(0, ib.var()->layout().fBinding)));
4812 this->write(") ");
4813 }
4814 this->write("var<");
4815 this->write(addressSpace);
4816 this->write(accessMode);
4817 this->write("> ");
4818 this->write(instanceName);
4819 this->write(" : ");
4820 this->write(to_wgsl_type(fContext, ib.var()->type(), &ib.var()->layout()));
4821 this->writeLine(";");
4822 }
4823
4824 void WGSLCodeGenerator::writeNonBlockUniformsForTests() {
4825 TArray<Field> globalVarFields;
4826 Position globalVarPos;
4827 for (const ProgramElement* e : fProgram.elements()) {
4828 if (e->is<GlobalVarDeclaration>()) {
4829 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
4830 const Variable& var = *decls.varDeclaration().var();
4831
4832 if (is_in_global_uniforms(var)) {
4833 if (globalVarFields.empty()) {
4834 globalVarPos = var.position();
4835 }
4836 globalVarFields.push_back(Field(var.position(), var.layout(), ModifierFlag::kNone,
4837 var.name(), &var.type()));
4838 }
4839 }
4840 }
4841
4842 if (!globalVarFields.empty()) {
4843 Layout layout{LayoutFlag::kNone, 0, 0, fProgram.fConfig->fSettings.fDefaultUniformBinding, 0,
4844 fProgram.fConfig->fSettings.fDefaultUniformSet, 0, 0};
4845 Modifiers modifiers{globalVarPos, layout, ModifierFlag::kUniform};
4846
4847 // Interface blocks (for SkSL) are normally only allowed in fragment, vertex, or compute
4848 // programs and not the synthetic SkSL files that are allowed to declare non-block uniforms
4849 // Arbitrarily pick kFragment to temporarily override the config kind to pass validations.
4850 ProgramKind orig = fContext.fConfig->fKind;
4851 fContext.fConfig->fKind = ProgramKind::kFragment;
4852 fSyntheticGlobalUniformsBlock = InterfaceBlock::Convert(fContext,
4853 globalVarPos,
4854 modifiers,
4855 "_GlobalUniforms",
4856 std::move(globalVarFields),
4857 "_globalUniforms",
4858 /*arraySize=*/0);
4859 this->writeInterfaceBlock(*fSyntheticGlobalUniformsBlock);
4860 fContext.fConfig->fKind = orig;
4861 }
4862 }
4863
4864 std::string WGSLCodeGenerator::functionDependencyArgs(const FunctionDeclaration& f) {
4865 WGSLFunctionDependencies* deps = fRequirements.fDependencies.find(&f);
4866 std::string args;
4867 if (deps && *deps) {
4868 const char* separator = "";
4869 if (*deps & WGSLFunctionDependency::kPipelineInputs) {
4870 args += "_stageIn";
4871 separator = ", ";
4872 }
4873 if (*deps & WGSLFunctionDependency::kPipelineOutputs) {
4874 args += separator;
4875 args += "_stageOut";
4876 }
4877 }
4878 return args;
4879 }
4880
4881 bool WGSLCodeGenerator::writeFunctionDependencyParams(const FunctionDeclaration& f) {
4882 WGSLFunctionDependencies* deps = fRequirements.fDependencies.find(&f);
4883 if (!deps || !*deps) {
4884 return false;
4885 }
4886
4887 std::string_view structNamePrefix = pipeline_struct_prefix(fProgram.fConfig->fKind);
4888 if (structNamePrefix.empty()) {
4889 return false;
4890 }
4891 const char* separator = "";
4892 if (*deps & WGSLFunctionDependency::kPipelineInputs) {
4893 this->write("_stageIn: ");
4894 separator = ", ";
4895 this->write(structNamePrefix);
4896 this->write("In");
4897 }
4898 if (*deps & WGSLFunctionDependency::kPipelineOutputs) {
4899 this->write(separator);
4900 this->write("_stageOut: ptr<function, ");
4901 this->write(structNamePrefix);
4902 this->write("Out>");
4903 }
4904 return true;
4905 }
4906
4907 bool ToWGSL(Program& program,
4908 const ShaderCaps* caps,
4909 OutputStream& out,
4910 PrettyPrint pp,
4911 IncludeSyntheticCode isc,
4912 ValidateWGSLProc validateWGSL) {
4913 TRACE_EVENT0("skia.shaders", "SkSL::ToWGSL");
4914 SkASSERT(caps != nullptr);
4915
4916 program.fContext->fErrors->setSource(*program.fSource);
4917 bool result;
4918 if (validateWGSL) {
4919 StringStream wgsl;
4920 WGSLCodeGenerator cg(program.fContext.get(), caps, &program, &wgsl, pp, isc);
4921 result = cg.generateCode();
4922 if (result) {
4923 std::string_view wgslBytes = wgsl.str();
4924 std::string warnings;
4925 result = validateWGSL(*program.fContext->fErrors, wgslBytes, &warnings);
4926 if (!warnings.empty()) {
4927 out.writeText("/* Tint reported warnings. */\n\n");
4928 }
4929 out.write(wgslBytes.data(), wgslBytes.size());
4930 }
4931 } else {
4932 WGSLCodeGenerator cg(program.fContext.get(), caps, &program, &out, pp, isc);
4933 result = cg.generateCode();
4934 }
4935 program.fContext->fErrors->setSource(std::string_view());
4936
4937 return result;
4938 }
4939
4940 bool ToWGSL(Program& program, const ShaderCaps* caps, OutputStream& out) {
4941 #if defined(SK_DEBUG)
4942 constexpr PrettyPrint defaultPrintOpts = PrettyPrint::kYes;
4943 #else
4944 constexpr PrettyPrint defaultPrintOpts = PrettyPrint::kNo;
4945 #endif
4946 return ToWGSL(program, caps, out, defaultPrintOpts, IncludeSyntheticCode::kNo, nullptr);
4947 }
4948
4949 bool ToWGSL(Program& program, const ShaderCaps* caps, NativeShader* out) {
4950 StringStream buffer;
4951 if (!ToWGSL(program, caps, buffer)) {
4952 return false;
4953 }
4954 out->fText = buffer.str();
4955 return true;
4956 }
4957
4958 } // namespace SkSL