Debian Codegraph @

src/sksl/codegen/SkSLRasterPipelineCodeGenerator.cpp

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 * Copyright 2022 Google LLC
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/SkSLRasterPipelineCodeGenerator.h"
9
10 #include "include/core/SkPoint.h"
11 #include "include/core/SkSpan.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/base/SkUtils.h"
17 #include "src/core/SkTHash.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/SkSLIntrinsicList.h"
25 #include "src/sksl/SkSLOperator.h"
26 #include "src/sksl/SkSLPosition.h"
27 #include "src/sksl/analysis/SkSLProgramUsage.h"
28 #include "src/sksl/codegen/SkSLRasterPipelineBuilder.h"
29 #include "src/sksl/ir/SkSLBinaryExpression.h"
30 #include "src/sksl/ir/SkSLBlock.h"
31 #include "src/sksl/ir/SkSLBreakStatement.h"
32 #include "src/sksl/ir/SkSLChildCall.h"
33 #include "src/sksl/ir/SkSLConstructor.h"
34 #include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
35 #include "src/sksl/ir/SkSLConstructorMatrixResize.h"
36 #include "src/sksl/ir/SkSLConstructorSplat.h"
37 #include "src/sksl/ir/SkSLContinueStatement.h"
38 #include "src/sksl/ir/SkSLDoStatement.h"
39 #include "src/sksl/ir/SkSLExpression.h"
40 #include "src/sksl/ir/SkSLExpressionStatement.h"
41 #include "src/sksl/ir/SkSLFieldAccess.h"
42 #include "src/sksl/ir/SkSLForStatement.h"
43 #include "src/sksl/ir/SkSLFunctionCall.h"
44 #include "src/sksl/ir/SkSLFunctionDeclaration.h"
45 #include "src/sksl/ir/SkSLFunctionDefinition.h"
46 #include "src/sksl/ir/SkSLIRNode.h"
47 #include "src/sksl/ir/SkSLIfStatement.h"
48 #include "src/sksl/ir/SkSLIndexExpression.h"
49 #include "src/sksl/ir/SkSLLayout.h"
50 #include "src/sksl/ir/SkSLLiteral.h"
51 #include "src/sksl/ir/SkSLModifierFlags.h"
52 #include "src/sksl/ir/SkSLPostfixExpression.h"
53 #include "src/sksl/ir/SkSLPrefixExpression.h"
54 #include "src/sksl/ir/SkSLProgram.h"
55 #include "src/sksl/ir/SkSLProgramElement.h"
56 #include "src/sksl/ir/SkSLReturnStatement.h"
57 #include "src/sksl/ir/SkSLStatement.h"
58 #include "src/sksl/ir/SkSLSwitchCase.h"
59 #include "src/sksl/ir/SkSLSwitchStatement.h"
60 #include "src/sksl/ir/SkSLSwizzle.h"
61 #include "src/sksl/ir/SkSLTernaryExpression.h"
62 #include "src/sksl/ir/SkSLType.h"
63 #include "src/sksl/ir/SkSLVarDeclarations.h"
64 #include "src/sksl/ir/SkSLVariable.h"
65 #include "src/sksl/ir/SkSLVariableReference.h"
66 #include "src/sksl/tracing/SkSLDebugTracePriv.h"
67 #include "src/sksl/transform/SkSLTransform.h"
68
69 #include <algorithm>
70 #include <climits>
71 #include <cstddef>
72 #include <cstdint>
73 #include <float.h>
74 #include <iterator>
75 #include <optional>
76 #include <string>
77 #include <string_view>
78 #include <utility>
79 #include <vector>
80
81 using namespace skia_private;
82
83 namespace SkSL {
84 namespace RP {
85
86 static bool unsupported() {
87 // If MakeRasterPipelineProgram returns false, set a breakpoint here for more information.
88 return false;
89 }
90
91 class AutoContinueMask;
92 class Generator;
93 class LValue;
94
95 class SlotManager {
96 public:
97 SlotManager(std::vector<SlotDebugInfo>* i) : fSlotDebugInfo(i) {}
98
99 /** Used by `createSlots` to add this variable to SlotDebugInfo inside the DebugTrace. */
100 void addSlotDebugInfoForGroup(const std::string& varName,
101 const Type& type,
102 Position pos,
103 int* groupIndex,
104 bool isFunctionReturnValue);
105 void addSlotDebugInfo(const std::string& varName,
106 const Type& type,
107 Position pos,
108 bool isFunctionReturnValue);
109
110 /** Creates slots associated with an SkSL variable or return value. */
111 SlotRange createSlots(std::string name,
112 const Type& type,
113 Position pos,
114 bool isFunctionReturnValue);
115
116 /**
117 * Associates previously-created slots with an SkSL variable; this can allow multiple variables
118 * to share overlapping ranges. If the variable was already associated with a slot range,
119 * returns the previously associated range.
120 */
121 std::optional<SlotRange> mapVariableToSlots(const Variable& v, SlotRange range);
122
123 /**
124 * Deletes the existing mapping between a variable and its slots; a future call to
125 * `getVariableSlots` will see this as a brand new variable and associate new slots.
126 */
127 void unmapVariableSlots(const Variable& v);
128
129 /** Looks up the slots associated with an SkSL variable; creates the slot if necessary. */
130 SlotRange getVariableSlots(const Variable& v);
131
132 /**
133 * Looks up the slots associated with an SkSL function's return value; creates the range if
134 * necessary. Note that recursion is never supported, so we don't need to maintain return values
135 * in a stack; we can just statically allocate one slot per function call-site.
136 */
137 SlotRange getFunctionSlots(const IRNode& callSite, const FunctionDeclaration& f);
138
139 /** Returns the total number of slots consumed. */
140 int slotCount() const { return fSlotCount; }
141
142 private:
143 THashMap<const IRNode*, SlotRange> fSlotMap;
144 int fSlotCount = 0;
145 std::vector<SlotDebugInfo>* fSlotDebugInfo;
146 };
147
148 class AutoStack {
149 public:
150 /**
151 * Creates a temporary stack. The caller is responsible for discarding every entry on this
152 * stack before ~AutoStack is reached.
153 */
154 explicit AutoStack(Generator* g);
155 ~AutoStack();
156
157 /** Activates the associated stack. */
158 void enter();
159
160 /** Undoes a call to `enter`, returning to the previously-active stack. */
161 void exit();
162
163 /** Returns the stack ID of this AutoStack. */
164 int stackID() { return fStackID; }
165
166 /** Clones values from this stack onto the top of the active stack. */
167 void pushClone(int slots);
168
169 /** Clones values from a fixed range of this stack onto the top of the active stack. */
170 void pushClone(SlotRange range, int offsetFromStackTop);
171
172 /** Clones values from a dynamic range of this stack onto the top of the active stack. */
173 void pushCloneIndirect(SlotRange range, int dynamicStackID, int offsetFromStackTop);
174
175 private:
176 Generator* fGenerator;
177 int fStackID = 0;
178 int fParentStackID = 0;
179 };
180
181 class Generator {
182 public:
183 Generator(const SkSL::Program& program, DebugTracePriv* debugTrace, bool writeTraceOps)
184 : fProgram(program)
185 , fContext(fProgram.fContext->fTypes, *fProgram.fContext->fErrors)
186 , fDebugTrace(debugTrace)
187 , fWriteTraceOps(writeTraceOps)
188 , fProgramSlots(debugTrace ? &debugTrace->fSlotInfo : nullptr)
189 , fUniformSlots(debugTrace ? &debugTrace->fUniformInfo : nullptr)
190 , fImmutableSlots(nullptr) {
191 fContext.fConfig = fProgram.fConfig.get();
192 fContext.fModule = fProgram.fContext->fModule;
193 }
194
195 ~Generator() {
196 // ~AutoStack calls into the Generator, so we need to make sure the trace mask is reset
197 // before the Generator is destroyed.
198 fTraceMask.reset();
199 }
200
201 /** Converts the SkSL main() function into a set of Instructions. */
202 bool writeProgram(const FunctionDefinition& function);
203
204 /** Returns the generated program. */
205 std::unique_ptr<RP::Program> finish();
206
207 /**
208 * Converts an SkSL function into a set of Instructions. Returns nullopt if the function
209 * contained unsupported statements or expressions.
210 */
211 std::optional<SlotRange> writeFunction(const IRNode& callSite,
212 const FunctionDefinition& function,
213 SkSpan<std::unique_ptr<Expression> const> arguments);
214
215 /**
216 * Returns the slot index of this function inside the FunctionDebugInfo array in DebugTracePriv.
217 * The FunctionDebugInfo slot will be created if it doesn't already exist.
218 */
219 int getFunctionDebugInfo(const FunctionDeclaration& decl);
220
221 /** Returns true for variables with slots in fProgramSlots; immutables or uniforms are false. */
222 bool hasVariableSlots(const Variable& v) {
223 return !IsUniform(v) && !fImmutableVariables.contains(&v);
224 }
225
226 /** Looks up the slots associated with an SkSL variable; creates the slots if necessary. */
227 SlotRange getVariableSlots(const Variable& v) {
228 SkASSERT(this->hasVariableSlots(v));
229 return fProgramSlots.getVariableSlots(v);
230 }
231
232 /**
233 * Looks up the slots associated with an immutable variable; creates the slots if necessary.
234 */
235 SlotRange getImmutableSlots(const Variable& v) {
236 SkASSERT(!IsUniform(v));
237 SkASSERT(fImmutableVariables.contains(&v));
238 return fImmutableSlots.getVariableSlots(v);
239 }
240
241 /** Looks up the slots associated with an SkSL uniform; creates the slots if necessary. */
242 SlotRange getUniformSlots(const Variable& v) {
243 SkASSERT(IsUniform(v));
244 SkASSERT(!fImmutableVariables.contains(&v));
245 return fUniformSlots.getVariableSlots(v);
246 }
247
248 /**
249 * Looks up the slots associated with an SkSL function's return value; creates the range if
250 * necessary. Note that recursion is never supported, so we don't need to maintain return values
251 * in a stack; we can just statically allocate one slot per function call-site.
252 */
253 SlotRange getFunctionSlots(const IRNode& callSite, const FunctionDeclaration& f) {
254 return fProgramSlots.getFunctionSlots(callSite, f);
255 }
256
257 /**
258 * Creates an additional stack for the program to push values onto. The stack will not become
259 * actively in-use until `setCurrentStack` is called.
260 */
261 int createStack();
262
263 /** Frees a stack generated by `createStack`. The freed stack must be completely empty. */
264 void recycleStack(int stackID);
265
266 /** Redirects builder ops to point to a different stack (created by `createStack`). */
267 void setCurrentStack(int stackID);
268
269 /** Reports the currently active stack. */
270 int currentStack() {
271 return fCurrentStack;
272 }
273
274 /**
275 * Returns an LValue for the passed-in expression; if the expression isn't supported as an
276 * LValue, returns nullptr.
277 */
278 std::unique_ptr<LValue> makeLValue(const Expression& e, bool allowScratch = false);
279
280 /** Copies the top-of-stack value into this lvalue, without discarding it from the stack. */
281 [[nodiscard]] bool store(LValue& lvalue);
282
283 /** Pushes the lvalue onto the top-of-stack. */
284 [[nodiscard]] bool push(LValue& lvalue);
285
286 /** The Builder stitches our instructions together into Raster Pipeline code. */
287 Builder* builder() { return &fBuilder; }
288
289 /** Appends a statement to the program. */
290 [[nodiscard]] bool writeStatement(const Statement& s);
291 [[nodiscard]] bool writeBlock(const Block& b);
292 [[nodiscard]] bool writeBreakStatement(const BreakStatement& b);
293 [[nodiscard]] bool writeContinueStatement(const ContinueStatement& b);
294 [[nodiscard]] bool writeDoStatement(const DoStatement& d);
295 [[nodiscard]] bool writeExpressionStatement(const ExpressionStatement& e);
296 [[nodiscard]] bool writeMasklessForStatement(const ForStatement& f);
297 [[nodiscard]] bool writeForStatement(const ForStatement& f);
298 [[nodiscard]] bool writeGlobals();
299 [[nodiscard]] bool writeIfStatement(const IfStatement& i);
300 [[nodiscard]] bool writeDynamicallyUniformIfStatement(const IfStatement& i);
301 [[nodiscard]] bool writeReturnStatement(const ReturnStatement& r);
302 [[nodiscard]] bool writeSwitchStatement(const SwitchStatement& s);
303 [[nodiscard]] bool writeVarDeclaration(const VarDeclaration& v);
304 [[nodiscard]] bool writeImmutableVarDeclaration(const VarDeclaration& d);
305
306 /** Pushes an expression to the value stack. */
307 [[nodiscard]] bool pushBinaryExpression(const BinaryExpression& e);
308 [[nodiscard]] bool pushBinaryExpression(const Expression& left,
309 Operator op,
310 const Expression& right);
311 [[nodiscard]] bool pushChildCall(const ChildCall& c);
312 [[nodiscard]] bool pushConstructorCast(const AnyConstructor& c);
313 [[nodiscard]] bool pushConstructorCompound(const AnyConstructor& c);
314 [[nodiscard]] bool pushConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c);
315 [[nodiscard]] bool pushConstructorMatrixResize(const ConstructorMatrixResize& c);
316 [[nodiscard]] bool pushConstructorSplat(const ConstructorSplat& c);
317 [[nodiscard]] bool pushExpression(const Expression& e, bool usesResult = true);
318 [[nodiscard]] bool pushFieldAccess(const FieldAccess& f);
319 [[nodiscard]] bool pushFunctionCall(const FunctionCall& c);
320 [[nodiscard]] bool pushIndexExpression(const IndexExpression& i);
321 [[nodiscard]] bool pushIntrinsic(const FunctionCall& c);
322 [[nodiscard]] bool pushIntrinsic(IntrinsicKind intrinsic, const Expression& arg0);
323 [[nodiscard]] bool pushIntrinsic(IntrinsicKind intrinsic,
324 const Expression& arg0,
325 const Expression& arg1);
326 [[nodiscard]] bool pushIntrinsic(IntrinsicKind intrinsic,
327 const Expression& arg0,
328 const Expression& arg1,
329 const Expression& arg2);
330 [[nodiscard]] bool pushLiteral(const Literal& l);
331 [[nodiscard]] bool pushPostfixExpression(const PostfixExpression& p, bool usesResult);
332 [[nodiscard]] bool pushPrefixExpression(const PrefixExpression& p);
333 [[nodiscard]] bool pushPrefixExpression(Operator op, const Expression& expr);
334 [[nodiscard]] bool pushSwizzle(const Swizzle& s);
335 [[nodiscard]] bool pushTernaryExpression(const TernaryExpression& t);
336 [[nodiscard]] bool pushTernaryExpression(const Expression& test,
337 const Expression& ifTrue,
338 const Expression& ifFalse);
339 [[nodiscard]] bool pushDynamicallyUniformTernaryExpression(const Expression& test,
340 const Expression& ifTrue,
341 const Expression& ifFalse);
342 [[nodiscard]] bool pushVariableReference(const VariableReference& v);
343
344 /** Support methods for immutable data, which trade more slots for smaller code size. */
345 using ImmutableBits = int32_t;
346
347 [[nodiscard]] bool pushImmutableData(const Expression& e);
348 [[nodiscard]] std::optional<SlotRange> findPreexistingImmutableData(
349 const TArray<ImmutableBits>& immutableValues);
350 [[nodiscard]] std::optional<ImmutableBits> getImmutableBitsForSlot(const Expression& expr,
351 size_t slot);
352 [[nodiscard]] bool getImmutableValueForExpression(const Expression& expr,
353 TArray<ImmutableBits>* immutableValues);
354 void storeImmutableValueToSlots(const TArray<ImmutableBits>& immutableValues, SlotRange slots);
355
356 /** Pops an expression from the value stack and copies it into slots. */
357 void popToSlotRange(SlotRange r) {
358 fBuilder.pop_slots(r);
359 if (this->shouldWriteTraceOps()) {
360 fBuilder.trace_var(fTraceMask->stackID(), r);
361 }
362 }
363 void popToSlotRangeUnmasked(SlotRange r) {
364 fBuilder.pop_slots_unmasked(r);
365 if (this->shouldWriteTraceOps()) {
366 fBuilder.trace_var(fTraceMask->stackID(), r);
367 }
368 }
369
370 /** Pops an expression from the value stack and discards it. */
371 void discardExpression(int slots) { fBuilder.discard_stack(slots); }
372
373 /** Zeroes out a range of slots. */
374 void zeroSlotRangeUnmasked(SlotRange r) {
375 fBuilder.zero_slots_unmasked(r);
376 if (this->shouldWriteTraceOps()) {
377 fBuilder.trace_var(fTraceMask->stackID(), r);
378 }
379 }
380
381 /**
382 * Emits a trace_line opcode. writeStatement does this, and statements that alter control flow
383 * may need to explicitly add additional traces.
384 */
385 void emitTraceLine(Position pos);
386
387 /**
388 * Emits a trace_scope opcode, which alters the SkSL variable-scope depth.
389 * Unlike the other trace ops, trace_scope takes a dedicated mask instead of the trace-scope
390 * mask. Call `pushTraceScopeMask` to synthesize this mask; discard it when you're done.
391 */
392 void pushTraceScopeMask();
393 void discardTraceScopeMask();
394 void emitTraceScope(int delta);
395
396 /** Prepares our position-to-line-offset conversion table (stored in `fLineOffsets`). */
397 void calculateLineOffsets();
398
399 bool shouldWriteTraceOps() { return fDebugTrace && fWriteTraceOps; }
400 int traceMaskStackID() { return fTraceMask->stackID(); }
401
402 /** Expression utilities. */
403 struct TypedOps {
404 BuilderOp fFloatOp;
405 BuilderOp fSignedOp;
406 BuilderOp fUnsignedOp;
407 BuilderOp fBooleanOp;
408 };
409
410 static BuilderOp GetTypedOp(const SkSL::Type& type, const TypedOps& ops);
411
412 [[nodiscard]] bool unaryOp(const SkSL::Type& type, const TypedOps& ops);
413 [[nodiscard]] bool binaryOp(const SkSL::Type& type, const TypedOps& ops);
414 [[nodiscard]] bool ternaryOp(const SkSL::Type& type, const TypedOps& ops);
415 [[nodiscard]] bool pushIntrinsic(const TypedOps& ops, const Expression& arg0);
416 [[nodiscard]] bool pushIntrinsic(const TypedOps& ops,
417 const Expression& arg0,
418 const Expression& arg1);
419 [[nodiscard]] bool pushIntrinsic(BuilderOp builderOp, const Expression& arg0);
420 [[nodiscard]] bool pushIntrinsic(BuilderOp builderOp,
421 const Expression& arg0,
422 const Expression& arg1);
423 [[nodiscard]] bool pushAbsFloatIntrinsic(int slots);
424 [[nodiscard]] bool pushLengthIntrinsic(int slotCount);
425 [[nodiscard]] bool pushVectorizedExpression(const Expression& expr, const Type& vectorType);
426 [[nodiscard]] bool pushVariableReferencePartial(const VariableReference& v, SlotRange subset);
427 [[nodiscard]] bool pushLValueOrExpression(LValue* lvalue, const Expression& expr);
428 [[nodiscard]] bool pushMatrixMultiply(LValue* lvalue,
429 const Expression& left,
430 const Expression& right,
431 int leftColumns, int leftRows,
432 int rightColumns, int rightRows);
433 [[nodiscard]] bool pushStructuredComparison(LValue* left,
434 Operator op,
435 LValue* right,
436 const Type& type);
437
438 void foldWithMultiOp(BuilderOp op, int elements);
439 void foldComparisonOp(Operator op, int elements);
440
441 BuilderOp getTypedOp(const SkSL::Type& type, const TypedOps& ops) const;
442
443 Analysis::ReturnComplexity returnComplexity(const FunctionDefinition* func) {
444 Analysis::ReturnComplexity* complexity = fReturnComplexityMap.find(func);
445 if (!complexity) {
446 complexity = fReturnComplexityMap.set(fCurrentFunction,
447 Analysis::GetReturnComplexity(*func));
448 }
449 return *complexity;
450 }
451
452 bool needsReturnMask(const FunctionDefinition* func) {
453 return this->returnComplexity(func) >= Analysis::ReturnComplexity::kEarlyReturns;
454 }
455
456 bool needsFunctionResultSlots(const FunctionDefinition* func) {
457 return this->shouldWriteTraceOps() || (this->returnComplexity(func) >
458 Analysis::ReturnComplexity::kSingleSafeReturn);
459 }
460
461 static bool IsUniform(const Variable& var) {
462 return var.modifierFlags().isUniform();
463 }
464
465 static bool IsOutParameter(const Variable& var) {
466 return (var.modifierFlags() & (ModifierFlag::kIn | ModifierFlag::kOut)) ==
467 ModifierFlag::kOut;
468 }
469
470 static bool IsInoutParameter(const Variable& var) {
471 return (var.modifierFlags() & (ModifierFlag::kIn | ModifierFlag::kOut)) ==
472 (ModifierFlag::kIn | ModifierFlag::kOut);
473 }
474
475 private:
476 const SkSL::Program& fProgram;
477 SkSL::Context fContext;
478 Builder fBuilder;
479 DebugTracePriv* fDebugTrace = nullptr;
480 bool fWriteTraceOps = false;
481 THashMap<const Variable*, int> fChildEffectMap;
482
483 SlotManager fProgramSlots;
484 SlotManager fUniformSlots;
485 SlotManager fImmutableSlots;
486
487 std::optional<AutoStack> fTraceMask;
488 const FunctionDefinition* fCurrentFunction = nullptr;
489 SlotRange fCurrentFunctionResult;
490 AutoContinueMask* fCurrentContinueMask = nullptr;
491 int fCurrentBreakTarget = -1;
492 int fCurrentStack = 0;
493 int fNextStackID = 0;
494 TArray<int> fRecycledStacks;
495
496 THashMap<const FunctionDefinition*, Analysis::ReturnComplexity> fReturnComplexityMap;
497
498 THashMap<ImmutableBits, THashSet<Slot>> fImmutableSlotMap;
499 THashSet<const Variable*> fImmutableVariables;
500
501 // `fInsideCompoundStatement` will be nonzero if we are currently writing statements inside of a
502 // compound-statement Block. (Conceptually those statements should all count as one.)
503 int fInsideCompoundStatement = 0;
504
505 // `fLineOffsets` contains the position of each newline in the source, plus a zero at the
506 // beginning, and the total source length at the end, as sentinels.
507 TArray<int> fLineOffsets;
508
509 static constexpr auto kAddOps = TypedOps{BuilderOp::add_n_floats,
510 BuilderOp::add_n_ints,
511 BuilderOp::add_n_ints,
512 BuilderOp::unsupported};
513 static constexpr auto kSubtractOps = TypedOps{BuilderOp::sub_n_floats,
514 BuilderOp::sub_n_ints,
515 BuilderOp::sub_n_ints,
516 BuilderOp::unsupported};
517 static constexpr auto kMultiplyOps = TypedOps{BuilderOp::mul_n_floats,
518 BuilderOp::mul_n_ints,
519 BuilderOp::mul_n_ints,
520 BuilderOp::unsupported};
521 static constexpr auto kDivideOps = TypedOps{BuilderOp::div_n_floats,
522 BuilderOp::div_n_ints,
523 BuilderOp::div_n_uints,
524 BuilderOp::unsupported};
525 static constexpr auto kLessThanOps = TypedOps{BuilderOp::cmplt_n_floats,
526 BuilderOp::cmplt_n_ints,
527 BuilderOp::cmplt_n_uints,
528 BuilderOp::unsupported};
529 static constexpr auto kLessThanEqualOps = TypedOps{BuilderOp::cmple_n_floats,
530 BuilderOp::cmple_n_ints,
531 BuilderOp::cmple_n_uints,
532 BuilderOp::unsupported};
533 static constexpr auto kEqualOps = TypedOps{BuilderOp::cmpeq_n_floats,
534 BuilderOp::cmpeq_n_ints,
535 BuilderOp::cmpeq_n_ints,
536 BuilderOp::cmpeq_n_ints};
537 static constexpr auto kNotEqualOps = TypedOps{BuilderOp::cmpne_n_floats,
538 BuilderOp::cmpne_n_ints,
539 BuilderOp::cmpne_n_ints,
540 BuilderOp::cmpne_n_ints};
541 static constexpr auto kModOps = TypedOps{BuilderOp::mod_n_floats,
542 BuilderOp::unsupported,
543 BuilderOp::unsupported,
544 BuilderOp::unsupported};
545 static constexpr auto kMinOps = TypedOps{BuilderOp::min_n_floats,
546 BuilderOp::min_n_ints,
547 BuilderOp::min_n_uints,
548 BuilderOp::min_n_uints};
549 static constexpr auto kMaxOps = TypedOps{BuilderOp::max_n_floats,
550 BuilderOp::max_n_ints,
551 BuilderOp::max_n_uints,
552 BuilderOp::max_n_uints};
553 static constexpr auto kMixOps = TypedOps{BuilderOp::mix_n_floats,
554 BuilderOp::unsupported,
555 BuilderOp::unsupported,
556 BuilderOp::unsupported};
557 static constexpr auto kInverseSqrtOps = TypedOps{BuilderOp::invsqrt_float,
558 BuilderOp::unsupported,
559 BuilderOp::unsupported,
560 BuilderOp::unsupported};
561 friend class AutoContinueMask;
562 };
563
564 AutoStack::AutoStack(Generator* g)
565 : fGenerator(g)
566 , fStackID(g->createStack()) {}
567
568 AutoStack::~AutoStack() {
569 fGenerator->recycleStack(fStackID);
570 }
571
572 void AutoStack::enter() {
573 fParentStackID = fGenerator->currentStack();
574 fGenerator->setCurrentStack(fStackID);
575 }
576
577 void AutoStack::exit() {
578 SkASSERT(fGenerator->currentStack() == fStackID);
579 fGenerator->setCurrentStack(fParentStackID);
580 }
581
582 void AutoStack::pushClone(int slots) {
583 this->pushClone(SlotRange{0, slots}, /*offsetFromStackTop=*/slots);
584 }
585
586 void AutoStack::pushClone(SlotRange range, int offsetFromStackTop) {
587 fGenerator->builder()->push_clone_from_stack(range, fStackID, offsetFromStackTop);
588 }
589
590 void AutoStack::pushCloneIndirect(SlotRange range, int dynamicStackID, int offsetFromStackTop) {
591 fGenerator->builder()->push_clone_indirect_from_stack(
592 range, dynamicStackID, /*otherStackID=*/fStackID, offsetFromStackTop);
593 }
594
595 class AutoContinueMask {
596 public:
597 AutoContinueMask(Generator* gen) : fGenerator(gen) {}
598
599 ~AutoContinueMask() {
600 if (fPreviousContinueMask) {
601 fGenerator->fCurrentContinueMask = fPreviousContinueMask;
602 }
603 }
604
605 void enable() {
606 SkASSERT(!fContinueMaskStack.has_value());
607
608 fContinueMaskStack.emplace(fGenerator);
609 fPreviousContinueMask = fGenerator->fCurrentContinueMask;
610 fGenerator->fCurrentContinueMask = this;
611 }
612
613 void enter() {
614 SkASSERT(fContinueMaskStack.has_value());
615 fContinueMaskStack->enter();
616 }
617
618 void exit() {
619 SkASSERT(fContinueMaskStack.has_value());
620 fContinueMaskStack->exit();
621 }
622
623 void enterLoopBody() {
624 if (fContinueMaskStack.has_value()) {
625 fContinueMaskStack->enter();
626 fGenerator->builder()->push_constant_i(0);
627 fContinueMaskStack->exit();
628 }
629 }
630
631 void exitLoopBody() {
632 if (fContinueMaskStack.has_value()) {
633 fContinueMaskStack->enter();
634 fGenerator->builder()->pop_and_reenable_loop_mask();
635 fContinueMaskStack->exit();
636 }
637 }
638
639 int stackID() {
640 SkASSERT(fContinueMaskStack.has_value());
641 return fContinueMaskStack->stackID();
642 }
643
644 private:
645 std::optional<AutoStack> fContinueMaskStack;
646 Generator* fGenerator = nullptr;
647 AutoContinueMask* fPreviousContinueMask = nullptr;
648 };
649
650 class AutoLoopTarget {
651 public:
652 AutoLoopTarget(Generator* gen, int* targetPtr) : fGenerator(gen), fLoopTargetPtr(targetPtr) {
653 fLabelID = fGenerator->builder()->nextLabelID();
654 fPreviousLoopTarget = *fLoopTargetPtr;
655 *fLoopTargetPtr = fLabelID;
656 }
657
658 ~AutoLoopTarget() {
659 *fLoopTargetPtr = fPreviousLoopTarget;
660 }
661
662 int labelID() {
663 return fLabelID;
664 }
665
666 private:
667 Generator* fGenerator = nullptr;
668 int* fLoopTargetPtr = nullptr;
669 int fPreviousLoopTarget;
670 int fLabelID;
671 };
672
673 class LValue {
674 public:
675 virtual ~LValue() = default;
676
677 /** Returns true if this lvalue is actually writable--temporaries and uniforms are not. */
678 virtual bool isWritable() const = 0;
679
680 /**
681 * Returns the fixed slot range of the lvalue, after it is winnowed down to the selected
682 * field/index. The range is calculated assuming every dynamic index will evaluate to zero.
683 */
684 virtual SlotRange fixedSlotRange(Generator* gen) = 0;
685
686 /**
687 * Returns a stack which holds a single integer, representing the dynamic offset of the lvalue.
688 * This value does not incorporate the fixed offset. If null is returned, the lvalue doesn't
689 * have a dynamic offset. `evaluateDynamicIndices` must be called before this is used.
690 */
691 virtual AutoStack* dynamicSlotRange() = 0;
692
693 /** Returns the swizzle components of the lvalue, or an empty span for non-swizzle LValues. */
694 virtual SkSpan<const int8_t> swizzle() { return {}; }
695
696 /** Pushes values directly onto the stack. */
697 [[nodiscard]] virtual bool push(Generator* gen,
698 SlotRange fixedOffset,
699 AutoStack* dynamicOffset,
700 SkSpan<const int8_t> swizzle) = 0;
701
702 /** Stores topmost values from the stack directly into the lvalue. */
703 [[nodiscard]] virtual bool store(Generator* gen,
704 SlotRange fixedOffset,
705 AutoStack* dynamicOffset,
706 SkSpan<const int8_t> swizzle) = 0;
707 /**
708 * Some lvalues refer to a temporary expression; these temps can be held in the
709 * scratch-expression field to ensure that they exist for the lifetime of the lvalue.
710 */
711 std::unique_ptr<Expression> fScratchExpression;
712 };
713
714 class ScratchLValue final : public LValue {
715 public:
716 explicit ScratchLValue(const Expression& e)
717 : fExpression(&e)
718 , fNumSlots(e.type().slotCount()) {}
719
720 ~ScratchLValue() override {
721 if (fGenerator && fDedicatedStack.has_value()) {
722 // Jettison the scratch expression.
723 fDedicatedStack->enter();
724 fGenerator->discardExpression(fNumSlots);
725 fDedicatedStack->exit();
726 }
727 }
728
729 bool isWritable() const override {
730 return false;
731 }
732
733 SlotRange fixedSlotRange(Generator* gen) override {
734 return SlotRange{0, fNumSlots};
735 }
736
737 AutoStack* dynamicSlotRange() override {
738 return nullptr;
739 }
740
741 [[nodiscard]] bool push(Generator* gen,
742 SlotRange fixedOffset,
743 AutoStack* dynamicOffset,
744 SkSpan<const int8_t> swizzle) override {
745 if (!fDedicatedStack.has_value()) {
746 // Push the scratch expression onto a dedicated stack.
747 fGenerator = gen;
748 fDedicatedStack.emplace(fGenerator);
749 fDedicatedStack->enter();
750 if (!fGenerator->pushExpression(*fExpression)) {
751 return unsupported();
752 }
753 fDedicatedStack->exit();
754 }
755
756 if (dynamicOffset) {
757 fDedicatedStack->pushCloneIndirect(fixedOffset, dynamicOffset->stackID(), fNumSlots);
758 } else {
759 fDedicatedStack->pushClone(fixedOffset, fNumSlots);
760 }
761 if (!swizzle.empty()) {
762 gen->builder()->swizzle(fixedOffset.count, swizzle);
763 }
764 return true;
765 }
766
767 [[nodiscard]] bool store(Generator*, SlotRange, AutoStack*, SkSpan<const int8_t>) override {
768 SkDEBUGFAIL("scratch lvalues cannot be stored into");
769 return unsupported();
770 }
771
772 private:
773 Generator* fGenerator = nullptr;
774 const Expression* fExpression = nullptr;
775 std::optional<AutoStack> fDedicatedStack;
776 int fNumSlots = 0;
777 };
778
779 class VariableLValue final : public LValue {
780 public:
781 explicit VariableLValue(const Variable* v) : fVariable(v) {}
782
783 bool isWritable() const override {
784 return !Generator::IsUniform(*fVariable);
785 }
786
787 SlotRange fixedSlotRange(Generator* gen) override {
788 return Generator::IsUniform(*fVariable) ? gen->getUniformSlots(*fVariable)
789 : gen->getVariableSlots(*fVariable);
790 }
791
792 AutoStack* dynamicSlotRange() override {
793 return nullptr;
794 }
795
796 [[nodiscard]] bool push(Generator* gen,
797 SlotRange fixedOffset,
798 AutoStack* dynamicOffset,
799 SkSpan<const int8_t> swizzle) override {
800 if (Generator::IsUniform(*fVariable)) {
801 if (dynamicOffset) {
802 gen->builder()->push_uniform_indirect(fixedOffset, dynamicOffset->stackID(),
803 this->fixedSlotRange(gen));
804 } else {
805 gen->builder()->push_uniform(fixedOffset);
806 }
807 } else {
808 if (dynamicOffset) {
809 gen->builder()->push_slots_indirect(fixedOffset, dynamicOffset->stackID(),
810 this->fixedSlotRange(gen));
811 } else {
812 gen->builder()->push_slots(fixedOffset);
813 }
814 }
815 if (!swizzle.empty()) {
816 gen->builder()->swizzle(fixedOffset.count, swizzle);
817 }
818 return true;
819 }
820
821 [[nodiscard]] bool store(Generator* gen,
822 SlotRange fixedOffset,
823 AutoStack* dynamicOffset,
824 SkSpan<const int8_t> swizzle) override {
825 SkASSERT(!Generator::IsUniform(*fVariable));
826
827 if (swizzle.empty()) {
828 if (dynamicOffset) {
829 gen->builder()->copy_stack_to_slots_indirect(fixedOffset, dynamicOffset->stackID(),
830 this->fixedSlotRange(gen));
831 } else {
832 gen->builder()->copy_stack_to_slots(fixedOffset);
833 }
834 } else {
835 if (dynamicOffset) {
836 gen->builder()->swizzle_copy_stack_to_slots_indirect(fixedOffset,
837 dynamicOffset->stackID(),
838 this->fixedSlotRange(gen),
839 swizzle,
840 swizzle.size());
841 } else {
842 gen->builder()->swizzle_copy_stack_to_slots(fixedOffset, swizzle, swizzle.size());
843 }
844 }
845 if (gen->shouldWriteTraceOps()) {
846 if (dynamicOffset) {
847 gen->builder()->trace_var_indirect(gen->traceMaskStackID(),
848 fixedOffset,
849 dynamicOffset->stackID(),
850 this->fixedSlotRange(gen));
851 } else {
852 gen->builder()->trace_var(gen->traceMaskStackID(), fixedOffset);
853 }
854 }
855 return true;
856 }
857
858 private:
859 const Variable* fVariable;
860 };
861
862 class ImmutableLValue final : public LValue {
863 public:
864 explicit ImmutableLValue(const Variable* v) : fVariable(v) {}
865
866 bool isWritable() const override {
867 return false;
868 }
869
870 SlotRange fixedSlotRange(Generator* gen) override {
871 return gen->getImmutableSlots(*fVariable);
872 }
873
874 AutoStack* dynamicSlotRange() override {
875 return nullptr;
876 }
877
878 [[nodiscard]] bool push(Generator* gen,
879 SlotRange fixedOffset,
880 AutoStack* dynamicOffset,
881 SkSpan<const int8_t> swizzle) override {
882 if (dynamicOffset) {
883 gen->builder()->push_immutable_indirect(fixedOffset, dynamicOffset->stackID(),
884 this->fixedSlotRange(gen));
885 } else {
886 gen->builder()->push_immutable(fixedOffset);
887 }
888 if (!swizzle.empty()) {
889 gen->builder()->swizzle(fixedOffset.count, swizzle);
890 }
891 return true;
892 }
893
894 [[nodiscard]] bool store(Generator* gen,
895 SlotRange fixedOffset,
896 AutoStack* dynamicOffset,
897 SkSpan<const int8_t> swizzle) override {
898 SkDEBUGFAIL("immutable values cannot be stored into");
899 return unsupported();
900 }
901
902 private:
903 const Variable* fVariable;
904 };
905
906 class SwizzleLValue final : public LValue {
907 public:
908 explicit SwizzleLValue(std::unique_ptr<LValue> p, const ComponentArray& c)
909 : fParent(std::move(p))
910 , fComponents(c) {
911 SkASSERT(!fComponents.empty() && fComponents.size() <= 4);
912 }
913
914 bool isWritable() const override {
915 return fParent->isWritable();
916 }
917
918 SlotRange fixedSlotRange(Generator* gen) override {
919 return fParent->fixedSlotRange(gen);
920 }
921
922 AutoStack* dynamicSlotRange() override {
923 return fParent->dynamicSlotRange();
924 }
925
926 SkSpan<const int8_t> swizzle() override {
927 return fComponents;
928 }
929
930 [[nodiscard]] bool push(Generator* gen,
931 SlotRange fixedOffset,
932 AutoStack* dynamicOffset,
933 SkSpan<const int8_t> swizzle) override {
934 if (!swizzle.empty()) {
935 SkDEBUGFAIL("swizzle-of-a-swizzle should have been folded out in front end");
936 return unsupported();
937 }
938 return fParent->push(gen, fixedOffset, dynamicOffset, fComponents);
939 }
940
941 [[nodiscard]] bool store(Generator* gen,
942 SlotRange fixedOffset,
943 AutoStack* dynamicOffset,
944 SkSpan<const int8_t> swizzle) override {
945 if (!swizzle.empty()) {
946 SkDEBUGFAIL("swizzle-of-a-swizzle should have been folded out in front end");
947 return unsupported();
948 }
949 return fParent->store(gen, fixedOffset, dynamicOffset, fComponents);
950 }
951
952 private:
953 std::unique_ptr<LValue> fParent;
954 const ComponentArray& fComponents;
955 };
956
957 class UnownedLValueSlice : public LValue {
958 public:
959 explicit UnownedLValueSlice(LValue* p, int initialSlot, int numSlots)
960 : fParent(p)
961 , fInitialSlot(initialSlot)
962 , fNumSlots(numSlots) {
963 SkASSERT(fInitialSlot >= 0);
964 SkASSERT(fNumSlots > 0);
965 }
966
967 bool isWritable() const override {
968 return fParent->isWritable();
969 }
970
971 SlotRange fixedSlotRange(Generator* gen) override {
972 SlotRange range = fParent->fixedSlotRange(gen);
973 SlotRange adjusted = range;
974 adjusted.index += fInitialSlot;
975 adjusted.count = fNumSlots;
976 SkASSERT((adjusted.index + adjusted.count) <= (range.index + range.count));
977 return adjusted;
978 }
979
980 AutoStack* dynamicSlotRange() override {
981 return fParent->dynamicSlotRange();
982 }
983
984 [[nodiscard]] bool push(Generator* gen,
985 SlotRange fixedOffset,
986 AutoStack* dynamicOffset,
987 SkSpan<const int8_t> swizzle) override {
988 return fParent->push(gen, fixedOffset, dynamicOffset, swizzle);
989 }
990
991 [[nodiscard]] bool store(Generator* gen,
992 SlotRange fixedOffset,
993 AutoStack* dynamicOffset,
994 SkSpan<const int8_t> swizzle) override {
995 return fParent->store(gen, fixedOffset, dynamicOffset, swizzle);
996 }
997
998 protected:
999 LValue* fParent;
1000
1001 private:
1002 int fInitialSlot = 0;
1003 int fNumSlots = 0;
1004 };
1005
1006 class LValueSlice final : public UnownedLValueSlice {
1007 public:
1008 explicit LValueSlice(std::unique_ptr<LValue> p, int initialSlot, int numSlots)
1009 : UnownedLValueSlice(p.release(), initialSlot, numSlots) {}
1010
1011 ~LValueSlice() override {
1012 delete fParent;
1013 }
1014 };
1015
1016 class DynamicIndexLValue final : public LValue {
1017 public:
1018 explicit DynamicIndexLValue(std::unique_ptr<LValue> p, const IndexExpression& i)
1019 : fParent(std::move(p))
1020 , fIndexExpr(&i) {
1021 SkASSERT(fIndexExpr->index()->type().isInteger());
1022 }
1023
1024 ~DynamicIndexLValue() override {
1025 if (fDedicatedStack.has_value()) {
1026 SkASSERT(fGenerator);
1027
1028 // Jettison the index expression.
1029 fDedicatedStack->enter();
1030 fGenerator->discardExpression(/*slots=*/1);
1031 fDedicatedStack->exit();
1032 }
1033 }
1034
1035 bool isWritable() const override {
1036 return fParent->isWritable();
1037 }
1038
1039 [[nodiscard]] bool evaluateDynamicIndices(Generator* gen) {
1040 // The index must only be computed once; the index-expression could have side effects.
1041 // Once it has been computed, the offset lives on `fDedicatedStack`.
1042 SkASSERT(!fDedicatedStack.has_value());
1043 SkASSERT(!fGenerator);
1044 fGenerator = gen;
1045 fDedicatedStack.emplace(fGenerator);
1046
1047 if (!fParent->swizzle().empty()) {
1048 SkDEBUGFAIL("an indexed-swizzle should have been handled by RewriteIndexedSwizzle");
1049 return unsupported();
1050 }
1051
1052 // Push the index expression onto the dedicated stack.
1053 fDedicatedStack->enter();
1054 if (!fGenerator->pushExpression(*fIndexExpr->index())) {
1055 return unsupported();
1056 }
1057
1058 // Multiply the index-expression result by the per-value slot count.
1059 int slotCount = fIndexExpr->type().slotCount();
1060 if (slotCount != 1) {
1061 fGenerator->builder()->push_constant_i(fIndexExpr->type().slotCount());
1062 fGenerator->builder()->binary_op(BuilderOp::mul_n_ints, 1);
1063 }
1064
1065 // Check to see if a parent LValue already has a dynamic index. If so, we need to
1066 // incorporate its value into our own.
1067 if (AutoStack* parentDynamicIndexStack = fParent->dynamicSlotRange()) {
1068 parentDynamicIndexStack->pushClone(/*slots=*/1);
1069 fGenerator->builder()->binary_op(BuilderOp::add_n_ints, 1);
1070 }
1071 fDedicatedStack->exit();
1072 return true;
1073 }
1074
1075 SlotRange fixedSlotRange(Generator* gen) override {
1076 // Compute the fixed slot range as if we are indexing into position zero.
1077 SlotRange range = fParent->fixedSlotRange(gen);
1078 range.count = fIndexExpr->type().slotCount();
1079 return range;
1080 }
1081
1082 AutoStack* dynamicSlotRange() override {
1083 // We incorporated any parent dynamic offsets when `evaluateDynamicIndices` was called.
1084 SkASSERT(fDedicatedStack.has_value());
1085 return &*fDedicatedStack;
1086 }
1087
1088 [[nodiscard]] bool push(Generator* gen,
1089 SlotRange fixedOffset,
1090 AutoStack* dynamicOffset,
1091 SkSpan<const int8_t> swizzle) override {
1092 return fParent->push(gen, fixedOffset, dynamicOffset, swizzle);
1093 }
1094
1095 [[nodiscard]] bool store(Generator* gen,
1096 SlotRange fixedOffset,
1097 AutoStack* dynamicOffset,
1098 SkSpan<const int8_t> swizzle) override {
1099 return fParent->store(gen, fixedOffset, dynamicOffset, swizzle);
1100 }
1101
1102 private:
1103 Generator* fGenerator = nullptr;
1104 std::unique_ptr<LValue> fParent;
1105 std::optional<AutoStack> fDedicatedStack;
1106 const IndexExpression* fIndexExpr = nullptr;
1107 };
1108
1109 void SlotManager::addSlotDebugInfoForGroup(const std::string& varName,
1110 const Type& type,
1111 Position pos,
1112 int* groupIndex,
1113 bool isFunctionReturnValue) {
1114 SkASSERT(fSlotDebugInfo);
1115 switch (type.typeKind()) {
1116 case Type::TypeKind::kArray: {
1117 int nslots = type.columns();
1118 const Type& elemType = type.componentType();
1119 for (int slot = 0; slot < nslots; ++slot) {
1120 this->addSlotDebugInfoForGroup(varName + "[" + std::to_string(slot) + "]", elemType,
1121 pos, groupIndex, isFunctionReturnValue);
1122 }
1123 break;
1124 }
1125 case Type::TypeKind::kStruct: {
1126 for (const Field& field : type.fields()) {
1127 this->addSlotDebugInfoForGroup(varName + "." + std::string(field.fName),
1128 *field.fType, pos, groupIndex,
1129 isFunctionReturnValue);
1130 }
1131 break;
1132 }
1133 default:
1134 SkASSERTF(0, "unsupported slot type %d", (int)type.typeKind());
1135 [[fallthrough]];
1136
1137 case Type::TypeKind::kScalar:
1138 case Type::TypeKind::kVector:
1139 case Type::TypeKind::kMatrix: {
1140 Type::NumberKind numberKind = type.componentType().numberKind();
1141 int nslots = type.slotCount();
1142
1143 for (int slot = 0; slot < nslots; ++slot) {
1144 SlotDebugInfo slotInfo;
1145 slotInfo.name = varName;
1146 slotInfo.columns = type.columns();
1147 slotInfo.rows = type.rows();
1148 slotInfo.componentIndex = slot;
1149 slotInfo.groupIndex = (*groupIndex)++;
1150 slotInfo.numberKind = numberKind;
1151 slotInfo.pos = pos;
1152 slotInfo.fnReturnValue = isFunctionReturnValue ? 1 : -1;
1153 fSlotDebugInfo->push_back(std::move(slotInfo));
1154 }
1155 break;
1156 }
1157 }
1158 }
1159
1160 void SlotManager::addSlotDebugInfo(const std::string& varName,
1161 const Type& type,
1162 Position pos,
1163 bool isFunctionReturnValue) {
1164 int groupIndex = 0;
1165 this->addSlotDebugInfoForGroup(varName, type, pos, &groupIndex, isFunctionReturnValue);
1166 SkASSERT((size_t)groupIndex == type.slotCount());
1167 }
1168
1169 SlotRange SlotManager::createSlots(std::string name,
1170 const Type& type,
1171 Position pos,
1172 bool isFunctionReturnValue) {
1173 size_t nslots = type.slotCount();
1174 if (nslots == 0) {
1175 return {};
1176 }
1177 if (fSlotDebugInfo) {
1178 // Our debug slot-info table should have the same length as the actual slot table.
1179 SkASSERT(fSlotDebugInfo->size() == (size_t)fSlotCount);
1180
1181 // Append slot names and types to our debug slot-info table.
1182 fSlotDebugInfo->reserve(fSlotCount + nslots);
1183 this->addSlotDebugInfo(name, type, pos, isFunctionReturnValue);
1184
1185 // Confirm that we added the expected number of slots.
1186 SkASSERT(fSlotDebugInfo->size() == (size_t)(fSlotCount + nslots));
1187 }
1188
1189 SlotRange result = {fSlotCount, (int)nslots};
1190 fSlotCount += nslots;
1191 return result;
1192 }
1193
1194 std::optional<SlotRange> SlotManager::mapVariableToSlots(const Variable& v, SlotRange range) {
1195 SkASSERT(v.type().slotCount() == SkToSizeT(range.count));
1196 const SlotRange* existingEntry = fSlotMap.find(&v);
1197 std::optional<SlotRange> originalRange = existingEntry ? std::optional(*existingEntry)
1198 : std::nullopt;
1199 fSlotMap.set(&v, range);
1200 return originalRange;
1201 }
1202
1203 void SlotManager::unmapVariableSlots(const Variable& v) {
1204 fSlotMap.remove(&v);
1205 }
1206
1207 SlotRange SlotManager::getVariableSlots(const Variable& v) {
1208 SlotRange* entry = fSlotMap.find(&v);
1209 if (entry != nullptr) {
1210 return *entry;
1211 }
1212 SlotRange range = this->createSlots(std::string(v.name()),
1213 v.type(),
1214 v.fPosition,
1215 /*isFunctionReturnValue=*/false);
1216 this->mapVariableToSlots(v, range);
1217 return range;
1218 }
1219
1220 SlotRange SlotManager::getFunctionSlots(const IRNode& callSite, const FunctionDeclaration& f) {
1221 SlotRange* entry = fSlotMap.find(&callSite);
1222 if (entry != nullptr) {
1223 return *entry;
1224 }
1225 SlotRange range = this->createSlots("[" + std::string(f.name()) + "].result",
1226 f.returnType(),
1227 f.fPosition,
1228 /*isFunctionReturnValue=*/true);
1229 fSlotMap.set(&callSite, range);
1230 return range;
1231 }
1232
1233 static bool is_sliceable_swizzle(SkSpan<const int8_t> components) {
1234 // Determine if the swizzle rearranges its elements, or if it's a simple subset of its elements.
1235 // (A simple subset would be a sequential non-repeating range of components, like `.xyz` or
1236 // `.yzw` or `.z`, but not `.xx` or `.xz`, which can be accessed as a slice of the variable.)
1237 for (size_t index = 1; index < components.size(); ++index) {
1238 if (components[index] != int8_t(components[0] + index)) {
1239 return false;
1240 }
1241 }
1242 return true;
1243 }
1244
1245 std::unique_ptr<LValue> Generator::makeLValue(const Expression& e, bool allowScratch) {
1246 if (e.is<VariableReference>()) {
1247 const Variable* variable = e.as<VariableReference>().variable();
1248 if (fImmutableVariables.contains(variable)) {
1249 return std::make_unique<ImmutableLValue>(variable);
1250 }
1251 return std::make_unique<VariableLValue>(variable);
1252 }
1253 if (e.is<Swizzle>()) {
1254 const Swizzle& swizzleExpr = e.as<Swizzle>();
1255 if (std::unique_ptr<LValue> base = this->makeLValue(*swizzleExpr.base(),
1256 allowScratch)) {
1257 const ComponentArray& components = swizzleExpr.components();
1258 if (is_sliceable_swizzle(components)) {
1259 // If the swizzle is a contiguous subset, we can represent it with a fixed slice.
1260 return std::make_unique<LValueSlice>(std::move(base), components[0],
1261 components.size());
1262 }
1263 return std::make_unique<SwizzleLValue>(std::move(base), components);
1264 }
1265 return nullptr;
1266 }
1267 if (e.is<FieldAccess>()) {
1268 const FieldAccess& fieldExpr = e.as<FieldAccess>();
1269 if (std::unique_ptr<LValue> base = this->makeLValue(*fieldExpr.base(),
1270 allowScratch)) {
1271 // Represent field access with a slice.
1272 return std::make_unique<LValueSlice>(std::move(base), fieldExpr.initialSlot(),
1273 fieldExpr.type().slotCount());
1274 }
1275 return nullptr;
1276 }
1277 if (e.is<IndexExpression>()) {
1278 const IndexExpression& indexExpr = e.as<IndexExpression>();
1279
1280 // If the index base is swizzled (`vec.zyx[idx]`), rewrite it into an equivalent
1281 // non-swizzled form (`vec[uint3(2,1,0)[idx]]`).
1282 if (std::unique_ptr<Expression> rewritten = Transform::RewriteIndexedSwizzle(fContext,
1283 indexExpr)) {
1284 // Convert the rewritten expression into an lvalue.
1285 std::unique_ptr<LValue> lvalue = this->makeLValue(*rewritten, allowScratch);
1286 if (!lvalue) {
1287 return nullptr;
1288 }
1289 // We need to hold onto the rewritten expression for the lifetime of the lvalue.
1290 lvalue->fScratchExpression = std::move(rewritten);
1291 return lvalue;
1292 }
1293 if (std::unique_ptr<LValue> base = this->makeLValue(*indexExpr.base(),
1294 allowScratch)) {
1295 // If the index is a compile-time constant, we can represent it with a fixed slice.
1296 SKSL_INT indexValue;
1297 if (ConstantFolder::GetConstantInt(*indexExpr.index(), &indexValue)) {
1298 int numSlots = indexExpr.type().slotCount();
1299 return std::make_unique<LValueSlice>(std::move(base), numSlots * indexValue,
1300 numSlots);
1301 }
1302
1303 // Represent non-constant indexing via a dynamic index.
1304 auto dynLValue = std::make_unique<DynamicIndexLValue>(std::move(base), indexExpr);
1305 return dynLValue->evaluateDynamicIndices(this) ? std::move(dynLValue)
1306 : nullptr;
1307 }
1308 return nullptr;
1309 }
1310 if (allowScratch) {
1311 // This path allows us to perform field- and index-accesses on an expression as if it were
1312 // an lvalue, but is a temporary and shouldn't be written back to.
1313 return std::make_unique<ScratchLValue>(e);
1314 }
1315 return nullptr;
1316 }
1317
1318 bool Generator::push(LValue& lvalue) {
1319 return lvalue.push(this,
1320 lvalue.fixedSlotRange(this),
1321 lvalue.dynamicSlotRange(),
1322 /*swizzle=*/{});
1323 }
1324
1325 bool Generator::store(LValue& lvalue) {
1326 SkASSERT(lvalue.isWritable());
1327 return lvalue.store(this,
1328 lvalue.fixedSlotRange(this),
1329 lvalue.dynamicSlotRange(),
1330 /*swizzle=*/{});
1331 }
1332
1333 int Generator::getFunctionDebugInfo(const FunctionDeclaration& decl) {
1334 SkASSERT(fDebugTrace);
1335
1336 std::string name = decl.description();
1337
1338 // When generating the debug trace, we typically mark every function as `noinline`. This makes
1339 // the trace more confusing, since this isn't in the source program, so remove it.
1340 static constexpr std::string_view kNoInline = "noinline ";
1341 if (skstd::starts_with(name, kNoInline)) {
1342 name = name.substr(kNoInline.size());
1343 }
1344
1345 // Look for a matching FunctionDebugInfo slot.
1346 for (size_t index = 0; index < fDebugTrace->fFuncInfo.size(); ++index) {
1347 if (fDebugTrace->fFuncInfo[index].name == name) {
1348 return index;
1349 }
1350 }
1351
1352 // We've never called this function before; create a new slot to hold its information.
1353 int slot = (int)fDebugTrace->fFuncInfo.size();
1354 fDebugTrace->fFuncInfo.push_back(FunctionDebugInfo{std::move(name)});
1355 return slot;
1356 }
1357
1358 int Generator::createStack() {
1359 if (!fRecycledStacks.empty()) {
1360 int stackID = fRecycledStacks.back();
1361 fRecycledStacks.pop_back();
1362 return stackID;
1363 }
1364 return ++fNextStackID;
1365 }
1366
1367 void Generator::recycleStack(int stackID) {
1368 fRecycledStacks.push_back(stackID);
1369 }
1370
1371 void Generator::setCurrentStack(int stackID) {
1372 if (fCurrentStack != stackID) {
1373 fCurrentStack = stackID;
1374 fBuilder.set_current_stack(stackID);
1375 }
1376 }
1377
1378 std::optional<SlotRange> Generator::writeFunction(
1379 const IRNode& callSite,
1380 const FunctionDefinition& function,
1381 SkSpan<std::unique_ptr<Expression> const> arguments) {
1382 // Generate debug information and emit a trace-enter op.
1383 int funcIndex = -1;
1384 if (fDebugTrace) {
1385 funcIndex = this->getFunctionDebugInfo(function.declaration());
1386 SkASSERT(funcIndex >= 0);
1387 if (this->shouldWriteTraceOps()) {
1388 fBuilder.trace_enter(fTraceMask->stackID(), funcIndex);
1389 }
1390 }
1391
1392 // Handle parameter lvalues.
1393 struct RemappedSlotRange {
1394 const Variable* fVariable;
1395 std::optional<SlotRange> fSlotRange;
1396 };
1397 SkSpan<Variable* const> parameters = function.declaration().parameters();
1398 TArray<std::unique_ptr<LValue>> lvalues;
1399 TArray<RemappedSlotRange> remappedSlotRanges;
1400
1401 if (function.declaration().isMain()) {
1402 // For main(), the parameter slots have already been populated by `writeProgram`, but we
1403 // still need to explicitly emit trace ops for the variables in main(), since they are
1404 // initialized before it is safe to use trace-var. (We can't invoke init-lane-masks until
1405 // after we've copied the inputs from main into slots, because dst.rgba is used to pass in a
1406 // blend-destination color, but we clobber it and put in the execution mask instead.)
1407 if (this->shouldWriteTraceOps()) {
1408 for (const Variable* var : parameters) {
1409 fBuilder.trace_var(fTraceMask->stackID(), this->getVariableSlots(*var));
1410 }
1411 }
1412 } else {
1413 // Write all the arguments into their parameter's variable slots. Because we never allow
1414 // recursion, we don't need to worry about overwriting any existing values in those slots.
1415 // (In fact, we don't even need to apply the write mask.)
1416 lvalues.resize(arguments.size());
1417
1418 for (size_t index = 0; index < arguments.size(); ++index) {
1419 const Expression& arg = *arguments[index];
1420 const Variable& param = *parameters[index];
1421
1422 // If we are passing a child effect to a function, we need to add its mapping to our
1423 // child map.
1424 if (arg.type().isEffectChild()) {
•1425 if (int* childIndexPtr =
1426 fChildEffectMap.find(arg.as<VariableReference>().variable())) {
1427 // In earlier C++ versions, the map assignment could cause the map to be
1428 // resized, invalidating the pointer.
1429 int childIndex = *childIndexPtr;
1430 SkASSERT(!fChildEffectMap.find(&param));
•1431 fChildEffectMap[&param] = childIndex;
1432 }
1433 continue;
1434 }
1435
1436 // Use LValues for out-parameters and inout-parameters, so we can store back to them
1437 // later.
1438 if (IsInoutParameter(param) || IsOutParameter(param)) {
1439 lvalues[index] = this->makeLValue(arg);
1440 if (!lvalues[index]) {
1441 return std::nullopt;
1442 }
1443 // There are no guarantees on the starting value of an out-parameter, so we only
1444 // need to store the lvalues associated with an inout parameter.
1445 if (IsInoutParameter(param)) {
1446 if (!this->push(*lvalues[index])) {
1447 return std::nullopt;
1448 }
1449 this->popToSlotRangeUnmasked(this->getVariableSlots(param));
1450 }
1451 continue;
1452 }
1453
1454 // If a parameter is never read by the function, we don't need to populate its slots.
1455 ProgramUsage::VariableCounts paramCounts = fProgram.fUsage->get(param);
1456 if (paramCounts.fRead == 0) {
1457 // Honor the expression's side effects, if any.
1458 if (Analysis::HasSideEffects(arg)) {
1459 if (!this->pushExpression(arg, /*usesResult=*/false)) {
1460 return std::nullopt;
1461 }
1462 this->discardExpression(arg.type().slotCount());
1463 }
1464 continue;
1465 }
1466
1467 // If the expression is a plain variable and the parameter is never written to, we don't
1468 // need to copy it; we can just share the slots from the existing variable.
1469 if (paramCounts.fWrite == 0 && arg.is<VariableReference>()) {
1470 const Variable& var = *arg.as<VariableReference>().variable();
1471 if (this->hasVariableSlots(var)) {
1472 std::optional<SlotRange> originalRange =
1473 fProgramSlots.mapVariableToSlots(param, this->getVariableSlots(var));
1474 remappedSlotRanges.push_back({&param, originalRange});
1475 continue;
1476 }
1477 }
1478
1479 // Copy input arguments into their respective parameter slots.
1480 if (!this->pushExpression(arg)) {
1481 return std::nullopt;
1482 }
1483 this->popToSlotRangeUnmasked(this->getVariableSlots(param));
1484 }
1485 }
1486
1487 // Set up a slot range dedicated to this function's return value.
1488 SlotRange lastFunctionResult = fCurrentFunctionResult;
1489 fCurrentFunctionResult = this->getFunctionSlots(callSite, function.declaration());
1490
1491 // Save off the return mask.
1492 if (this->needsReturnMask(&function)) {
1493 fBuilder.enableExecutionMaskWrites();
1494 if (!function.declaration().isMain()) {
1495 fBuilder.push_return_mask();
1496 }
1497 }
1498
1499 // Emit the function body.
1500 if (!this->writeStatement(*function.body())) {
1501 return std::nullopt;
1502 }
1503
1504 // Restore the original return mask.
1505 if (this->needsReturnMask(&function)) {
1506 if (!function.declaration().isMain()) {
1507 fBuilder.pop_return_mask();
1508 }
1509 fBuilder.disableExecutionMaskWrites();
1510 }
1511
1512 // Restore the function-result slot range.
1513 SlotRange functionResult = fCurrentFunctionResult;
1514 fCurrentFunctionResult = lastFunctionResult;
1515
1516 // Emit a trace-exit op.
1517 if (fDebugTrace && fWriteTraceOps) {
1518 fBuilder.trace_exit(fTraceMask->stackID(), funcIndex);
1519 }
1520
1521 // Copy out-parameters and inout-parameters back to their homes.
1522 for (int index = 0; index < lvalues.size(); ++index) {
1523 if (lvalues[index]) {
1524 // Only out- and inout-parameters should have an associated lvalue.
1525 const Variable& param = *parameters[index];
1526 SkASSERT(IsInoutParameter(param) || IsOutParameter(param));
1527
1528 // Copy the parameter's slots directly into the lvalue.
1529 fBuilder.push_slots(this->getVariableSlots(param));
1530 if (!this->store(*lvalues[index])) {
1531 return std::nullopt;
1532 }
1533 this->discardExpression(param.type().slotCount());
1534 }
1535 }
1536
1537 // Restore any remapped parameter slot ranges to their original values.
1538 for (const RemappedSlotRange& remapped : remappedSlotRanges) {
1539 if (remapped.fSlotRange.has_value()) {
1540 fProgramSlots.mapVariableToSlots(*remapped.fVariable, *remapped.fSlotRange);
1541 } else {
1542 fProgramSlots.unmapVariableSlots(*remapped.fVariable);
1543 }
1544 }
1545
1546 // Remove any child-effect mappings that were made for this call.
1547 for (size_t index = 0; index < arguments.size(); ++index) {
1548 const Expression& arg = *arguments[index];
1549 if (arg.type().isEffectChild()) {
1550 fChildEffectMap.remove(parameters[index]);
1551 }
1552 }
1553
1554 return functionResult;
1555 }
1556
1557 void Generator::emitTraceLine(Position pos) {
1558 if (fDebugTrace && fWriteTraceOps && pos.valid() && fInsideCompoundStatement == 0) {
1559 // Binary search within fLineOffets to convert the position into a line number.
1560 SkASSERT(fLineOffsets.size() >= 2);
1561 SkASSERT(fLineOffsets[0] == 0);
1562 SkASSERT(fLineOffsets.back() == (int)fProgram.fSource->length());
1563 int lineNumber = std::distance(
1564 fLineOffsets.begin(),
1565 std::upper_bound(fLineOffsets.begin(), fLineOffsets.end(), pos.startOffset()));
1566
1567 fBuilder.trace_line(fTraceMask->stackID(), lineNumber);
1568 }
1569 }
1570
1571 void Generator::pushTraceScopeMask() {
1572 if (this->shouldWriteTraceOps()) {
1573 // Take the intersection of the trace mask and the execution mask. To do this, start with an
1574 // all-zero mask, then use select to overwrite those zeros with the trace mask across all
1575 // executing lanes. We'll get the trace mask in executing lanes, and zero in dead lanes.
1576 fBuilder.push_constant_i(0);
1577 fTraceMask->pushClone(/*slots=*/1);
1578 fBuilder.select(/*slots=*/1);
1579 }
1580 }
1581
1582 void Generator::discardTraceScopeMask() {
1583 if (this->shouldWriteTraceOps()) {
1584 this->discardExpression(/*slots=*/1);
1585 }
1586 }
1587
1588 void Generator::emitTraceScope(int delta) {
1589 if (this->shouldWriteTraceOps()) {
1590 fBuilder.trace_scope(this->currentStack(), delta);
1591 }
1592 }
1593
1594 void Generator::calculateLineOffsets() {
1595 SkASSERT(fLineOffsets.empty());
1596 fLineOffsets.push_back(0);
1597 for (size_t i = 0; i < fProgram.fSource->length(); ++i) {
1598 if ((*fProgram.fSource)[i] == '\n') {
1599 fLineOffsets.push_back(i);
1600 }
1601 }
1602 fLineOffsets.push_back(fProgram.fSource->length());
1603 }
1604
1605 bool Generator::writeGlobals() {
1606 for (const ProgramElement* e : fProgram.elements()) {
1607 if (e->is<GlobalVarDeclaration>()) {
1608 const GlobalVarDeclaration& gvd = e->as<GlobalVarDeclaration>();
1609 const VarDeclaration& decl = gvd.varDeclaration();
1610 const Variable* var = decl.var();
1611
1612 if (var->type().isEffectChild()) {
1613 // Associate each child effect variable with its numeric index.
1614 SkASSERT(!fChildEffectMap.find(var));
1615 int childEffectIndex = fChildEffectMap.count();
1616 fChildEffectMap[var] = childEffectIndex;
1617 continue;
1618 }
1619
1620 // Opaque types include child processors and GL objects (samplers, textures, etc).
1621 // Of those, only child processors are legal variables.
1622 SkASSERT(!var->type().isVoid());
1623 SkASSERT(!var->type().isOpaque());
1624
1625 // Builtin variables are system-defined, with special semantics.
1626 if (int builtin = var->layout().fBuiltin; builtin >= 0) {
1627 if (builtin == SK_FRAGCOORD_BUILTIN) {
1628 fBuilder.store_device_xy01(this->getVariableSlots(*var));
1629 continue;
1630 }
1631 // The only builtin variable exposed to runtime effects is sk_FragCoord.
1632 return unsupported();
1633 }
1634
1635 if (IsUniform(*var)) {
1636 // Create the uniform slot map in first-to-last order.
1637 SlotRange uniformSlotRange = this->getUniformSlots(*var);
1638
1639 if (this->shouldWriteTraceOps()) {
1640 // We expect uniform values to show up in the debug trace. To make this happen
1641 // without updating the file format, we synthesize a value-slot range for the
1642 // uniform here, and copy the uniform data into the value slots. This allows
1643 // trace_var to work naturally. This wastes a bit of memory, but debug traces
1644 // don't need to be hyper-efficient.
1645 SlotRange copyRange = fProgramSlots.getVariableSlots(*var);
1646 fBuilder.push_uniform(uniformSlotRange);
1647 this->popToSlotRangeUnmasked(copyRange);
1648 }
1649
1650 continue;
1651 }
1652
1653 // Other globals are treated as normal variable declarations.
1654 if (!this->writeVarDeclaration(decl)) {
1655 return unsupported();
1656 }
1657 }
1658 }
1659
1660 return true;
1661 }
1662
1663 bool Generator::writeStatement(const Statement& s) {
1664 switch (s.kind()) {
1665 case Statement::Kind::kBlock:
1666 // The debugger will stop on statements inside Blocks; there's no need for an additional
1667 // stop on the block's initial open-brace.
1668 case Statement::Kind::kFor:
1669 // The debugger will stop on the init-statement of a for statement, so we don't need to
1670 // stop on the outer for-statement itself as well.
1671 break;
1672
1673 default:
1674 // The debugger should stop on other statements.
1675 this->emitTraceLine(s.fPosition);
1676 break;
1677 }
1678
1679 switch (s.kind()) {
1680 case Statement::Kind::kBlock:
1681 return this->writeBlock(s.as<Block>());
1682
1683 case Statement::Kind::kBreak:
1684 return this->writeBreakStatement(s.as<BreakStatement>());
1685
1686 case Statement::Kind::kContinue:
1687 return this->writeContinueStatement(s.as<ContinueStatement>());
1688
1689 case Statement::Kind::kDo:
1690 return this->writeDoStatement(s.as<DoStatement>());
1691
1692 case Statement::Kind::kExpression:
1693 return this->writeExpressionStatement(s.as<ExpressionStatement>());
1694
1695 case Statement::Kind::kFor:
1696 return this->writeForStatement(s.as<ForStatement>());
1697
1698 case Statement::Kind::kIf:
1699 return this->writeIfStatement(s.as<IfStatement>());
1700
1701 case Statement::Kind::kNop:
1702 return true;
1703
1704 case Statement::Kind::kReturn:
1705 return this->writeReturnStatement(s.as<ReturnStatement>());
1706
1707 case Statement::Kind::kSwitch:
1708 return this->writeSwitchStatement(s.as<SwitchStatement>());
1709
1710 case Statement::Kind::kVarDeclaration:
1711 return this->writeVarDeclaration(s.as<VarDeclaration>());
1712
1713 default:
1714 return unsupported();
1715 }
1716 }
1717
1718 bool Generator::writeBlock(const Block& b) {
1719 if (b.blockKind() == Block::Kind::kCompoundStatement) {
1720 this->emitTraceLine(b.fPosition);
1721 ++fInsideCompoundStatement;
1722 } else {
1723 this->pushTraceScopeMask();
1724 this->emitTraceScope(+1);
1725 }
1726
1727 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1728 if (!this->writeStatement(*stmt)) {
1729 return unsupported();
1730 }
1731 }
1732
1733 if (b.blockKind() == Block::Kind::kCompoundStatement) {
1734 --fInsideCompoundStatement;
1735 } else {
1736 this->emitTraceScope(-1);
1737 this->discardTraceScopeMask();
1738 }
1739
1740 return true;
1741 }
1742
1743 bool Generator::writeBreakStatement(const BreakStatement&) {
1744 // If all lanes have reached this break, we can just branch straight to the break target instead
1745 // of updating masks.
1746 fBuilder.branch_if_all_lanes_active(fCurrentBreakTarget);
1747 fBuilder.mask_off_loop_mask();
1748 return true;
1749 }
1750
1751 bool Generator::writeContinueStatement(const ContinueStatement&) {
1752 fBuilder.continue_op(fCurrentContinueMask->stackID());
1753 return true;
1754 }
1755
1756 bool Generator::writeDoStatement(const DoStatement& d) {
1757 // Set up a break target.
1758 AutoLoopTarget breakTarget(this, &fCurrentBreakTarget);
1759
1760 // Save off the original loop mask.
1761 fBuilder.enableExecutionMaskWrites();
1762 fBuilder.push_loop_mask();
1763
1764 // If `continue` is used in the loop...
1765 Analysis::LoopControlFlowInfo loopInfo = Analysis::GetLoopControlFlowInfo(*d.statement());
1766 AutoContinueMask autoContinueMask(this);
1767 if (loopInfo.fHasContinue) {
1768 // ... create a temporary slot for continue-mask storage.
1769 autoContinueMask.enable();
1770 }
1771
1772 // Write the do-loop body.
1773 int labelID = fBuilder.nextLabelID();
1774 fBuilder.label(labelID);
1775
1776 autoContinueMask.enterLoopBody();
1777
1778 if (!this->writeStatement(*d.statement())) {
1779 return false;
1780 }
1781
1782 autoContinueMask.exitLoopBody();
1783
1784 // Point the debugger at the do-statement's test-expression before we run it.
1785 this->emitTraceLine(d.test()->fPosition);
1786
1787 // Emit the test-expression, in order to combine it with the loop mask.
1788 if (!this->pushExpression(*d.test())) {
1789 return false;
1790 }
1791
1792 // Mask off any lanes in the loop mask where the test-expression is false; this breaks the loop.
1793 // We don't use the test expression for anything else, so jettison it.
1794 fBuilder.merge_loop_mask();
1795 this->discardExpression(/*slots=*/1);
1796
1797 // If any lanes are still running, go back to the top and run the loop body again.
1798 fBuilder.branch_if_any_lanes_active(labelID);
1799
1800 // If we hit a break statement on all lanes, we will branch here to escape from the loop.
1801 fBuilder.label(breakTarget.labelID());
1802
1803 // Restore the loop mask.
1804 fBuilder.pop_loop_mask();
1805 fBuilder.disableExecutionMaskWrites();
1806
1807 return true;
1808 }
1809
1810 bool Generator::writeMasklessForStatement(const ForStatement& f) {
1811 SkASSERT(f.unrollInfo());
1812 SkASSERT(f.unrollInfo()->fCount > 0);
1813 SkASSERT(f.initializer());
1814 SkASSERT(f.test());
1815 SkASSERT(f.next());
1816
1817 // We want the loop index to disappear at the end of the loop, so wrap the for statement in a
1818 // trace scope.
1819 this->pushTraceScopeMask();
1820 this->emitTraceScope(+1);
1821
1822 // If no lanes are active, skip over the loop entirely. This guards against looping forever;
1823 // with no lanes active, we wouldn't be able to write the loop variable back to its slot, so
1824 // we'd never make forward progress.
1825 int loopExitID = fBuilder.nextLabelID();
1826 int loopBodyID = fBuilder.nextLabelID();
1827 fBuilder.branch_if_no_lanes_active(loopExitID);
1828
1829 // Run the loop initializer.
1830 if (!this->writeStatement(*f.initializer())) {
1831 return unsupported();
1832 }
1833
1834 // Write the for-loop body. We know the for-loop has a standard ES2 unrollable structure, and
1835 // that it runs for at least one iteration, so we can plow straight ahead into the loop body
1836 // instead of running the loop-test first.
1837 fBuilder.label(loopBodyID);
1838
1839 if (!this->writeStatement(*f.statement())) {
1840 return unsupported();
1841 }
1842
1843 // Point the debugger at the for-statement's next-expression before we run it, or as close as we
1844 // can reasonably get.
1845 if (f.next()) {
1846 this->emitTraceLine(f.next()->fPosition);
1847 } else if (f.test()) {
1848 this->emitTraceLine(f.test()->fPosition);
1849 } else {
1850 this->emitTraceLine(f.fPosition);
1851 }
1852
1853 // If the loop only runs for a single iteration, we are already done. If not...
1854 if (f.unrollInfo()->fCount > 1) {
1855 // ... run the next-expression, and immediately discard its result.
1856 if (!this->pushExpression(*f.next(), /*usesResult=*/false)) {
1857 return unsupported();
1858 }
1859 this->discardExpression(f.next()->type().slotCount());
1860
1861 // Run the test-expression, and repeat the loop until the test-expression evaluates false.
1862 if (!this->pushExpression(*f.test())) {
1863 return unsupported();
1864 }
1865 fBuilder.branch_if_no_active_lanes_on_stack_top_equal(0, loopBodyID);
1866
1867 // Jettison the test-expression.
1868 this->discardExpression(/*slots=*/1);
1869 }
1870
1871 fBuilder.label(loopExitID);
1872
1873 this->emitTraceScope(-1);
1874 this->discardTraceScopeMask();
1875 return true;
1876 }
1877
1878 bool Generator::writeForStatement(const ForStatement& f) {
1879 // If we've determined that the loop does not run, omit its code entirely.
1880 if (f.unrollInfo() && f.unrollInfo()->fCount == 0) {
1881 return true;
1882 }
1883
1884 // If the loop doesn't escape early due to a `continue`, `break` or `return`, and the loop
1885 // conforms to ES2 structure, we know that we will run the full number of iterations across all
1886 // lanes and don't need to use a loop mask.
1887 Analysis::LoopControlFlowInfo loopInfo = Analysis::GetLoopControlFlowInfo(*f.statement());
1888 if (!loopInfo.fHasContinue && !loopInfo.fHasBreak && !loopInfo.fHasReturn && f.unrollInfo()) {
1889 return this->writeMasklessForStatement(f);
1890 }
1891
1892 // We want the loop index to disappear at the end of the loop, so wrap the for statement in a
1893 // trace scope.
1894 this->pushTraceScopeMask();
1895 this->emitTraceScope(+1);
1896
1897 // Set up a break target.
1898 AutoLoopTarget breakTarget(this, &fCurrentBreakTarget);
1899
1900 // Run the loop initializer.
1901 if (f.initializer()) {
1902 if (!this->writeStatement(*f.initializer())) {
1903 return unsupported();
1904 }
1905 } else {
1906 this->emitTraceLine(f.fPosition);
1907 }
1908
1909 AutoContinueMask autoContinueMask(this);
1910 if (loopInfo.fHasContinue) {
1911 // Acquire a temporary slot for continue-mask storage.
1912 autoContinueMask.enable();
1913 }
1914
1915 // Save off the original loop mask.
1916 fBuilder.enableExecutionMaskWrites();
1917 fBuilder.push_loop_mask();
1918
1919 int loopTestID = fBuilder.nextLabelID();
1920 int loopBodyID = fBuilder.nextLabelID();
1921
1922 // Jump down to the loop test so we can fall out of the loop immediately if it's zero-iteration.
1923 fBuilder.jump(loopTestID);
1924
1925 // Write the for-loop body.
1926 fBuilder.label(loopBodyID);
1927
1928 autoContinueMask.enterLoopBody();
1929
1930 if (!this->writeStatement(*f.statement())) {
1931 return unsupported();
1932 }
1933
1934 autoContinueMask.exitLoopBody();
1935
1936 // Point the debugger at the for-statement's next-expression before we run it, or as close as we
1937 // can reasonably get.
1938 if (f.next()) {
1939 this->emitTraceLine(f.next()->fPosition);
1940 } else if (f.test()) {
1941 this->emitTraceLine(f.test()->fPosition);
1942 } else {
1943 this->emitTraceLine(f.fPosition);
1944 }
1945
1946 // Run the next-expression. Immediately discard its result.
1947 if (f.next()) {
1948 if (!this->pushExpression(*f.next(), /*usesResult=*/false)) {
1949 return unsupported();
1950 }
1951 this->discardExpression(f.next()->type().slotCount());
1952 }
1953
1954 fBuilder.label(loopTestID);
1955 if (f.test()) {
1956 // Emit the test-expression, in order to combine it with the loop mask.
1957 if (!this->pushExpression(*f.test())) {
1958 return unsupported();
1959 }
1960 // Mask off any lanes in the loop mask where the test-expression is false; this breaks the
1961 // loop. We don't use the test expression for anything else, so jettison it.
1962 fBuilder.merge_loop_mask();
1963 this->discardExpression(/*slots=*/1);
1964 }
1965
1966 // If any lanes are still running, go back to the top and run the loop body again.
1967 fBuilder.branch_if_any_lanes_active(loopBodyID);
1968
1969 // If we hit a break statement on all lanes, we will branch here to escape from the loop.
1970 fBuilder.label(breakTarget.labelID());
1971
1972 // Restore the loop mask.
1973 fBuilder.pop_loop_mask();
1974 fBuilder.disableExecutionMaskWrites();
1975
1976 this->emitTraceScope(-1);
1977 this->discardTraceScopeMask();
1978 return true;
1979 }
1980
1981 bool Generator::writeExpressionStatement(const ExpressionStatement& e) {
1982 if (!this->pushExpression(*e.expression(), /*usesResult=*/false)) {
1983 return unsupported();
1984 }
1985 this->discardExpression(e.expression()->type().slotCount());
1986 return true;
1987 }
1988
1989 bool Generator::writeDynamicallyUniformIfStatement(const IfStatement& i) {
1990 SkASSERT(Analysis::IsDynamicallyUniformExpression(*i.test()));
1991
1992 int falseLabelID = fBuilder.nextLabelID();
1993 int exitLabelID = fBuilder.nextLabelID();
1994
1995 if (!this->pushExpression(*i.test())) {
1996 return unsupported();
1997 }
1998
1999 fBuilder.branch_if_no_active_lanes_on_stack_top_equal(~0, falseLabelID);
2000
2001 if (!this->writeStatement(*i.ifTrue())) {
2002 return unsupported();
2003 }
2004
2005 if (!i.ifFalse()) {
2006 // We don't have an if-false condition at all.
2007 fBuilder.label(falseLabelID);
2008 } else {
2009 // We do have an if-false condition. We've just completed the if-true block, so we need to
2010 // jump past the if-false block to avoid executing it.
2011 fBuilder.jump(exitLabelID);
2012
2013 // The if-false block starts here.
2014 fBuilder.label(falseLabelID);
2015
2016 if (!this->writeStatement(*i.ifFalse())) {
2017 return unsupported();
2018 }
2019
2020 fBuilder.label(exitLabelID);
2021 }
2022
2023 // Jettison the test-expression.
2024 this->discardExpression(/*slots=*/1);
2025 return true;
2026 }
2027
2028 bool Generator::writeIfStatement(const IfStatement& i) {
2029 // If the test condition is known to be uniform, we can skip over the untrue portion entirely.
2030 if (Analysis::IsDynamicallyUniformExpression(*i.test())) {
2031 return this->writeDynamicallyUniformIfStatement(i);
2032 }
2033
2034 // Save the current condition-mask.
2035 fBuilder.enableExecutionMaskWrites();
2036 fBuilder.push_condition_mask();
2037
2038 // Push the test condition mask.
2039 if (!this->pushExpression(*i.test())) {
2040 return unsupported();
2041 }
2042
2043 // Merge the current condition-mask with the test condition, then run the if-true branch.
2044 fBuilder.merge_condition_mask();
2045 if (!this->writeStatement(*i.ifTrue())) {
2046 return unsupported();
2047 }
2048
2049 if (i.ifFalse()) {
2050 // Apply the inverse condition-mask. Then run the if-false branch.
2051 fBuilder.merge_inv_condition_mask();
2052 if (!this->writeStatement(*i.ifFalse())) {
2053 return unsupported();
2054 }
2055 }
2056
2057 // Jettison the test-expression, and restore the the condition-mask.
2058 this->discardExpression(/*slots=*/1);
2059 fBuilder.pop_condition_mask();
2060 fBuilder.disableExecutionMaskWrites();
2061
2062 return true;
2063 }
2064
2065 bool Generator::writeReturnStatement(const ReturnStatement& r) {
2066 if (r.expression()) {
2067 if (!this->pushExpression(*r.expression())) {
2068 return unsupported();
2069 }
2070 if (this->needsFunctionResultSlots(fCurrentFunction)) {
2071 this->popToSlotRange(fCurrentFunctionResult);
2072 }
2073 }
2074 if (fBuilder.executionMaskWritesAreEnabled() && this->needsReturnMask(fCurrentFunction)) {
2075 fBuilder.mask_off_return_mask();
2076 }
2077 return true;
2078 }
2079
2080 bool Generator::writeSwitchStatement(const SwitchStatement& s) {
2081 const StatementArray& cases = s.cases();
2082 SkASSERT(std::all_of(cases.begin(), cases.end(), [](const std::unique_ptr<Statement>& stmt) {
2083 return stmt->is<SwitchCase>();
2084 }));
2085
2086 // Set up a break target.
2087 AutoLoopTarget breakTarget(this, &fCurrentBreakTarget);
2088
2089 // Save off the original loop mask.
2090 fBuilder.enableExecutionMaskWrites();
2091 fBuilder.push_loop_mask();
2092
2093 // Push the switch-case value, and write a default-mask that enables every lane which already
2094 // has an active loop mask. As we match cases, the default mask will get pared down.
2095 if (!this->pushExpression(*s.value())) {
2096 return unsupported();
2097 }
2098 fBuilder.push_loop_mask();
2099
2100 // Zero out the loop mask; each case op will re-enable it as we go.
2101 fBuilder.mask_off_loop_mask();
2102
2103 // Write each switch-case.
2104 bool foundDefaultCase = false;
2105 for (const std::unique_ptr<Statement>& stmt : cases) {
2106 int skipLabelID = fBuilder.nextLabelID();
2107
2108 const SwitchCase& sc = stmt->as<SwitchCase>();
2109 if (sc.isDefault()) {
2110 foundDefaultCase = true;
2111 if (stmt.get() != cases.back().get()) {
2112 // We only support a default case when it is the very last case. If that changes,
2113 // this logic will need to be updated.
2114 return unsupported();
2115 }
2116 // Keep whatever lanes are executing now, and also enable any lanes in the default mask.
2117 fBuilder.pop_and_reenable_loop_mask();
2118 // Execute the switch-case block, if any lanes are alive to see it.
2119 fBuilder.branch_if_no_lanes_active(skipLabelID);
2120 if (!this->writeStatement(*sc.statement())) {
2121 return unsupported();
2122 }
2123 } else {
2124 // The case-op will enable the loop mask if the switch-value matches, and mask off lanes
2125 // from the default-mask.
2126 fBuilder.case_op(sc.value());
2127 // Execute the switch-case block, if any lanes are alive to see it.
2128 fBuilder.branch_if_no_lanes_active(skipLabelID);
2129 if (!this->writeStatement(*sc.statement())) {
2130 return unsupported();
2131 }
2132 }
2133 fBuilder.label(skipLabelID);
2134 }
2135
2136 // Jettison the switch value, and the default case mask if it was never consumed above.
2137 this->discardExpression(/*slots=*/foundDefaultCase ? 1 : 2);
2138
2139 // If we hit a break statement on all lanes, we will branch here to escape from the switch.
2140 fBuilder.label(breakTarget.labelID());
2141
2142 // Restore the loop mask.
2143 fBuilder.pop_loop_mask();
2144 fBuilder.disableExecutionMaskWrites();
2145 return true;
2146 }
2147
2148 bool Generator::writeImmutableVarDeclaration(const VarDeclaration& d) {
2149 // In a debugging session, we expect debug traces for a variable declaration to appear, even if
2150 // it's constant, so we don't use immutable slots for variables when tracing is on.
2151 if (this->shouldWriteTraceOps()) {
2152 return false;
2153 }
2154
2155 // Find the constant value for this variable.
2156 const Expression* initialValue = ConstantFolder::GetConstantValueForVariable(*d.value());
2157 SkASSERT(initialValue);
2158
2159 // For a variable to be immutable, it cannot be written-to besides its initial declaration.
2160 ProgramUsage::VariableCounts counts = fProgram.fUsage->get(*d.var());
2161 if (counts.fWrite != 1) {
2162 return false;
2163 }
2164
2165 STArray<16, ImmutableBits> immutableValues;
2166 if (!this->getImmutableValueForExpression(*initialValue, &immutableValues)) {
2167 return false;
2168 }
2169
2170 fImmutableVariables.add(d.var());
2171
2172 std::optional<SlotRange> preexistingSlots = this->findPreexistingImmutableData(immutableValues);
2173 if (preexistingSlots.has_value()) {
2174 // Associate this variable with a preexisting range of immutable data (no new data or code).
2175 fImmutableSlots.mapVariableToSlots(*d.var(), *preexistingSlots);
2176 } else {
2177 // Write out the constant value back to immutable slots. (This generates data, but no
2178 // runtime code.)
2179 SlotRange slots = this->getImmutableSlots(*d.var());
2180 this->storeImmutableValueToSlots(immutableValues, slots);
2181 }
2182
2183 return true;
2184 }
2185
2186 bool Generator::writeVarDeclaration(const VarDeclaration& v) {
2187 if (v.value()) {
2188 // If a variable never actually changes, we can make it immutable.
2189 if (this->writeImmutableVarDeclaration(v)) {
2190 return true;
2191 }
2192 // This is a real variable which can change over the course of execution.
2193 if (!this->pushExpression(*v.value())) {
2194 return unsupported();
2195 }
2196 this->popToSlotRangeUnmasked(this->getVariableSlots(*v.var()));
2197 } else {
2198 this->zeroSlotRangeUnmasked(this->getVariableSlots(*v.var()));
2199 }
2200 return true;
2201 }
2202
2203 bool Generator::pushExpression(const Expression& e, bool usesResult) {
2204 switch (e.kind()) {
2205 case Expression::Kind::kBinary:
2206 return this->pushBinaryExpression(e.as<BinaryExpression>());
2207
2208 case Expression::Kind::kChildCall:
2209 return this->pushChildCall(e.as<ChildCall>());
2210
2211 case Expression::Kind::kConstructorArray:
2212 case Expression::Kind::kConstructorArrayCast:
2213 case Expression::Kind::kConstructorCompound:
2214 case Expression::Kind::kConstructorStruct:
2215 return this->pushConstructorCompound(e.asAnyConstructor());
2216
2217 case Expression::Kind::kConstructorCompoundCast:
2218 case Expression::Kind::kConstructorScalarCast:
2219 return this->pushConstructorCast(e.asAnyConstructor());
2220
2221 case Expression::Kind::kConstructorDiagonalMatrix:
2222 return this->pushConstructorDiagonalMatrix(e.as<ConstructorDiagonalMatrix>());
2223
2224 case Expression::Kind::kConstructorMatrixResize:
2225 return this->pushConstructorMatrixResize(e.as<ConstructorMatrixResize>());
2226
2227 case Expression::Kind::kConstructorSplat:
2228 return this->pushConstructorSplat(e.as<ConstructorSplat>());
2229
2230 case Expression::Kind::kEmpty:
2231 return true;
2232
2233 case Expression::Kind::kFieldAccess:
2234 return this->pushFieldAccess(e.as<FieldAccess>());
2235
2236 case Expression::Kind::kFunctionCall:
2237 return this->pushFunctionCall(e.as<FunctionCall>());
2238
2239 case Expression::Kind::kIndex:
2240 return this->pushIndexExpression(e.as<IndexExpression>());
2241
2242 case Expression::Kind::kLiteral:
2243 return this->pushLiteral(e.as<Literal>());
2244
2245 case Expression::Kind::kPrefix:
2246 return this->pushPrefixExpression(e.as<PrefixExpression>());
2247
2248 case Expression::Kind::kPostfix:
2249 return this->pushPostfixExpression(e.as<PostfixExpression>(), usesResult);
2250
2251 case Expression::Kind::kSwizzle:
2252 return this->pushSwizzle(e.as<Swizzle>());
2253
2254 case Expression::Kind::kTernary:
2255 return this->pushTernaryExpression(e.as<TernaryExpression>());
2256
2257 case Expression::Kind::kVariableReference:
2258 return this->pushVariableReference(e.as<VariableReference>());
2259
2260 default:
2261 return unsupported();
2262 }
2263 }
2264
2265 BuilderOp Generator::GetTypedOp(const SkSL::Type& type, const TypedOps& ops) {
2266 switch (type.componentType().numberKind()) {
2267 case Type::NumberKind::kFloat: return ops.fFloatOp;
2268 case Type::NumberKind::kSigned: return ops.fSignedOp;
2269 case Type::NumberKind::kUnsigned: return ops.fUnsignedOp;
2270 case Type::NumberKind::kBoolean: return ops.fBooleanOp;
2271 default: return BuilderOp::unsupported;
2272 }
2273 }
2274
2275 bool Generator::unaryOp(const SkSL::Type& type, const TypedOps& ops) {
2276 BuilderOp op = GetTypedOp(type, ops);
2277 if (op == BuilderOp::unsupported) {
2278 return unsupported();
2279 }
2280 fBuilder.unary_op(op, type.slotCount());
2281 return true;
2282 }
2283
2284 bool Generator::binaryOp(const SkSL::Type& type, const TypedOps& ops) {
2285 BuilderOp op = GetTypedOp(type, ops);
2286 if (op == BuilderOp::unsupported) {
2287 return unsupported();
2288 }
2289 fBuilder.binary_op(op, type.slotCount());
2290 return true;
2291 }
2292
2293 bool Generator::ternaryOp(const SkSL::Type& type, const TypedOps& ops) {
2294 BuilderOp op = GetTypedOp(type, ops);
2295 if (op == BuilderOp::unsupported) {
2296 return unsupported();
2297 }
2298 fBuilder.ternary_op(op, type.slotCount());
2299 return true;
2300 }
2301
2302 void Generator::foldWithMultiOp(BuilderOp op, int elements) {
2303 // Fold the top N elements on the stack using an op that supports multiple slots, e.g.:
2304 // (A + B + C + D) -> add_2_floats $0..1 += $2..3
2305 // add_float $0 += $1
2306 for (; elements >= 8; elements -= 4) {
2307 fBuilder.binary_op(op, /*slots=*/4);
2308 }
2309 for (; elements >= 6; elements -= 3) {
2310 fBuilder.binary_op(op, /*slots=*/3);
2311 }
2312 for (; elements >= 4; elements -= 2) {
2313 fBuilder.binary_op(op, /*slots=*/2);
2314 }
2315 for (; elements >= 2; elements -= 1) {
2316 fBuilder.binary_op(op, /*slots=*/1);
2317 }
2318 }
2319
2320 bool Generator::pushLValueOrExpression(LValue* lvalue, const Expression& expr) {
2321 return lvalue ? this->push(*lvalue)
2322 : this->pushExpression(expr);
2323 }
2324
2325 bool Generator::pushMatrixMultiply(LValue* lvalue,
2326 const Expression& left,
2327 const Expression& right,
2328 int leftColumns,
2329 int leftRows,
2330 int rightColumns,
2331 int rightRows) {
2332 SkASSERT(left.type().isMatrix() || left.type().isVector());
2333 SkASSERT(right.type().isMatrix() || right.type().isVector());
2334
2335 // Insert padding space on the stack to hold the result.
2336 fBuilder.pad_stack(rightColumns * leftRows);
2337
2338 // Push the left and right matrices onto the stack.
2339 if (!this->pushLValueOrExpression(lvalue, left) || !this->pushExpression(right)) {
2340 return unsupported();
2341 }
2342
2343 fBuilder.matrix_multiply(leftColumns, leftRows, rightColumns, rightRows);
2344
2345 // If this multiply was actually an assignment (via *=), write the result back to the lvalue.
2346 return lvalue ? this->store(*lvalue)
2347 : true;
2348 }
2349
2350 void Generator::foldComparisonOp(Operator op, int elements) {
2351 switch (op.kind()) {
2352 case OperatorKind::EQEQ:
2353 // equal(x,y) returns a vector; use & to fold into a scalar.
2354 this->foldWithMultiOp(BuilderOp::bitwise_and_n_ints, elements);
2355 break;
2356
2357 case OperatorKind::NEQ:
2358 // notEqual(x,y) returns a vector; use | to fold into a scalar.
2359 this->foldWithMultiOp(BuilderOp::bitwise_or_n_ints, elements);
2360 break;
2361
2362 default:
2363 SkDEBUGFAIL("comparison only allows == and !=");
2364 break;
2365 }
2366 }
2367
2368 bool Generator::pushStructuredComparison(LValue* left,
2369 Operator op,
2370 LValue* right,
2371 const Type& type) {
2372 if (type.isStruct()) {
2373 // Compare every field in the struct.
2374 SkSpan<const Field> fields = type.fields();
2375 int currentSlot = 0;
2376 for (size_t index = 0; index < fields.size(); ++index) {
2377 const Type& fieldType = *fields[index].fType;
2378 const int fieldSlotCount = fieldType.slotCount();
2379 UnownedLValueSlice fieldLeft {left, currentSlot, fieldSlotCount};
2380 UnownedLValueSlice fieldRight{right, currentSlot, fieldSlotCount};
2381 if (!this->pushStructuredComparison(&fieldLeft, op, &fieldRight, fieldType)) {
2382 return unsupported();
2383 }
2384 currentSlot += fieldSlotCount;
2385 }
2386
2387 this->foldComparisonOp(op, fields.size());
2388 return true;
2389 }
2390
2391 if (type.isArray()) {
2392 const Type& indexedType = type.componentType();
2393 if (indexedType.numberKind() == Type::NumberKind::kNonnumeric) {
2394 // Compare every element in the array.
2395 const int indexedSlotCount = indexedType.slotCount();
2396 int currentSlot = 0;
2397 for (int index = 0; index < type.columns(); ++index) {
2398 UnownedLValueSlice indexedLeft {left, currentSlot, indexedSlotCount};
2399 UnownedLValueSlice indexedRight{right, currentSlot, indexedSlotCount};
2400 if (!this->pushStructuredComparison(&indexedLeft, op, &indexedRight, indexedType)) {
2401 return unsupported();
2402 }
2403 currentSlot += indexedSlotCount;
2404 }
2405
2406 this->foldComparisonOp(op, type.columns());
2407 return true;
2408 }
2409 }
2410
2411 // We've winnowed down to a single element, or an array of homogeneous numeric elements.
2412 // Push the elements onto the stack, then compare them.
2413 if (!this->push(*left) || !this->push(*right)) {
2414 return unsupported();
2415 }
2416 switch (op.kind()) {
2417 case OperatorKind::EQEQ:
2418 if (!this->binaryOp(type, kEqualOps)) {
2419 return unsupported();
2420 }
2421 break;
2422
2423 case OperatorKind::NEQ:
2424 if (!this->binaryOp(type, kNotEqualOps)) {
2425 return unsupported();
2426 }
2427 break;
2428
2429 default:
2430 SkDEBUGFAIL("comparison only allows == and !=");
2431 break;
2432 }
2433
2434 this->foldComparisonOp(op, type.slotCount());
2435 return true;
2436 }
2437
2438 bool Generator::pushBinaryExpression(const BinaryExpression& e) {
2439 return this->pushBinaryExpression(*e.left(), e.getOperator(), *e.right());
2440 }
2441
2442 bool Generator::pushBinaryExpression(const Expression& left, Operator op, const Expression& right) {
2443 switch (op.kind()) {
2444 // Rewrite greater-than ops as their less-than equivalents.
2445 case OperatorKind::GT:
2446 return this->pushBinaryExpression(right, OperatorKind::LT, left);
2447
2448 case OperatorKind::GTEQ:
2449 return this->pushBinaryExpression(right, OperatorKind::LTEQ, left);
2450
2451 // Handle struct and array comparisons.
2452 case OperatorKind::EQEQ:
2453 case OperatorKind::NEQ:
2454 if (left.type().isStruct() || left.type().isArray()) {
2455 SkASSERT(left.type().matches(right.type()));
2456 std::unique_ptr<LValue> lvLeft = this->makeLValue(left, /*allowScratch=*/true);
2457 std::unique_ptr<LValue> lvRight = this->makeLValue(right, /*allowScratch=*/true);
2458 return this->pushStructuredComparison(lvLeft.get(), op, lvRight.get(), left.type());
2459 }
2460 [[fallthrough]];
2461
2462 // Rewrite commutative ops so that the literal is on the right-hand side. This gives the
2463 // Builder more opportunities to use immediate-mode ops.
2464 case OperatorKind::PLUS:
2465 case OperatorKind::STAR:
2466 case OperatorKind::BITWISEAND:
2467 case OperatorKind::BITWISEXOR:
2468 case OperatorKind::LOGICALXOR: {
2469 double unused;
2470 if (ConstantFolder::GetConstantValue(left, &unused) &&
2471 !ConstantFolder::GetConstantValue(right, &unused)) {
2472 return this->pushBinaryExpression(right, op, left);
2473 }
2474 break;
2475 }
2476 // Emit comma expressions.
2477 case OperatorKind::COMMA:
2478 if (Analysis::HasSideEffects(left)) {
2479 if (!this->pushExpression(left, /*usesResult=*/false)) {
2480 return unsupported();
2481 }
2482 this->discardExpression(left.type().slotCount());
2483 }
2484 return this->pushExpression(right);
2485
2486 default:
2487 break;
2488 }
2489
2490 // Handle binary expressions with mismatched types.
2491 bool vectorizeLeft = false, vectorizeRight = false;
2492 if (!left.type().matches(right.type())) {
2493 if (left.type().componentType().numberKind() != right.type().componentType().numberKind()) {
2494 return unsupported();
2495 }
2496 if (left.type().isScalar() && (right.type().isVector() || right.type().isMatrix())) {
2497 vectorizeLeft = true;
2498 } else if ((left.type().isVector() || left.type().isMatrix()) && right.type().isScalar()) {
2499 vectorizeRight = true;
2500 }
2501 }
2502
2503 const Type& type = vectorizeLeft ? right.type() : left.type();
2504
2505 // If this is an assignment...
2506 std::unique_ptr<LValue> lvalue;
2507 if (op.isAssignment()) {
2508 // ... turn the left side into an lvalue.
2509 lvalue = this->makeLValue(left);
2510 if (!lvalue) {
2511 return unsupported();
2512 }
2513
2514 // Handle simple assignment (`var = expr`).
2515 if (op.kind() == OperatorKind::EQ) {
2516 return this->pushExpression(right) &&
2517 this->store(*lvalue);
2518 }
2519
2520 // Strip off the assignment from the op (turning += into +).
2521 op = op.removeAssignment();
2522 }
2523
2524 // Handle matrix multiplication (MxM/MxV/VxM).
2525 if (op.kind() == OperatorKind::STAR) {
2526 // Matrix * matrix:
2527 if (left.type().isMatrix() && right.type().isMatrix()) {
2528 return this->pushMatrixMultiply(lvalue.get(), left, right,
2529 left.type().columns(), left.type().rows(),
2530 right.type().columns(), right.type().rows());
2531 }
2532
2533 // Vector * matrix:
2534 if (left.type().isVector() && right.type().isMatrix()) {
2535 return this->pushMatrixMultiply(lvalue.get(), left, right,
2536 left.type().columns(), 1,
2537 right.type().columns(), right.type().rows());
2538 }
2539
2540 // Matrix * vector:
2541 if (left.type().isMatrix() && right.type().isVector()) {
2542 return this->pushMatrixMultiply(lvalue.get(), left, right,
2543 left.type().columns(), left.type().rows(),
2544 1, right.type().columns());
2545 }
2546 }
2547
2548 if (!vectorizeLeft && !vectorizeRight && !type.matches(right.type())) {
2549 // We have mismatched types but don't know how to handle them.
2550 return unsupported();
2551 }
2552
2553 // Handle binary ops which require short-circuiting.
2554 switch (op.kind()) {
2555 case OperatorKind::LOGICALAND:
2556 if (Analysis::HasSideEffects(right)) {
2557 // If the RHS has side effects, we rewrite `a && b` as `a ? b : false`. This
2558 // generates pretty solid code and gives us the required short-circuit behavior.
2559 SkASSERT(!op.isAssignment());
2560 SkASSERT(type.componentType().isBoolean());
2561 SkASSERT(type.slotCount() == 1); // operator&& only works with scalar types
2562 Literal falseLiteral{Position{}, 0.0, &right.type()};
2563 return this->pushTernaryExpression(left, right, falseLiteral);
2564 }
2565 break;
2566
2567 case OperatorKind::LOGICALOR:
2568 if (Analysis::HasSideEffects(right)) {
2569 // If the RHS has side effects, we rewrite `a || b` as `a ? true : b`.
2570 SkASSERT(!op.isAssignment());
2571 SkASSERT(type.componentType().isBoolean());
2572 SkASSERT(type.slotCount() == 1); // operator|| only works with scalar types
2573 Literal trueLiteral{Position{}, 1.0, &right.type()};
2574 return this->pushTernaryExpression(left, trueLiteral, right);
2575 }
2576 break;
2577
2578 default:
2579 break;
2580 }
2581
2582 // Push the left- and right-expressions onto the stack.
2583 if (!this->pushLValueOrExpression(lvalue.get(), left)) {
2584 return unsupported();
2585 }
2586 if (vectorizeLeft) {
2587 fBuilder.push_duplicates(right.type().slotCount() - 1);
2588 }
2589 if (!this->pushExpression(right)) {
2590 return unsupported();
2591 }
2592 if (vectorizeRight) {
2593 fBuilder.push_duplicates(left.type().slotCount() - 1);
2594 }
2595
2596 switch (op.kind()) {
2597 case OperatorKind::PLUS:
2598 if (!this->binaryOp(type, kAddOps)) {
2599 return unsupported();
2600 }
2601 break;
2602
2603 case OperatorKind::MINUS:
2604 if (!this->binaryOp(type, kSubtractOps)) {
2605 return unsupported();
2606 }
2607 break;
2608
2609 case OperatorKind::STAR:
2610 if (!this->binaryOp(type, kMultiplyOps)) {
2611 return unsupported();
2612 }
2613 break;
2614
2615 case OperatorKind::SLASH:
2616 if (!this->binaryOp(type, kDivideOps)) {
2617 return unsupported();
2618 }
2619 break;
2620
2621 case OperatorKind::LT:
2622 case OperatorKind::GT:
2623 if (!this->binaryOp(type, kLessThanOps)) {
2624 return unsupported();
2625 }
2626 SkASSERT(type.slotCount() == 1); // operator< only works with scalar types
2627 break;
2628
2629 case OperatorKind::LTEQ:
2630 case OperatorKind::GTEQ:
2631 if (!this->binaryOp(type, kLessThanEqualOps)) {
2632 return unsupported();
2633 }
2634 SkASSERT(type.slotCount() == 1); // operator<= only works with scalar types
2635 break;
2636
2637 case OperatorKind::EQEQ:
2638 if (!this->binaryOp(type, kEqualOps)) {
2639 return unsupported();
2640 }
2641 this->foldComparisonOp(op, type.slotCount());
2642 break;
2643
2644 case OperatorKind::NEQ:
2645 if (!this->binaryOp(type, kNotEqualOps)) {
2646 return unsupported();
2647 }
2648 this->foldComparisonOp(op, type.slotCount());
2649 break;
2650
2651 case OperatorKind::LOGICALAND:
2652 case OperatorKind::BITWISEAND:
2653 // For logical-and, we verified above that the RHS does not have side effects, so we
2654 // don't need to worry about short-circuiting side effects.
2655 fBuilder.binary_op(BuilderOp::bitwise_and_n_ints, type.slotCount());
2656 break;
2657
2658 case OperatorKind::LOGICALOR:
2659 case OperatorKind::BITWISEOR:
2660 // For logical-or, we verified above that the RHS does not have side effects.
2661 fBuilder.binary_op(BuilderOp::bitwise_or_n_ints, type.slotCount());
2662 break;
2663
2664 case OperatorKind::LOGICALXOR:
2665 case OperatorKind::BITWISEXOR:
2666 // Logical-xor does not short circuit.
2667 fBuilder.binary_op(BuilderOp::bitwise_xor_n_ints, type.slotCount());
2668 break;
2669
2670 default:
2671 return unsupported();
2672 }
2673
2674 // If we have an lvalue, we need to write the result back into it.
2675 return lvalue ? this->store(*lvalue)
2676 : true;
2677 }
2678
2679 std::optional<Generator::ImmutableBits> Generator::getImmutableBitsForSlot(const Expression& expr,
2680 size_t slot) {
2681 // Determine the constant-value of the slot; bail if it isn't constant.
2682 std::optional<double> v = expr.getConstantValue(slot);
2683 if (!v.has_value()) {
2684 return std::nullopt;
2685 }
2686 // Determine the number-kind of the slot, and convert the value to its bit-representation.
2687 Type::NumberKind kind = expr.type().slotType(slot).numberKind();
2688 double value = *v;
2689 switch (kind) {
2690 case Type::NumberKind::kFloat:
2691 return sk_bit_cast<ImmutableBits>((float)value);
2692
2693 case Type::NumberKind::kSigned:
2694 return sk_bit_cast<ImmutableBits>((int32_t)value);
2695
2696 case Type::NumberKind::kUnsigned:
2697 return sk_bit_cast<ImmutableBits>((uint32_t)value);
2698
2699 case Type::NumberKind::kBoolean:
2700 return value ? ~0 : 0;
2701
2702 default:
2703 return std::nullopt;
2704 }
2705 }
2706
2707 bool Generator::getImmutableValueForExpression(const Expression& expr,
2708 TArray<ImmutableBits>* immutableValues) {
2709 if (!expr.supportsConstantValues()) {
2710 return false;
2711 }
2712 size_t numSlots = expr.type().slotCount();
2713 immutableValues->reserve_exact(numSlots);
2714 for (size_t index = 0; index < numSlots; ++index) {
2715 std::optional<ImmutableBits> bits = this->getImmutableBitsForSlot(expr, index);
2716 if (!bits.has_value()) {
2717 return false;
2718 }
2719 immutableValues->push_back(*bits);
2720 }
2721 return true;
2722 }
2723
2724 void Generator::storeImmutableValueToSlots(const TArray<ImmutableBits>& immutableValues,
2725 SlotRange slots) {
2726 for (int index = 0; index < slots.count; ++index) {
2727 // Store the immutable value in its slot.
2728 const Slot slot = slots.index++;
2729 const ImmutableBits bits = immutableValues[index];
2730 fBuilder.store_immutable_value_i(slot, bits);
2731
2732 // Keep track of every stored immutable value for potential later reuse.
2733 fImmutableSlotMap[bits].add(slot);
2734 }
2735 }
2736
2737 std::optional<SlotRange> Generator::findPreexistingImmutableData(
2738 const TArray<ImmutableBits>& immutableValues) {
2739 STArray<16, const THashSet<Slot>*> slotArray;
2740 slotArray.reserve_exact(immutableValues.size());
2741
2742 // Find all the slots associated with each immutable-value bit representation.
2743 // If a given bit-pattern doesn't exist anywhere in our program yet, we can stop searching.
2744 for (const ImmutableBits& immutableValue : immutableValues) {
2745 const THashSet<Slot>* slotsForValue = fImmutableSlotMap.find(immutableValue);
2746 if (!slotsForValue) {
2747 return std::nullopt;
2748 }
2749 slotArray.push_back(slotsForValue);
2750 }
2751
2752 // Look for the group with the fewest number of entries, since that can be searched in the
2753 // least amount of effort.
2754 int leastSlotIndex = 0, leastSlotCount = INT_MAX;
2755 for (int index = 0; index < slotArray.size(); ++index) {
2756 int currentCount = slotArray[index]->count();
2757 if (currentCount < leastSlotCount) {
2758 leastSlotIndex = index;
2759 leastSlotCount = currentCount;
2760 }
2761 }
2762
2763 // See if we can reconstitute the value that we want with any of the data we've already got.
2764 for (int slot : *slotArray[leastSlotIndex]) {
2765 int firstSlot = slot - leastSlotIndex;
2766 bool found = true;
2767 for (int index = 0; index < slotArray.size(); ++index) {
2768 if (!slotArray[index]->contains(firstSlot + index)) {
2769 found = false;
2770 break;
2771 }
2772 }
2773 if (found) {
2774 // We've found an exact match for the input value; return its slot-range.
2775 return SlotRange{firstSlot, slotArray.size()};
2776 }
2777 }
2778
2779 // We didn't find any reusable slot ranges.
2780 return std::nullopt;
2781 }
2782
2783 bool Generator::pushImmutableData(const Expression& e) {
2784 STArray<16, ImmutableBits> immutableValues;
2785 if (!this->getImmutableValueForExpression(e, &immutableValues)) {
2786 return false;
2787 }
2788 std::optional<SlotRange> preexistingData = this->findPreexistingImmutableData(immutableValues);
2789 if (preexistingData.has_value()) {
2790 fBuilder.push_immutable(*preexistingData);
2791 return true;
2792 }
2793 SlotRange range = fImmutableSlots.createSlots(e.description(),
2794 e.type(),
2795 e.fPosition,
2796 /*isFunctionReturnValue=*/false);
2797 this->storeImmutableValueToSlots(immutableValues, range);
2798 fBuilder.push_immutable(range);
2799 return true;
2800 }
2801
2802 bool Generator::pushConstructorCompound(const AnyConstructor& c) {
2803 if (c.type().slotCount() > 1 && this->pushImmutableData(c)) {
2804 return true;
2805 }
2806 for (const std::unique_ptr<Expression> &arg : c.argumentSpan()) {
2807 if (!this->pushExpression(*arg)) {
2808 return unsupported();
2809 }
2810 }
2811 return true;
2812 }
2813
2814 bool Generator::pushChildCall(const ChildCall& c) {
•2815 int* childIdxPtr = fChildEffectMap.find(&c.child());
2816 SkASSERT(childIdxPtr != nullptr);
2817 int childIdx = *childIdxPtr; // Save this in case pushExpression changes fChildEffectMap
2818 SkASSERT(!c.arguments().empty());
2819
2820 // All child calls have at least one argument.
2821 const Expression* arg = c.arguments()[0].get();
2822 if (!this->pushExpression(*arg)) {
2823 return unsupported();
2824 }
2825
2826 // Copy arguments from the stack into src/dst as required by this particular child-call.
2827 switch (c.child().type().typeKind()) {
2828 case Type::TypeKind::kShader: {
2829 // The argument must be a float2.
2830 SkASSERT(c.arguments().size() == 1);
2831 SkASSERT(arg->type().matches(*fContext.fTypes.fFloat2));
2832
2833 // `exchange_src` will use the top four values on the stack, but we don't care what goes
2834 // into the blue/alpha components. We inject padding here to balance the stack.
2835 fBuilder.pad_stack(2);
2836
2837 // Move the argument into src.rgba while also preserving the execution mask.
2838 fBuilder.exchange_src();
•2839 fBuilder.invoke_shader(childIdx);
2840 break;
2841 }
2842 case Type::TypeKind::kColorFilter: {
2843 // The argument must be a half4/float4.
2844 SkASSERT(c.arguments().size() == 1);
2845 SkASSERT(arg->type().matches(*fContext.fTypes.fHalf4) ||
2846 arg->type().matches(*fContext.fTypes.fFloat4));
2847
2848 // Move the argument into src.rgba while also preserving the execution mask.
2849 fBuilder.exchange_src();
•2850 fBuilder.invoke_color_filter(childIdx);
2851 break;
2852 }
2853 case Type::TypeKind::kBlender: {
2854 // Both arguments must be half4/float4.
2855 SkASSERT(c.arguments().size() == 2);
2856 SkASSERT(c.arguments()[0]->type().matches(*fContext.fTypes.fHalf4) ||
2857 c.arguments()[0]->type().matches(*fContext.fTypes.fFloat4));
2858 SkASSERT(c.arguments()[1]->type().matches(*fContext.fTypes.fHalf4) ||
2859 c.arguments()[1]->type().matches(*fContext.fTypes.fFloat4));
2860
2861 // Move the second argument into dst.rgba, and the first argument into src.rgba, while
2862 // simultaneously preserving the execution mask.
2863 if (!this->pushExpression(*c.arguments()[1])) {
2864 return unsupported();
2865 }
2866 fBuilder.pop_dst_rgba();
2867 fBuilder.exchange_src();
•2868 fBuilder.invoke_blender(childIdx);
2869 break;
2870 }
2871 default: {
2872 SkDEBUGFAILF("cannot sample from type '%s'", c.child().type().description().c_str());
2873 }
2874 }
2875
2876 // The child call has returned the result color via src.rgba, and the SkRP execution mask is
2877 // on top of the stack. Swapping the two puts the result color on top of the stack, and also
2878 // restores our execution masks.
2879 fBuilder.exchange_src();
2880 return true;
2881 }
2882
2883 bool Generator::pushConstructorCast(const AnyConstructor& c) {
2884 SkASSERT(c.argumentSpan().size() == 1);
2885 const Expression& inner = *c.argumentSpan().front();
2886 SkASSERT(inner.type().slotCount() == c.type().slotCount());
2887
2888 if (!this->pushExpression(inner)) {
2889 return unsupported();
2890 }
2891 const Type::NumberKind innerKind = inner.type().componentType().numberKind();
2892 const Type::NumberKind outerKind = c.type().componentType().numberKind();
2893
2894 if (innerKind == outerKind) {
2895 // Since we ignore type precision, this cast is effectively a no-op.
2896 return true;
2897 }
2898
2899 switch (innerKind) {
2900 case Type::NumberKind::kSigned:
2901 if (outerKind == Type::NumberKind::kUnsigned) {
2902 // Treat uint(int) as a no-op.
2903 return true;
2904 }
2905 if (outerKind == Type::NumberKind::kFloat) {
2906 fBuilder.unary_op(BuilderOp::cast_to_float_from_int, c.type().slotCount());
2907 return true;
2908 }
2909 break;
2910
2911 case Type::NumberKind::kUnsigned:
2912 if (outerKind == Type::NumberKind::kSigned) {
2913 // Treat int(uint) as a no-op.
2914 return true;
2915 }
2916 if (outerKind == Type::NumberKind::kFloat) {
2917 fBuilder.unary_op(BuilderOp::cast_to_float_from_uint, c.type().slotCount());
2918 return true;
2919 }
2920 break;
2921
2922 case Type::NumberKind::kBoolean:
2923 // Converting boolean to int or float can be accomplished via bitwise-and.
2924 if (outerKind == Type::NumberKind::kFloat) {
2925 fBuilder.push_constant_f(1.0f);
2926 } else if (outerKind == Type::NumberKind::kSigned ||
2927 outerKind == Type::NumberKind::kUnsigned) {
2928 fBuilder.push_constant_i(1);
2929 } else {
2930 SkDEBUGFAILF("unexpected cast from bool to %s", c.type().description().c_str());
2931 return unsupported();
2932 }
2933 fBuilder.push_duplicates(c.type().slotCount() - 1);
2934 fBuilder.binary_op(BuilderOp::bitwise_and_n_ints, c.type().slotCount());
2935 return true;
2936
2937 case Type::NumberKind::kFloat:
2938 if (outerKind == Type::NumberKind::kSigned) {
2939 fBuilder.unary_op(BuilderOp::cast_to_int_from_float, c.type().slotCount());
2940 return true;
2941 }
2942 if (outerKind == Type::NumberKind::kUnsigned) {
2943 fBuilder.unary_op(BuilderOp::cast_to_uint_from_float, c.type().slotCount());
2944 return true;
2945 }
2946 break;
2947
2948 case Type::NumberKind::kNonnumeric:
2949 break;
2950 }
2951
2952 if (outerKind == Type::NumberKind::kBoolean) {
2953 // Converting int or float to boolean can be accomplished via `notEqual(x, 0)`.
2954 fBuilder.push_zeros(c.type().slotCount());
2955 return this->binaryOp(inner.type(), kNotEqualOps);
2956 }
2957
2958 SkDEBUGFAILF("unexpected cast from %s to %s",
2959 c.type().description().c_str(), inner.type().description().c_str());
2960 return unsupported();
2961 }
2962
2963 bool Generator::pushConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c) {
2964 if (this->pushImmutableData(c)) {
2965 return true;
2966 }
2967 fBuilder.push_zeros(1);
2968 if (!this->pushExpression(*c.argument())) {
2969 return unsupported();
2970 }
2971 fBuilder.diagonal_matrix(c.type().columns(), c.type().rows());
2972
2973 return true;
2974 }
2975
2976 bool Generator::pushConstructorMatrixResize(const ConstructorMatrixResize& c) {
2977 if (!this->pushExpression(*c.argument())) {
2978 return unsupported();
2979 }
2980 fBuilder.matrix_resize(c.argument()->type().columns(),
2981 c.argument()->type().rows(),
2982 c.type().columns(),
2983 c.type().rows());
2984 return true;
2985 }
2986
2987 bool Generator::pushConstructorSplat(const ConstructorSplat& c) {
2988 if (!this->pushExpression(*c.argument())) {
2989 return unsupported();
2990 }
2991 fBuilder.push_duplicates(c.type().slotCount() - 1);
2992 return true;
2993 }
2994
2995 bool Generator::pushFieldAccess(const FieldAccess& f) {
2996 // If possible, get direct field access via the lvalue.
2997 std::unique_ptr<LValue> lvalue = this->makeLValue(f, /*allowScratch=*/true);
2998 return lvalue && this->push(*lvalue);
2999 }
3000
3001 bool Generator::pushFunctionCall(const FunctionCall& c) {
3002 if (c.function().isIntrinsic()) {
3003 return this->pushIntrinsic(c);
3004 }
3005
3006 // Keep track of the current function.
3007 const FunctionDefinition* lastFunction = fCurrentFunction;
3008 fCurrentFunction = c.function().definition();
3009
3010 // Skip over the function body entirely if there are no active lanes.
3011 // (If the function call was trivial, it would likely have been inlined in the frontend, so we
3012 // assume here that function calls generally represent a significant amount of work.)
3013 int skipLabelID = fBuilder.nextLabelID();
3014 fBuilder.branch_if_no_lanes_active(skipLabelID);
3015
3016 // Emit the function body.
3017 std::optional<SlotRange> r = this->writeFunction(c, *fCurrentFunction, c.arguments());
3018 if (!r.has_value()) {
3019 return unsupported();
3020 }
3021
3022 // If the function uses result slots, move its result from slots onto the stack.
3023 if (this->needsFunctionResultSlots(fCurrentFunction)) {
3024 fBuilder.push_slots(*r);
3025 }
3026
3027 // We've returned back to the last function.
3028 fCurrentFunction = lastFunction;
3029
3030 // Copy the function result from its slots onto the stack.
3031 fBuilder.label(skipLabelID);
3032 return true;
3033 }
3034
3035 bool Generator::pushIndexExpression(const IndexExpression& i) {
3036 std::unique_ptr<LValue> lvalue = this->makeLValue(i, /*allowScratch=*/true);
3037 return lvalue && this->push(*lvalue);
3038 }
3039
3040 bool Generator::pushIntrinsic(const FunctionCall& c) {
3041 const ExpressionArray& args = c.arguments();
3042 switch (args.size()) {
3043 case 1:
3044 return this->pushIntrinsic(c.function().intrinsicKind(), *args[0]);
3045
3046 case 2:
3047 return this->pushIntrinsic(c.function().intrinsicKind(), *args[0], *args[1]);
3048
3049 case 3:
3050 return this->pushIntrinsic(c.function().intrinsicKind(), *args[0], *args[1], *args[2]);
3051
3052 default:
3053 break;
3054 }
3055
3056 return unsupported();
3057 }
3058
3059 bool Generator::pushLengthIntrinsic(int slotCount) {
3060 if (slotCount == 1) {
3061 // `length(scalar)` is `sqrt(x^2)`, which is equivalent to `abs(x)`.
3062 return this->pushAbsFloatIntrinsic(/*slots=*/1);
3063 }
3064 // Implement `length(vec)` as `sqrt(dot(x, x))`.
3065 fBuilder.push_clone(slotCount);
3066 fBuilder.dot_floats(slotCount);
3067 fBuilder.unary_op(BuilderOp::sqrt_float, 1);
3068 return true;
3069 }
3070
3071 bool Generator::pushAbsFloatIntrinsic(int slots) {
3072 // Perform abs(float) by masking off the sign bit.
3073 fBuilder.push_constant_u(0x7FFFFFFF, slots);
3074 fBuilder.binary_op(BuilderOp::bitwise_and_n_ints, slots);
3075 return true;
3076 }
3077
3078 bool Generator::pushVectorizedExpression(const Expression& expr, const Type& vectorType) {
3079 if (!this->pushExpression(expr)) {
3080 return unsupported();
3081 }
3082 if (vectorType.slotCount() > expr.type().slotCount()) {
3083 SkASSERT(expr.type().slotCount() == 1);
3084 fBuilder.push_duplicates(vectorType.slotCount() - expr.type().slotCount());
3085 }
3086 return true;
3087 }
3088
3089 bool Generator::pushIntrinsic(const TypedOps& ops, const Expression& arg0) {
3090 if (!this->pushExpression(arg0)) {
3091 return unsupported();
3092 }
3093 return this->unaryOp(arg0.type(), ops);
3094 }
3095
3096 bool Generator::pushIntrinsic(BuilderOp builderOp, const Expression& arg0) {
3097 if (!this->pushExpression(arg0)) {
3098 return unsupported();
3099 }
3100 fBuilder.unary_op(builderOp, arg0.type().slotCount());
3101 return true;
3102 }
3103
3104 bool Generator::pushIntrinsic(IntrinsicKind intrinsic, const Expression& arg0) {
3105 switch (intrinsic) {
3106 case IntrinsicKind::k_abs_IntrinsicKind:
3107 if (arg0.type().componentType().isFloat()) {
3108 // Perform abs(float) by masking off the sign bit.
3109 if (!this->pushExpression(arg0)) {
3110 return unsupported();
3111 }
3112 return this->pushAbsFloatIntrinsic(arg0.type().slotCount());
3113 }
3114 // We have a dedicated op for abs(int).
3115 return this->pushIntrinsic(BuilderOp::abs_int, arg0);
3116
3117 case IntrinsicKind::k_any_IntrinsicKind:
3118 if (!this->pushExpression(arg0)) {
3119 return unsupported();
3120 }
3121 this->foldWithMultiOp(BuilderOp::bitwise_or_n_ints, arg0.type().slotCount());
3122 return true;
3123
3124 case IntrinsicKind::k_all_IntrinsicKind:
3125 if (!this->pushExpression(arg0)) {
3126 return unsupported();
3127 }
3128 this->foldWithMultiOp(BuilderOp::bitwise_and_n_ints, arg0.type().slotCount());
3129 return true;
3130
3131 case IntrinsicKind::k_acos_IntrinsicKind:
3132 return this->pushIntrinsic(BuilderOp::acos_float, arg0);
3133
3134 case IntrinsicKind::k_asin_IntrinsicKind:
3135 return this->pushIntrinsic(BuilderOp::asin_float, arg0);
3136
3137 case IntrinsicKind::k_atan_IntrinsicKind:
3138 return this->pushIntrinsic(BuilderOp::atan_float, arg0);
3139
3140 case IntrinsicKind::k_ceil_IntrinsicKind:
3141 return this->pushIntrinsic(BuilderOp::ceil_float, arg0);
3142
3143 case IntrinsicKind::k_cos_IntrinsicKind:
3144 return this->pushIntrinsic(BuilderOp::cos_float, arg0);
3145
3146 case IntrinsicKind::k_degrees_IntrinsicKind: {
3147 Literal lit180OverPi{Position{}, 57.2957795131f, &arg0.type().componentType()};
3148 return this->pushBinaryExpression(arg0, OperatorKind::STAR, lit180OverPi);
3149 }
3150 case IntrinsicKind::k_floatBitsToInt_IntrinsicKind:
3151 case IntrinsicKind::k_floatBitsToUint_IntrinsicKind:
3152 case IntrinsicKind::k_intBitsToFloat_IntrinsicKind:
3153 case IntrinsicKind::k_uintBitsToFloat_IntrinsicKind:
3154 return this->pushExpression(arg0);
3155
3156 case IntrinsicKind::k_exp_IntrinsicKind:
3157 return this->pushIntrinsic(BuilderOp::exp_float, arg0);
3158
3159 case IntrinsicKind::k_exp2_IntrinsicKind:
3160 return this->pushIntrinsic(BuilderOp::exp2_float, arg0);
3161
3162 case IntrinsicKind::k_floor_IntrinsicKind:
3163 return this->pushIntrinsic(BuilderOp::floor_float, arg0);
3164
3165 case IntrinsicKind::k_fract_IntrinsicKind:
3166 // Implement fract as `x - floor(x)`.
3167 if (!this->pushExpression(arg0)) {
3168 return unsupported();
3169 }
3170 fBuilder.push_clone(arg0.type().slotCount());
3171 fBuilder.unary_op(BuilderOp::floor_float, arg0.type().slotCount());
3172 return this->binaryOp(arg0.type(), kSubtractOps);
3173
3174 case IntrinsicKind::k_inverse_IntrinsicKind:
3175 SkASSERT(arg0.type().isMatrix());
3176 SkASSERT(arg0.type().rows() == arg0.type().columns());
3177 if (!this->pushExpression(arg0)) {
3178 return unsupported();
3179 }
3180 fBuilder.inverse_matrix(arg0.type().rows());
3181 return true;
3182
3183 case IntrinsicKind::k_inversesqrt_IntrinsicKind:
3184 return this->pushIntrinsic(kInverseSqrtOps, arg0);
3185
3186 case IntrinsicKind::k_length_IntrinsicKind:
3187 return this->pushExpression(arg0) &&
3188 this->pushLengthIntrinsic(arg0.type().slotCount());
3189
3190 case IntrinsicKind::k_log_IntrinsicKind:
3191 if (!this->pushExpression(arg0)) {
3192 return unsupported();
3193 }
3194 fBuilder.unary_op(BuilderOp::log_float, arg0.type().slotCount());
3195 return true;
3196
3197 case IntrinsicKind::k_log2_IntrinsicKind:
3198 if (!this->pushExpression(arg0)) {
3199 return unsupported();
3200 }
3201 fBuilder.unary_op(BuilderOp::log2_float, arg0.type().slotCount());
3202 return true;
3203
3204 case IntrinsicKind::k_normalize_IntrinsicKind: {
3205 // Implement normalize as `x / length(x)`. First, push the expression.
3206 if (!this->pushExpression(arg0)) {
3207 return unsupported();
3208 }
3209 int slotCount = arg0.type().slotCount();
3210 if (slotCount > 1) {
3211 #if defined(SK_USE_RSQRT_IN_RP_NORMALIZE)
3212 // Instead of `x / sqrt(dot(x, x))`, we can get roughly the same result in less time
3213 // by computing `x * invsqrt(dot(x, x))`.
3214 fBuilder.push_clone(slotCount);
3215 fBuilder.push_clone(slotCount);
3216 fBuilder.dot_floats(slotCount);
3217
3218 // Compute `vec(inversesqrt(dot(x, x)))`.
3219 fBuilder.unary_op(BuilderOp::invsqrt_float, 1);
3220 fBuilder.push_duplicates(slotCount - 1);
3221
3222 // Return `x * vec(inversesqrt(dot(x, x)))`.
3223 return this->binaryOp(arg0.type(), kMultiplyOps);
3224 #else
3225 // TODO: We can get roughly the same result in less time by using `invsqrt`, but
3226 // that leads to more variance across architectures, which Chromium layout tests do
3227 // not handle nicely.
3228 fBuilder.push_clone(slotCount);
3229 fBuilder.push_clone(slotCount);
3230 fBuilder.dot_floats(slotCount);
3231
3232 // Compute `vec(sqrt(dot(x, x)))`.
3233 fBuilder.unary_op(BuilderOp::sqrt_float, 1);
3234 fBuilder.push_duplicates(slotCount - 1);
3235
3236 // Return `x / vec(sqrt(dot(x, x)))`.
3237 return this->binaryOp(arg0.type(), kDivideOps);
3238 #endif
3239 } else {
3240 // For single-slot normalization, we can simplify `sqrt(x * x)` into `abs(x)`.
3241 fBuilder.push_clone(slotCount);
3242 return this->pushAbsFloatIntrinsic(/*slots=*/1) &&
3243 this->binaryOp(arg0.type(), kDivideOps);
3244 }
3245 }
3246 case IntrinsicKind::k_not_IntrinsicKind:
3247 return this->pushPrefixExpression(OperatorKind::LOGICALNOT, arg0);
3248
3249 case IntrinsicKind::k_radians_IntrinsicKind: {
3250 Literal litPiOver180{Position{}, 0.01745329251f, &arg0.type().componentType()};
3251 return this->pushBinaryExpression(arg0, OperatorKind::STAR, litPiOver180);
3252 }
3253 case IntrinsicKind::k_saturate_IntrinsicKind: {
3254 // Implement saturate as clamp(arg, 0, 1).
3255 Literal zeroLiteral{Position{}, 0.0, &arg0.type().componentType()};
3256 Literal oneLiteral{Position{}, 1.0, &arg0.type().componentType()};
3257 return this->pushIntrinsic(k_clamp_IntrinsicKind, arg0, zeroLiteral, oneLiteral);
3258 }
3259 case IntrinsicKind::k_sign_IntrinsicKind: {
3260 // Implement floating-point sign() as `clamp(arg * FLT_MAX, -1, 1)`.
3261 // FLT_MIN * FLT_MAX evaluates to 4, so multiplying any float value against FLT_MAX is
3262 // sufficient to ensure that |value| is always 1 or greater (excluding zero and nan).
3263 // Integer sign() doesn't need to worry about fractional values or nans, and can simply
3264 // be `clamp(arg, -1, 1)`.
3265 if (!this->pushExpression(arg0)) {
3266 return unsupported();
3267 }
3268 if (arg0.type().componentType().isFloat()) {
3269 Literal fltMaxLiteral{Position{}, FLT_MAX, &arg0.type().componentType()};
3270 if (!this->pushVectorizedExpression(fltMaxLiteral, arg0.type())) {
3271 return unsupported();
3272 }
3273 if (!this->binaryOp(arg0.type(), kMultiplyOps)) {
3274 return unsupported();
3275 }
3276 }
3277 Literal neg1Literal{Position{}, -1.0, &arg0.type().componentType()};
3278 if (!this->pushVectorizedExpression(neg1Literal, arg0.type())) {
3279 return unsupported();
3280 }
3281 if (!this->binaryOp(arg0.type(), kMaxOps)) {
3282 return unsupported();
3283 }
3284 Literal pos1Literal{Position{}, 1.0, &arg0.type().componentType()};
3285 if (!this->pushVectorizedExpression(pos1Literal, arg0.type())) {
3286 return unsupported();
3287 }
3288 return this->binaryOp(arg0.type(), kMinOps);
3289 }
3290 case IntrinsicKind::k_sin_IntrinsicKind:
3291 return this->pushIntrinsic(BuilderOp::sin_float, arg0);
3292
3293 case IntrinsicKind::k_sqrt_IntrinsicKind:
3294 return this->pushIntrinsic(BuilderOp::sqrt_float, arg0);
3295
3296 case IntrinsicKind::k_tan_IntrinsicKind:
3297 return this->pushIntrinsic(BuilderOp::tan_float, arg0);
3298
3299 case IntrinsicKind::k_transpose_IntrinsicKind:
3300 SkASSERT(arg0.type().isMatrix());
3301 if (!this->pushExpression(arg0)) {
3302 return unsupported();
3303 }
3304 fBuilder.transpose(arg0.type().columns(), arg0.type().rows());
3305 return true;
3306
3307 case IntrinsicKind::k_trunc_IntrinsicKind:
3308 // Implement trunc as `float(int(x))`, since float-to-int rounds toward zero.
3309 if (!this->pushExpression(arg0)) {
3310 return unsupported();
3311 }
3312 fBuilder.unary_op(BuilderOp::cast_to_int_from_float, arg0.type().slotCount());
3313 fBuilder.unary_op(BuilderOp::cast_to_float_from_int, arg0.type().slotCount());
3314 return true;
3315
3316 case IntrinsicKind::k_fromLinearSrgb_IntrinsicKind:
3317 case IntrinsicKind::k_toLinearSrgb_IntrinsicKind:
3318 // The argument must be a half3.
3319 SkASSERT(arg0.type().matches(*fContext.fTypes.fHalf3));
3320 if (!this->pushExpression(arg0)) {
3321 return unsupported();
3322 }
3323
3324 if (intrinsic == IntrinsicKind::k_fromLinearSrgb_IntrinsicKind) {
3325 fBuilder.invoke_from_linear_srgb();
3326 } else {
3327 fBuilder.invoke_to_linear_srgb();
3328 }
3329 return true;
3330
3331 default:
3332 break;
3333 }
3334 return unsupported();
3335 }
3336
3337 bool Generator::pushIntrinsic(const TypedOps& ops, const Expression& arg0, const Expression& arg1) {
3338 if (!this->pushExpression(arg0) || !this->pushVectorizedExpression(arg1, arg0.type())) {
3339 return unsupported();
3340 }
3341 return this->binaryOp(arg0.type(), ops);
3342 }
3343
3344 bool Generator::pushIntrinsic(BuilderOp builderOp, const Expression& arg0, const Expression& arg1) {
3345 if (!this->pushExpression(arg0) || !this->pushVectorizedExpression(arg1, arg0.type())) {
3346 return unsupported();
3347 }
3348 fBuilder.binary_op(builderOp, arg0.type().slotCount());
3349 return true;
3350 }
3351
3352 bool Generator::pushIntrinsic(IntrinsicKind intrinsic,
3353 const Expression& arg0,
3354 const Expression& arg1) {
3355 switch (intrinsic) {
3356 case IntrinsicKind::k_atan_IntrinsicKind:
3357 return this->pushIntrinsic(BuilderOp::atan2_n_floats, arg0, arg1);
3358
3359 case IntrinsicKind::k_cross_IntrinsicKind: {
3360 // Implement cross as `arg0.yzx * arg1.zxy - arg0.zxy * arg1.yzx`. We use two stacks so
3361 // that each subexpression can be multiplied separately.
3362 SkASSERT(arg0.type().matches(arg1.type()));
3363 SkASSERT(arg0.type().slotCount() == 3);
3364 SkASSERT(arg1.type().slotCount() == 3);
3365
3366 // Push `arg0.yzx` onto this stack and `arg0.zxy` onto a separate subexpression stack.
3367 AutoStack subexpressionStack(this);
3368 subexpressionStack.enter();
3369 if (!this->pushExpression(arg0)) {
3370 return unsupported();
3371 }
3372 subexpressionStack.exit();
3373 subexpressionStack.pushClone(/*slots=*/3);
3374
3375 fBuilder.swizzle(/*consumedSlots=*/3, {{1, 2, 0}});
3376 subexpressionStack.enter();
3377 fBuilder.swizzle(/*consumedSlots=*/3, {{2, 0, 1}});
3378 subexpressionStack.exit();
3379
3380 // Push `arg1.zxy` onto this stack and `arg1.yzx` onto the next stack. Perform the
3381 // multiply on each subexpression (`arg0.yzx * arg1.zxy` on the first stack, and
3382 // `arg0.zxy * arg1.yzx` on the next).
3383 subexpressionStack.enter();
3384 if (!this->pushExpression(arg1)) {
3385 return unsupported();
3386 }
3387 subexpressionStack.exit();
3388 subexpressionStack.pushClone(/*slots=*/3);
3389
3390 fBuilder.swizzle(/*consumedSlots=*/3, {{2, 0, 1}});
3391 fBuilder.binary_op(BuilderOp::mul_n_floats, 3);
3392
3393 subexpressionStack.enter();
3394 fBuilder.swizzle(/*consumedSlots=*/3, {{1, 2, 0}});
3395 fBuilder.binary_op(BuilderOp::mul_n_floats, 3);
3396 subexpressionStack.exit();
3397
3398 // Migrate the result of the second subexpression (`arg0.zxy * arg1.yzx`) back onto the
3399 // main stack and subtract it from the first subexpression (`arg0.yzx * arg1.zxy`).
3400 subexpressionStack.pushClone(/*slots=*/3);
3401 fBuilder.binary_op(BuilderOp::sub_n_floats, 3);
3402
3403 // Now that the calculation is complete, discard the subexpression on the next stack.
3404 subexpressionStack.enter();
3405 this->discardExpression(/*slots=*/3);
3406 subexpressionStack.exit();
3407 return true;
3408 }
3409 case IntrinsicKind::k_distance_IntrinsicKind:
3410 // Implement distance as `length(a - b)`.
3411 SkASSERT(arg0.type().slotCount() == arg1.type().slotCount());
3412 return this->pushBinaryExpression(arg0, OperatorKind::MINUS, arg1) &&
3413 this->pushLengthIntrinsic(arg0.type().slotCount());
3414
3415 case IntrinsicKind::k_dot_IntrinsicKind:
3416 SkASSERT(arg0.type().matches(arg1.type()));
3417 if (!this->pushExpression(arg0) || !this->pushExpression(arg1)) {
3418 return unsupported();
3419 }
3420 fBuilder.dot_floats(arg0.type().slotCount());
3421 return true;
3422
3423 case IntrinsicKind::k_equal_IntrinsicKind:
3424 SkASSERT(arg0.type().matches(arg1.type()));
3425 return this->pushIntrinsic(kEqualOps, arg0, arg1);
3426
3427 case IntrinsicKind::k_notEqual_IntrinsicKind:
3428 SkASSERT(arg0.type().matches(arg1.type()));
3429 return this->pushIntrinsic(kNotEqualOps, arg0, arg1);
3430
3431 case IntrinsicKind::k_lessThan_IntrinsicKind:
3432 SkASSERT(arg0.type().matches(arg1.type()));
3433 return this->pushIntrinsic(kLessThanOps, arg0, arg1);
3434
3435 case IntrinsicKind::k_greaterThan_IntrinsicKind:
3436 SkASSERT(arg0.type().matches(arg1.type()));
3437 return this->pushIntrinsic(kLessThanOps, arg1, arg0);
3438
3439 case IntrinsicKind::k_lessThanEqual_IntrinsicKind:
3440 SkASSERT(arg0.type().matches(arg1.type()));
3441 return this->pushIntrinsic(kLessThanEqualOps, arg0, arg1);
3442
3443 case IntrinsicKind::k_greaterThanEqual_IntrinsicKind:
3444 SkASSERT(arg0.type().matches(arg1.type()));
3445 return this->pushIntrinsic(kLessThanEqualOps, arg1, arg0);
3446
3447 case IntrinsicKind::k_min_IntrinsicKind:
3448 SkASSERT(arg0.type().componentType().matches(arg1.type().componentType()));
3449 return this->pushIntrinsic(kMinOps, arg0, arg1);
3450
3451 case IntrinsicKind::k_matrixCompMult_IntrinsicKind:
3452 SkASSERT(arg0.type().matches(arg1.type()));
3453 return this->pushIntrinsic(kMultiplyOps, arg0, arg1);
3454
3455 case IntrinsicKind::k_max_IntrinsicKind:
3456 SkASSERT(arg0.type().componentType().matches(arg1.type().componentType()));
3457 return this->pushIntrinsic(kMaxOps, arg0, arg1);
3458
3459 case IntrinsicKind::k_mod_IntrinsicKind:
3460 SkASSERT(arg0.type().componentType().matches(arg1.type().componentType()));
3461 return this->pushIntrinsic(kModOps, arg0, arg1);
3462
3463 case IntrinsicKind::k_pow_IntrinsicKind:
3464 SkASSERT(arg0.type().matches(arg1.type()));
3465 return this->pushIntrinsic(BuilderOp::pow_n_floats, arg0, arg1);
3466
3467 case IntrinsicKind::k_reflect_IntrinsicKind: {
3468 // Implement reflect as `I - (N * dot(I,N) * 2)`.
3469 SkASSERT(arg0.type().matches(arg1.type()));
3470 SkASSERT(arg0.type().slotCount() == arg1.type().slotCount());
3471 SkASSERT(arg0.type().componentType().isFloat());
3472 int slotCount = arg0.type().slotCount();
3473
3474 // Stack: I, N.
3475 if (!this->pushExpression(arg0) || !this->pushExpression(arg1)) {
3476 return unsupported();
3477 }
3478 // Stack: I, N, I, N.
3479 fBuilder.push_clone(2 * slotCount);
3480 // Stack: I, N, dot(I,N)
3481 fBuilder.dot_floats(slotCount);
3482 // Stack: I, N, dot(I,N), 2
3483 fBuilder.push_constant_f(2.0);
3484 // Stack: I, N, dot(I,N) * 2
3485 fBuilder.binary_op(BuilderOp::mul_n_floats, 1);
3486 // Stack: I, N * dot(I,N) * 2
3487 fBuilder.push_duplicates(slotCount - 1);
3488 fBuilder.binary_op(BuilderOp::mul_n_floats, slotCount);
3489 // Stack: I - (N * dot(I,N) * 2)
3490 fBuilder.binary_op(BuilderOp::sub_n_floats, slotCount);
3491 return true;
3492 }
3493 case IntrinsicKind::k_step_IntrinsicKind: {
3494 // Compute step as `float(lessThanEqual(edge, x))`. We convert from boolean 0/~0 to
3495 // floating point zero/one by using a bitwise-and against the bit-pattern of 1.0.
3496 SkASSERT(arg0.type().componentType().matches(arg1.type().componentType()));
3497 if (!this->pushVectorizedExpression(arg0, arg1.type()) || !this->pushExpression(arg1)) {
3498 return unsupported();
3499 }
3500 if (!this->binaryOp(arg1.type(), kLessThanEqualOps)) {
3501 return unsupported();
3502 }
3503 Literal pos1Literal{Position{}, 1.0, &arg1.type().componentType()};
3504 if (!this->pushVectorizedExpression(pos1Literal, arg1.type())) {
3505 return unsupported();
3506 }
3507 fBuilder.binary_op(BuilderOp::bitwise_and_n_ints, arg1.type().slotCount());
3508 return true;
3509 }
3510
3511 default:
3512 break;
3513 }
3514 return unsupported();
3515 }
3516
3517 bool Generator::pushIntrinsic(IntrinsicKind intrinsic,
3518 const Expression& arg0,
3519 const Expression& arg1,
3520 const Expression& arg2) {
3521 switch (intrinsic) {
3522 case IntrinsicKind::k_clamp_IntrinsicKind:
3523 // Implement clamp as min(max(arg, low), high).
3524 SkASSERT(arg0.type().componentType().matches(arg1.type().componentType()));
3525 SkASSERT(arg0.type().componentType().matches(arg2.type().componentType()));
3526 if (!this->pushExpression(arg0) || !this->pushVectorizedExpression(arg1, arg0.type())) {
3527 return unsupported();
3528 }
3529 if (!this->binaryOp(arg0.type(), kMaxOps)) {
3530 return unsupported();
3531 }
3532 if (!this->pushVectorizedExpression(arg2, arg0.type())) {
3533 return unsupported();
3534 }
3535 if (!this->binaryOp(arg0.type(), kMinOps)) {
3536 return unsupported();
3537 }
3538 return true;
3539
3540 case IntrinsicKind::k_faceforward_IntrinsicKind: {
3541 // Implement faceforward as `N ^ ((0 <= dot(I, NRef)) & 0x80000000)`.
3542 // In other words, flip the sign bit of N if `0 <= dot(I, NRef)`.
3543 SkASSERT(arg0.type().matches(arg1.type()));
3544 SkASSERT(arg0.type().matches(arg2.type()));
3545 int slotCount = arg0.type().slotCount();
3546
3547 // Stack: N, 0, I, Nref
3548 if (!this->pushExpression(arg0)) {
3549 return unsupported();
3550 }
3551 fBuilder.push_constant_f(0.0);
3552 if (!this->pushExpression(arg1) || !this->pushExpression(arg2)) {
3553 return unsupported();
3554 }
3555 // Stack: N, 0, dot(I,NRef)
3556 fBuilder.dot_floats(slotCount);
3557 // Stack: N, (0 <= dot(I,NRef))
3558 fBuilder.binary_op(BuilderOp::cmple_n_floats, 1);
3559 // Stack: N, (0 <= dot(I,NRef)), 0x80000000
3560 fBuilder.push_constant_u(0x80000000);
3561 // Stack: N, (0 <= dot(I,NRef)) & 0x80000000)
3562 fBuilder.binary_op(BuilderOp::bitwise_and_n_ints, 1);
3563 // Stack: N, vec(0 <= dot(I,NRef)) & 0x80000000)
3564 fBuilder.push_duplicates(slotCount - 1);
3565 // Stack: N ^ vec((0 <= dot(I,NRef)) & 0x80000000)
3566 fBuilder.binary_op(BuilderOp::bitwise_xor_n_ints, slotCount);
3567 return true;
3568 }
3569 case IntrinsicKind::k_mix_IntrinsicKind:
3570 // Note: our SkRP mix op takes the interpolation point first, not the interpolants.
3571 SkASSERT(arg0.type().matches(arg1.type()));
3572 if (arg2.type().componentType().isFloat()) {
3573 SkASSERT(arg0.type().componentType().matches(arg2.type().componentType()));
3574 if (!this->pushVectorizedExpression(arg2, arg0.type())) {
3575 return unsupported();
3576 }
3577 if (!this->pushExpression(arg0) || !this->pushExpression(arg1)) {
3578 return unsupported();
3579 }
3580 return this->ternaryOp(arg0.type(), kMixOps);
3581 }
3582 if (arg2.type().componentType().isBoolean()) {
3583 if (!this->pushExpression(arg2)) {
3584 return unsupported();
3585 }
3586 if (!this->pushExpression(arg0) || !this->pushExpression(arg1)) {
3587 return unsupported();
3588 }
3589 // The `mix_int` op isn't doing a lerp; it uses the third argument to select values
3590 // from the first and second arguments. It's safe for use with any type in arguments
3591 // 0 and 1.
3592 fBuilder.ternary_op(BuilderOp::mix_n_ints, arg0.type().slotCount());
3593 return true;
3594 }
3595 return unsupported();
3596
3597 case IntrinsicKind::k_refract_IntrinsicKind: {
3598 // We always calculate refraction using vec4s, so we pad out unused N/I slots with zero.
3599 int padding = 4 - arg0.type().slotCount();
3600 if (!this->pushExpression(arg0)) {
3601 return unsupported();
3602 }
3603 fBuilder.push_zeros(padding);
3604
3605 if (!this->pushExpression(arg1)) {
3606 return unsupported();
3607 }
3608 fBuilder.push_zeros(padding);
3609
3610 // eta is always a scalar and doesn't need padding.
3611 if (!this->pushExpression(arg2)) {
3612 return unsupported();
3613 }
3614 fBuilder.refract_floats();
3615
3616 // The result vector was returned as a vec4, so discard the extra columns.
3617 fBuilder.discard_stack(padding);
3618 return true;
3619 }
3620 case IntrinsicKind::k_smoothstep_IntrinsicKind:
3621 SkASSERT(arg0.type().componentType().isFloat());
3622 SkASSERT(arg1.type().matches(arg0.type()));
3623 SkASSERT(arg2.type().componentType().isFloat());
3624
3625 if (!this->pushVectorizedExpression(arg0, arg2.type()) ||
3626 !this->pushVectorizedExpression(arg1, arg2.type()) ||
3627 !this->pushExpression(arg2)) {
3628 return unsupported();
3629 }
3630 fBuilder.ternary_op(BuilderOp::smoothstep_n_floats, arg2.type().slotCount());
3631 return true;
3632
3633 default:
3634 break;
3635 }
3636 return unsupported();
3637 }
3638
3639 bool Generator::pushLiteral(const Literal& l) {
3640 switch (l.type().numberKind()) {
3641 case Type::NumberKind::kFloat:
3642 fBuilder.push_constant_f(l.floatValue());
3643 return true;
3644
3645 case Type::NumberKind::kSigned:
3646 fBuilder.push_constant_i(l.intValue());
3647 return true;
3648
3649 case Type::NumberKind::kUnsigned:
3650 fBuilder.push_constant_u(l.intValue());
3651 return true;
3652
3653 case Type::NumberKind::kBoolean:
3654 fBuilder.push_constant_i(l.boolValue() ? ~0 : 0);
3655 return true;
3656
3657 default:
3658 SkUNREACHABLE;
3659 }
3660 }
3661
3662 bool Generator::pushPostfixExpression(const PostfixExpression& p, bool usesResult) {
3663 // If the result is ignored...
3664 if (!usesResult) {
3665 // ... just emit a prefix expression instead.
3666 return this->pushPrefixExpression(p.getOperator(), *p.operand());
3667 }
3668 // Get the operand as an lvalue, and push it onto the stack as-is.
3669 std::unique_ptr<LValue> lvalue = this->makeLValue(*p.operand());
3670 if (!lvalue || !this->push(*lvalue)) {
3671 return unsupported();
3672 }
3673
3674 // Push a scratch copy of the operand.
3675 fBuilder.push_clone(p.type().slotCount());
3676
3677 // Increment or decrement the scratch copy by one.
3678 Literal oneLiteral{Position{}, 1.0, &p.type().componentType()};
3679 if (!this->pushVectorizedExpression(oneLiteral, p.type())) {
3680 return unsupported();
3681 }
3682
3683 switch (p.getOperator().kind()) {
3684 case OperatorKind::PLUSPLUS:
3685 if (!this->binaryOp(p.type(), kAddOps)) {
3686 return unsupported();
3687 }
3688 break;
3689
3690 case OperatorKind::MINUSMINUS:
3691 if (!this->binaryOp(p.type(), kSubtractOps)) {
3692 return unsupported();
3693 }
3694 break;
3695
3696 default:
3697 SkUNREACHABLE;
3698 }
3699
3700 // Write the new value back to the operand.
3701 if (!this->store(*lvalue)) {
3702 return unsupported();
3703 }
3704
3705 // Discard the scratch copy, leaving only the original value as-is.
3706 this->discardExpression(p.type().slotCount());
3707 return true;
3708 }
3709
3710 bool Generator::pushPrefixExpression(const PrefixExpression& p) {
3711 return this->pushPrefixExpression(p.getOperator(), *p.operand());
3712 }
3713
3714 bool Generator::pushPrefixExpression(Operator op, const Expression& expr) {
3715 switch (op.kind()) {
3716 case OperatorKind::BITWISENOT:
3717 case OperatorKind::LOGICALNOT:
3718 // Handle operators ! and ~.
3719 if (!this->pushExpression(expr)) {
3720 return unsupported();
3721 }
3722 fBuilder.push_constant_u(~0, expr.type().slotCount());
3723 fBuilder.binary_op(BuilderOp::bitwise_xor_n_ints, expr.type().slotCount());
3724 return true;
3725
3726 case OperatorKind::MINUS: {
3727 if (!this->pushExpression(expr)) {
3728 return unsupported();
3729 }
3730 if (expr.type().componentType().isFloat()) {
3731 // Handle float negation as an integer `x ^ 0x80000000`. This toggles the sign bit.
3732 fBuilder.push_constant_u(0x80000000, expr.type().slotCount());
3733 fBuilder.binary_op(BuilderOp::bitwise_xor_n_ints, expr.type().slotCount());
3734 } else {
3735 // Handle integer negation as a componentwise `expr * -1`.
3736 fBuilder.push_constant_i(-1, expr.type().slotCount());
3737 fBuilder.binary_op(BuilderOp::mul_n_ints, expr.type().slotCount());
3738 }
3739 return true;
3740 }
3741 case OperatorKind::PLUSPLUS: {
3742 // Rewrite as `expr += 1`.
3743 Literal oneLiteral{Position{}, 1.0, &expr.type().componentType()};
3744 return this->pushBinaryExpression(expr, OperatorKind::PLUSEQ, oneLiteral);
3745 }
3746 case OperatorKind::MINUSMINUS: {
3747 // Rewrite as `expr += -1`.
3748 Literal minusOneLiteral{expr.fPosition, -1.0, &expr.type().componentType()};
3749 return this->pushBinaryExpression(expr, OperatorKind::PLUSEQ, minusOneLiteral);
3750 }
3751 default:
3752 break;
3753 }
3754
3755 return unsupported();
3756 }
3757
3758 bool Generator::pushSwizzle(const Swizzle& s) {
3759 SkASSERT(!s.components().empty() && s.components().size() <= 4);
3760
3761 // If this is a simple subset of a variable's slots...
3762 bool isSimpleSubset = is_sliceable_swizzle(s.components());
3763 if (isSimpleSubset && s.base()->is<VariableReference>()) {
3764 // ... we can just push part of the variable directly onto the stack, rather than pushing
3765 // the whole expression and then immediately cutting it down. (Either way works, but this
3766 // saves a step.)
3767 return this->pushVariableReferencePartial(
3768 s.base()->as<VariableReference>(),
3769 SlotRange{/*index=*/s.components()[0], /*count=*/s.components().size()});
3770 }
3771 // Push the base expression.
3772 if (!this->pushExpression(*s.base())) {
3773 return false;
3774 }
3775 // An identity swizzle doesn't rearrange the data; it just (potentially) discards tail elements.
3776 if (isSimpleSubset && s.components()[0] == 0) {
3777 int discardedElements = s.base()->type().slotCount() - s.components().size();
3778 SkASSERT(discardedElements >= 0);
3779 fBuilder.discard_stack(discardedElements);
3780 return true;
3781 }
3782 // Perform the swizzle.
3783 fBuilder.swizzle(s.base()->type().slotCount(), s.components());
3784 return true;
3785 }
3786
3787 bool Generator::pushTernaryExpression(const TernaryExpression& t) {
3788 return this->pushTernaryExpression(*t.test(), *t.ifTrue(), *t.ifFalse());
3789 }
3790
3791 bool Generator::pushDynamicallyUniformTernaryExpression(const Expression& test,
3792 const Expression& ifTrue,
3793 const Expression& ifFalse) {
3794 SkASSERT(Analysis::IsDynamicallyUniformExpression(test));
3795
3796 int falseLabelID = fBuilder.nextLabelID();
3797 int exitLabelID = fBuilder.nextLabelID();
3798
3799 // First, push the test-expression into a separate stack.
3800 AutoStack testStack(this);
3801 testStack.enter();
3802 if (!this->pushExpression(test)) {
3803 return unsupported();
3804 }
3805
3806 // Branch to the true- or false-expression based on the test-expression. We can skip the
3807 // non-true path entirely since the test is known to be uniform.
3808 fBuilder.branch_if_no_active_lanes_on_stack_top_equal(~0, falseLabelID);
3809 testStack.exit();
3810
3811 if (!this->pushExpression(ifTrue)) {
3812 return unsupported();
3813 }
3814
3815 fBuilder.jump(exitLabelID);
3816
3817 // The builder doesn't understand control flow, and assumes that every push moves the stack-top
3818 // forwards. We need to manually balance out the `pushExpression` from the if-true path by
3819 // moving the stack position backwards, so that the if-false path pushes its expression into the
3820 // same as the if-true result.
3821 this->discardExpression(/*slots=*/ifTrue.type().slotCount());
3822
3823 fBuilder.label(falseLabelID);
3824
3825 if (!this->pushExpression(ifFalse)) {
3826 return unsupported();
3827 }
3828
3829 fBuilder.label(exitLabelID);
3830
3831 // Jettison the text-expression from the separate stack.
3832 testStack.enter();
3833 this->discardExpression(/*slots=*/1);
3834 testStack.exit();
3835 return true;
3836 }
3837
3838 bool Generator::pushTernaryExpression(const Expression& test,
3839 const Expression& ifTrue,
3840 const Expression& ifFalse) {
3841 // If the test-expression is dynamically-uniform, we can skip over the non-true expressions
3842 // entirely, and not need to involve the condition mask.
3843 if (Analysis::IsDynamicallyUniformExpression(test)) {
3844 return this->pushDynamicallyUniformTernaryExpression(test, ifTrue, ifFalse);
3845 }
3846
3847 // Analyze the ternary to see which corners we can safely cut.
3848 bool ifFalseHasSideEffects = Analysis::HasSideEffects(ifFalse);
3849 bool ifTrueHasSideEffects = Analysis::HasSideEffects(ifTrue);
3850 bool ifTrueIsTrivial = Analysis::IsTrivialExpression(ifTrue);
3851 int cleanupLabelID = fBuilder.nextLabelID();
3852
3853 // If the true- and false-expressions both lack side effects, we evaluate both of them safely
3854 // without masking off their effects. In that case, we can emit both sides and use boolean mix
3855 // to select the correct result without using the condition mask at all.
3856 if (!ifFalseHasSideEffects && !ifTrueHasSideEffects && ifTrueIsTrivial) {
3857 // Push all of the arguments to mix.
3858 if (!this->pushVectorizedExpression(test, ifTrue.type())) {
3859 return unsupported();
3860 }
3861 if (!this->pushExpression(ifFalse)) {
3862 return unsupported();
3863 }
3864 if (!this->pushExpression(ifTrue)) {
3865 return unsupported();
3866 }
3867 // Use boolean mix to select the true- or false-expression via the test-expression.
3868 fBuilder.ternary_op(BuilderOp::mix_n_ints, ifTrue.type().slotCount());
3869 return true;
3870 }
3871
3872 // First, push the current condition-mask and the test-expression into a separate stack.
3873 fBuilder.enableExecutionMaskWrites();
3874 AutoStack testStack(this);
3875 testStack.enter();
3876 fBuilder.push_condition_mask();
3877 if (!this->pushExpression(test)) {
3878 return unsupported();
3879 }
3880 testStack.exit();
3881
3882 // We can take some shortcuts with condition-mask handling if the false-expression is entirely
3883 // side-effect free. (We can evaluate it without masking off its effects.) We always handle the
3884 // condition mask properly for the test-expression and true-expression properly.
3885 if (!ifFalseHasSideEffects) {
3886 // Push the false-expression onto the primary stack.
3887 if (!this->pushExpression(ifFalse)) {
3888 return unsupported();
3889 }
3890
3891 // Next, merge the condition mask (on the separate stack) with the test expression.
3892 testStack.enter();
3893 fBuilder.merge_condition_mask();
3894 testStack.exit();
3895
3896 // If no lanes are active, we can skip the true-expression entirely. This isn't super likely
3897 // to happen, so it's probably only a win for non-trivial true-expressions.
3898 if (!ifTrueIsTrivial) {
3899 fBuilder.branch_if_no_lanes_active(cleanupLabelID);
3900 }
3901
3902 // Push the true-expression onto the primary stack, immediately after the false-expression.
3903 if (!this->pushExpression(ifTrue)) {
3904 return unsupported();
3905 }
3906
3907 // Use a select to conditionally mask-merge the true-expression and false-expression lanes.
3908 fBuilder.select(/*slots=*/ifTrue.type().slotCount());
3909 fBuilder.label(cleanupLabelID);
3910 } else {
3911 // Merge the condition mask (on the separate stack) with the test expression.
3912 testStack.enter();
3913 fBuilder.merge_condition_mask();
3914 testStack.exit();
3915
3916 // Push the true-expression onto the primary stack.
3917 if (!this->pushExpression(ifTrue)) {
3918 return unsupported();
3919 }
3920
3921 // Switch back to the test-expression stack and apply the inverted test condition.
3922 testStack.enter();
3923 fBuilder.merge_inv_condition_mask();
3924 testStack.exit();
3925
3926 // Push the false-expression onto the primary stack, immediately after the true-expression.
3927 if (!this->pushExpression(ifFalse)) {
3928 return unsupported();
3929 }
3930
3931 // Use a select to conditionally mask-merge the true-expression and false-expression lanes;
3932 // the mask is already set up for this.
3933 fBuilder.select(/*slots=*/ifTrue.type().slotCount());
3934 }
3935
3936 // Restore the condition-mask to its original state and jettison the test-expression.
3937 testStack.enter();
3938 this->discardExpression(/*slots=*/1);
3939 fBuilder.pop_condition_mask();
3940 testStack.exit();
3941
3942 fBuilder.disableExecutionMaskWrites();
3943 return true;
3944 }
3945
3946 bool Generator::pushVariableReference(const VariableReference& var) {
3947 // If we are pushing a constant-value variable, push the value directly; literal values are more
3948 // amenable to optimization.
3949 if (var.type().isScalar() || var.type().isVector()) {
3950 if (const Expression* expr = ConstantFolder::GetConstantValueOrNull(var)) {
3951 return this->pushExpression(*expr);
3952 }
3953 if (fImmutableVariables.contains(var.variable())) {
3954 return this->pushExpression(*var.variable()->initialValue());
3955 }
3956 }
3957 return this->pushVariableReferencePartial(var, SlotRange{0, (int)var.type().slotCount()});
3958 }
3959
3960 bool Generator::pushVariableReferencePartial(const VariableReference& v, SlotRange subset) {
3961 const Variable& var = *v.variable();
3962 SlotRange r;
3963 if (IsUniform(var)) {
3964 // Push a uniform.
3965 r = this->getUniformSlots(var);
3966 SkASSERT(r.count == (int)var.type().slotCount());
3967 r.index += subset.index;
3968 r.count = subset.count;
3969 fBuilder.push_uniform(r);
3970 } else if (fImmutableVariables.contains(&var)) {
3971 // If we only need a single slot, we can push a constant. This saves a lookup, and can
3972 // occasionally permit the use of an immediate-mode op.
3973 if (subset.count == 1) {
3974 const Expression& expr = *v.variable()->initialValue();
3975 std::optional<ImmutableBits> bits = this->getImmutableBitsForSlot(expr, subset.index);
3976 if (bits.has_value()) {
3977 fBuilder.push_constant_i(*bits);
3978 return true;
3979 }
3980 }
3981 // Push the immutable slot range.
3982 r = this->getImmutableSlots(var);
3983 SkASSERT(r.count == (int)var.type().slotCount());
3984 r.index += subset.index;
3985 r.count = subset.count;
3986 fBuilder.push_immutable(r);
3987 } else {
3988 // Push the variable.
3989 r = this->getVariableSlots(var);
3990 SkASSERT(r.count == (int)var.type().slotCount());
3991 r.index += subset.index;
3992 r.count = subset.count;
3993 fBuilder.push_slots(r);
3994 }
3995 return true;
3996 }
3997
3998 bool Generator::writeProgram(const FunctionDefinition& function) {
3999 fCurrentFunction = &function;
4000
4001 if (fDebugTrace) {
4002 // Copy the program source into the debug info so that it will be written in the trace file.
4003 fDebugTrace->setSource(*fProgram.fSource);
4004
4005 if (fWriteTraceOps) {
4006 // The Raster Pipeline blitter generates centered pixel coordinates. (0.5, 1.5, 2.5,
4007 // etc.) Add 0.5 to the requested trace coordinate to match this, then compare against
4008 // src.rg, which contains the shader's coordinates. We keep this result in a dedicated
4009 // trace-mask stack.
4010 fTraceMask.emplace(this);
4011 fTraceMask->enter();
4012 fBuilder.push_device_xy01();
4013 fBuilder.discard_stack(2);
4014 fBuilder.push_constant_f(fDebugTrace->fTraceCoord.fX + 0.5f);
4015 fBuilder.push_constant_f(fDebugTrace->fTraceCoord.fY + 0.5f);
4016 fBuilder.binary_op(BuilderOp::cmpeq_n_floats, 2);
4017 fBuilder.binary_op(BuilderOp::bitwise_and_n_ints, 1);
4018 fTraceMask->exit();
4019
4020 // Assemble a position-to-line-number mapping for the debugger.
4021 this->calculateLineOffsets();
4022 }
4023 }
4024
4025 // Assign slots to the parameters of main; copy src and dst into those slots as appropriate.
4026 const SkSL::Variable* mainCoordsParam = function.declaration().getMainCoordsParameter();
4027 const SkSL::Variable* mainInputColorParam = function.declaration().getMainInputColorParameter();
4028 const SkSL::Variable* mainDestColorParam = function.declaration().getMainDestColorParameter();
4029
4030 for (const SkSL::Variable* param : function.declaration().parameters()) {
4031 if (param == mainCoordsParam) {
4032 // Coordinates are passed via RG.
4033 SlotRange fragCoord = this->getVariableSlots(*param);
4034 SkASSERT(fragCoord.count == 2);
4035 fBuilder.store_src_rg(fragCoord);
4036 } else if (param == mainInputColorParam) {
4037 // Input colors are passed via RGBA.
4038 SlotRange srcColor = this->getVariableSlots(*param);
4039 SkASSERT(srcColor.count == 4);
4040 fBuilder.store_src(srcColor);
4041 } else if (param == mainDestColorParam) {
4042 // Dest colors are passed via dRGBA.
4043 SlotRange destColor = this->getVariableSlots(*param);
4044 SkASSERT(destColor.count == 4);
4045 fBuilder.store_dst(destColor);
4046 } else {
4047 SkDEBUGFAIL("Invalid parameter to main()");
4048 return unsupported();
4049 }
4050 }
4051
4052 // Initialize the program.
4053 fBuilder.init_lane_masks();
4054
4055 // Emit global variables.
4056 if (!this->writeGlobals()) {
4057 return unsupported();
4058 }
4059
4060 // Invoke main().
4061 std::optional<SlotRange> mainResult = this->writeFunction(function, function, /*arguments=*/{});
4062 if (!mainResult.has_value()) {
4063 return unsupported();
4064 }
4065
4066 // Move the result of main() from slots into RGBA.
4067 SkASSERT(mainResult->count == 4);
4068 if (this->needsFunctionResultSlots(fCurrentFunction)) {
4069 fBuilder.load_src(*mainResult);
4070 } else {
4071 fBuilder.pop_src_rgba();
4072 }
4073
4074 // Discard the trace mask.
4075 if (fTraceMask.has_value()) {
4076 fTraceMask->enter();
4077 fBuilder.discard_stack(1);
4078 fTraceMask->exit();
4079 }
4080
4081 return true;
4082 }
4083
4084 std::unique_ptr<RP::Program> Generator::finish() {
4085 return fBuilder.finish(fProgramSlots.slotCount(),
4086 fUniformSlots.slotCount(),
4087 fImmutableSlots.slotCount(),
4088 fDebugTrace);
4089 }
4090
4091 } // namespace RP
4092
4093 std::unique_ptr<RP::Program> MakeRasterPipelineProgram(const SkSL::Program& program,
4094 const FunctionDefinition& function,
4095 DebugTracePriv* debugTrace,
4096 bool writeTraceOps) {
4097 RP::Generator generator(program, debugTrace, writeTraceOps);
4098 if (!generator.writeProgram(function)) {
4099 return nullptr;
4100 }
4101 return generator.finish();
4102 }
4103
4104 } // namespace SkSL