blob: 0e8f16cdb96b1de2e277e98e2bc2e0e0deec40cc [file] [log] [blame]
Brian Osman0a442b72020-12-02 11:12:51 -05001/*
2 * Copyright 2020 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
Ethan Nicholas24c17722021-03-09 13:10:59 -05008#include "include/private/SkSLProgramElement.h"
9#include "include/private/SkSLStatement.h"
Brian Osman0a442b72020-12-02 11:12:51 -050010#include "include/private/SkTArray.h"
Brian Osmanb8ebe232021-01-19 16:33:11 -050011#include "include/private/SkTPin.h"
Brian Osman00185012021-02-04 16:07:11 -050012#include "src/sksl/SkSLCompiler.h"
13#include "src/sksl/SkSLOperators.h"
John Stiles3738ef52021-04-13 10:41:57 -040014#include "src/sksl/codegen/SkSLCodeGenerator.h"
15#include "src/sksl/codegen/SkSLVMCodeGenerator.h"
Brian Osman0a442b72020-12-02 11:12:51 -050016#include "src/sksl/ir/SkSLBinaryExpression.h"
17#include "src/sksl/ir/SkSLBlock.h"
18#include "src/sksl/ir/SkSLBoolLiteral.h"
19#include "src/sksl/ir/SkSLBreakStatement.h"
20#include "src/sksl/ir/SkSLConstructor.h"
John Stiles7384b372021-04-01 13:48:15 -040021#include "src/sksl/ir/SkSLConstructorArray.h"
John Stilese1182782021-03-30 22:09:37 -040022#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040023#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stiles2938eea2021-04-01 18:58:25 -040024#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040025#include "src/sksl/ir/SkSLConstructorStruct.h"
Brian Osman0a442b72020-12-02 11:12:51 -050026#include "src/sksl/ir/SkSLContinueStatement.h"
27#include "src/sksl/ir/SkSLDoStatement.h"
28#include "src/sksl/ir/SkSLExpressionStatement.h"
29#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050030#include "src/sksl/ir/SkSLExternalFunctionReference.h"
Brian Osman0a442b72020-12-02 11:12:51 -050031#include "src/sksl/ir/SkSLFieldAccess.h"
32#include "src/sksl/ir/SkSLFloatLiteral.h"
33#include "src/sksl/ir/SkSLForStatement.h"
34#include "src/sksl/ir/SkSLFunctionCall.h"
35#include "src/sksl/ir/SkSLFunctionDeclaration.h"
36#include "src/sksl/ir/SkSLFunctionDefinition.h"
37#include "src/sksl/ir/SkSLIfStatement.h"
38#include "src/sksl/ir/SkSLIndexExpression.h"
39#include "src/sksl/ir/SkSLIntLiteral.h"
Brian Osman0a442b72020-12-02 11:12:51 -050040#include "src/sksl/ir/SkSLPostfixExpression.h"
41#include "src/sksl/ir/SkSLPrefixExpression.h"
Brian Osman0a442b72020-12-02 11:12:51 -050042#include "src/sksl/ir/SkSLReturnStatement.h"
Brian Osman0a442b72020-12-02 11:12:51 -050043#include "src/sksl/ir/SkSLSwitchStatement.h"
44#include "src/sksl/ir/SkSLSwizzle.h"
45#include "src/sksl/ir/SkSLTernaryExpression.h"
46#include "src/sksl/ir/SkSLVarDeclarations.h"
47#include "src/sksl/ir/SkSLVariableReference.h"
48
49#include <algorithm>
50#include <unordered_map>
51
Mike Kleinff4decc2021-02-10 16:13:35 -060052namespace {
53 // sksl allows the optimizations of fast_mul(), so we want to use that most of the time.
54 // This little sneaky snippet of code lets us use ** as a fast multiply infix operator.
55 struct FastF32 { skvm::F32 val; };
56 static FastF32 operator*(skvm::F32 y) { return {y}; }
57 static skvm::F32 operator*(skvm::F32 x, FastF32 y) { return fast_mul(x, y.val); }
58 static skvm::F32 operator*(float x, FastF32 y) { return fast_mul(x, y.val); }
59}
60
Brian Osman0a442b72020-12-02 11:12:51 -050061namespace SkSL {
62
63namespace {
64
Brian Osman0a442b72020-12-02 11:12:51 -050065// Holds scalars, vectors, or matrices
66struct Value {
67 Value() = default;
68 explicit Value(size_t slots) {
69 fVals.resize(slots);
70 }
71 Value(skvm::F32 x) : fVals({ x.id }) {}
72 Value(skvm::I32 x) : fVals({ x.id }) {}
73
74 explicit operator bool() const { return !fVals.empty(); }
75
76 size_t slots() const { return fVals.size(); }
77
78 struct ValRef {
79 ValRef(skvm::Val& val) : fVal(val) {}
80
81 ValRef& operator=(ValRef v) { fVal = v.fVal; return *this; }
82 ValRef& operator=(skvm::Val v) { fVal = v; return *this; }
83 ValRef& operator=(skvm::F32 v) { fVal = v.id; return *this; }
84 ValRef& operator=(skvm::I32 v) { fVal = v.id; return *this; }
85
86 operator skvm::Val() { return fVal; }
87
88 skvm::Val& fVal;
89 };
90
Brian Osmanf932c692021-01-26 13:54:07 -050091 ValRef operator[](size_t i) {
92 // These redundant asserts work around what we think is a codegen bug in GCC 8.x for
93 // 32-bit x86 Debug builds.
94 SkASSERT(i < fVals.size());
95 return fVals[i];
96 }
97 skvm::Val operator[](size_t i) const {
98 // These redundant asserts work around what we think is a codegen bug in GCC 8.x for
99 // 32-bit x86 Debug builds.
100 SkASSERT(i < fVals.size());
101 return fVals[i];
102 }
Brian Osman0a442b72020-12-02 11:12:51 -0500103
Brian Osmanae87bf12021-05-11 13:36:10 -0400104 SkSpan<skvm::Val> asSpan() { return SkMakeSpan(fVals); }
Brian Osman54515b72021-01-07 14:38:08 -0500105
Brian Osman0a442b72020-12-02 11:12:51 -0500106private:
107 SkSTArray<4, skvm::Val, true> fVals;
108};
109
110} // namespace
111
112class SkVMGenerator {
113public:
114 SkVMGenerator(const Program& program,
Brian Osman0a442b72020-12-02 11:12:51 -0500115 skvm::Builder* builder,
116 SkSpan<skvm::Val> uniforms,
Brian Osman0a442b72020-12-02 11:12:51 -0500117 skvm::Coord device,
118 skvm::Coord local,
John Stiles137482f2021-07-23 10:38:57 -0400119 SampleShaderFn sampleShader,
John Stiles2955c262021-07-23 15:51:05 -0400120 SampleColorFilterFn sampleColorFilter,
121 SampleBlenderFn sampleBlender);
Brian Osman0a442b72020-12-02 11:12:51 -0500122
Brian Osmandb2dad52021-01-07 14:08:30 -0500123 void writeFunction(const FunctionDefinition& function,
124 SkSpan<skvm::Val> arguments,
125 SkSpan<skvm::Val> outReturn);
Brian Osman0a442b72020-12-02 11:12:51 -0500126
127private:
Brian Osman0a442b72020-12-02 11:12:51 -0500128 /**
129 * In SkSL, a Variable represents a named, typed value (along with qualifiers, etc).
Brian Osman21f57072021-01-25 13:51:57 -0500130 * Every Variable is mapped to one (or several, contiguous) indices into our vector of
Brian Osman0a442b72020-12-02 11:12:51 -0500131 * skvm::Val. Those skvm::Val entries hold the current actual value of that variable.
132 *
133 * NOTE: Conceptually, each Variable is just mapped to a Value. We could implement it that way,
Brian Osman21f57072021-01-25 13:51:57 -0500134 * (and eliminate the indirection), but it would add overhead for each Variable,
Brian Osman0a442b72020-12-02 11:12:51 -0500135 * and add additional (different) bookkeeping for things like lvalue-swizzles.
136 *
137 * Any time a variable appears in an expression, that's a VariableReference, which is a kind of
138 * Expression. Evaluating that VariableReference (or any other Expression) produces a Value,
139 * which is a set of skvm::Val. (This allows an Expression to produce a vector or matrix, in
140 * addition to a scalar).
141 *
Brian Osman21f57072021-01-25 13:51:57 -0500142 * For a VariableReference, producing a Value is straightforward - we get the slot of the
143 * Variable (from fVariableMap), use that to look up the current skvm::Vals holding the
144 * variable's contents, and construct a Value with those ids.
Brian Osman0a442b72020-12-02 11:12:51 -0500145 */
146
147 /**
Brian Osman21f57072021-01-25 13:51:57 -0500148 * Returns the slot holding v's Val(s). Allocates storage if this is first time 'v' is
Brian Osman0a442b72020-12-02 11:12:51 -0500149 * referenced. Compound variables (e.g. vectors) will consume more than one slot, with
150 * getSlot returning the start of the contiguous chunk of slots.
151 */
Brian Osman21f57072021-01-25 13:51:57 -0500152 size_t getSlot(const Variable& v);
Brian Osman0a442b72020-12-02 11:12:51 -0500153
Mike Kleinaebcf732021-01-14 10:15:00 -0600154 skvm::F32 f32(skvm::Val id) { SkASSERT(id != skvm::NA); return {fBuilder, id}; }
155 skvm::I32 i32(skvm::Val id) { SkASSERT(id != skvm::NA); return {fBuilder, id}; }
Brian Osman0a442b72020-12-02 11:12:51 -0500156
157 // Shorthand for scalars
158 skvm::F32 f32(const Value& v) { SkASSERT(v.slots() == 1); return f32(v[0]); }
159 skvm::I32 i32(const Value& v) { SkASSERT(v.slots() == 1); return i32(v[0]); }
160
161 template <typename Fn>
162 Value unary(const Value& v, Fn&& fn) {
163 Value result(v.slots());
164 for (size_t i = 0; i < v.slots(); ++i) {
165 result[i] = fn({fBuilder, v[i]});
166 }
167 return result;
168 }
169
Brian Osman54515b72021-01-07 14:38:08 -0500170 skvm::I32 mask() {
171 // As we encounter (possibly conditional) return statements, fReturned is updated to store
172 // the lanes that have already returned. For the remainder of the current function, those
173 // lanes should be disabled.
Brian Osman9333c872021-01-13 15:06:17 -0500174 return fConditionMask & fLoopMask & ~currentFunction().fReturned;
Brian Osman54515b72021-01-07 14:38:08 -0500175 }
Brian Osman0a442b72020-12-02 11:12:51 -0500176
Brian Osmanfa71ffa2021-01-26 14:05:31 -0500177 size_t fieldSlotOffset(const FieldAccess& expr);
178 size_t indexSlotOffset(const IndexExpression& expr);
179
Brian Osman0a442b72020-12-02 11:12:51 -0500180 Value writeExpression(const Expression& expr);
181 Value writeBinaryExpression(const BinaryExpression& b);
John Stilesd986f472021-04-06 15:54:43 -0400182 Value writeAggregationConstructor(const AnyConstructor& c);
John Stilese1182782021-03-30 22:09:37 -0400183 Value writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c);
John Stiles5abb9e12021-04-06 13:47:19 -0400184 Value writeConstructorMatrixResize(const ConstructorMatrixResize& c);
John Stilesb14a8192021-04-05 11:40:46 -0400185 Value writeConstructorCast(const AnyConstructor& c);
John Stiles2938eea2021-04-01 18:58:25 -0400186 Value writeConstructorSplat(const ConstructorSplat& c);
Brian Osman0a442b72020-12-02 11:12:51 -0500187 Value writeFunctionCall(const FunctionCall& c);
Brian Osmandd50b0c2021-01-11 17:04:29 -0500188 Value writeExternalFunctionCall(const ExternalFunctionCall& c);
Brian Osmanfa71ffa2021-01-26 14:05:31 -0500189 Value writeFieldAccess(const FieldAccess& expr);
190 Value writeIndexExpression(const IndexExpression& expr);
Brian Osman0a442b72020-12-02 11:12:51 -0500191 Value writeIntrinsicCall(const FunctionCall& c);
192 Value writePostfixExpression(const PostfixExpression& p);
193 Value writePrefixExpression(const PrefixExpression& p);
194 Value writeSwizzle(const Swizzle& swizzle);
195 Value writeTernaryExpression(const TernaryExpression& t);
Brian Osmanfa71ffa2021-01-26 14:05:31 -0500196 Value writeVariableExpression(const VariableReference& expr);
Brian Osman0a442b72020-12-02 11:12:51 -0500197
John Stilesfd7252f2021-04-04 22:24:40 -0400198 Value writeTypeConversion(const Value& src, Type::NumberKind srcKind, Type::NumberKind dstKind);
199
Brian Osman0a442b72020-12-02 11:12:51 -0500200 void writeStatement(const Statement& s);
201 void writeBlock(const Block& b);
Brian Osman9333c872021-01-13 15:06:17 -0500202 void writeBreakStatement();
203 void writeContinueStatement();
204 void writeForStatement(const ForStatement& f);
Brian Osman0a442b72020-12-02 11:12:51 -0500205 void writeIfStatement(const IfStatement& stmt);
206 void writeReturnStatement(const ReturnStatement& r);
207 void writeVarDeclaration(const VarDeclaration& decl);
208
209 Value writeStore(const Expression& lhs, const Value& rhs);
210
211 Value writeMatrixInverse2x2(const Value& m);
212 Value writeMatrixInverse3x3(const Value& m);
213 Value writeMatrixInverse4x4(const Value& m);
214
Brian Osmandb2dad52021-01-07 14:08:30 -0500215 //
216 // Global state for the lifetime of the generator:
217 //
Brian Osman0a442b72020-12-02 11:12:51 -0500218 const Program& fProgram;
Brian Osman0a442b72020-12-02 11:12:51 -0500219 skvm::Builder* fBuilder;
220
Brian Osman0a442b72020-12-02 11:12:51 -0500221 const skvm::Coord fLocalCoord;
John Stiles137482f2021-07-23 10:38:57 -0400222 const SampleShaderFn fSampleShader;
223 const SampleColorFilterFn fSampleColorFilter;
John Stiles2955c262021-07-23 15:51:05 -0400224 const SampleBlenderFn fSampleBlender;
Brian Osman0a442b72020-12-02 11:12:51 -0500225
226 // [Variable, first slot in fSlots]
Brian Osman21f57072021-01-25 13:51:57 -0500227 std::unordered_map<const Variable*, size_t> fVariableMap;
Brian Osmandb2dad52021-01-07 14:08:30 -0500228 std::vector<skvm::Val> fSlots;
Brian Osman0a442b72020-12-02 11:12:51 -0500229
Brian Osman9333c872021-01-13 15:06:17 -0500230 // Conditional execution mask (managed by ScopedCondition, and tied to control-flow scopes)
231 skvm::I32 fConditionMask;
232
233 // Similar: loop execution masks. Each loop starts with all lanes active (fLoopMask).
234 // 'break' disables a lane in fLoopMask until the loop finishes
235 // 'continue' disables a lane in fLoopMask, and sets fContinueMask to be re-enabled on the next
236 // iteration
237 skvm::I32 fLoopMask;
238 skvm::I32 fContinueMask;
Brian Osman54515b72021-01-07 14:38:08 -0500239
Brian Osmandb2dad52021-01-07 14:08:30 -0500240 //
241 // State that's local to the generation of a single function:
242 //
Brian Osman54515b72021-01-07 14:38:08 -0500243 struct Function {
244 const SkSpan<skvm::Val> fReturnValue;
245 skvm::I32 fReturned;
246 };
247 std::vector<Function> fFunctionStack;
248 Function& currentFunction() { return fFunctionStack.back(); }
Brian Osman0a442b72020-12-02 11:12:51 -0500249
Brian Osman9333c872021-01-13 15:06:17 -0500250 class ScopedCondition {
Brian Osman0a442b72020-12-02 11:12:51 -0500251 public:
Brian Osman9333c872021-01-13 15:06:17 -0500252 ScopedCondition(SkVMGenerator* generator, skvm::I32 mask)
253 : fGenerator(generator), fOldConditionMask(fGenerator->fConditionMask) {
254 fGenerator->fConditionMask &= mask;
Brian Osman0a442b72020-12-02 11:12:51 -0500255 }
256
Brian Osman9333c872021-01-13 15:06:17 -0500257 ~ScopedCondition() { fGenerator->fConditionMask = fOldConditionMask; }
Brian Osman0a442b72020-12-02 11:12:51 -0500258
259 private:
260 SkVMGenerator* fGenerator;
Brian Osman9333c872021-01-13 15:06:17 -0500261 skvm::I32 fOldConditionMask;
Brian Osman0a442b72020-12-02 11:12:51 -0500262 };
263};
264
265static Type::NumberKind base_number_kind(const Type& type) {
266 if (type.typeKind() == Type::TypeKind::kMatrix || type.typeKind() == Type::TypeKind::kVector) {
267 return base_number_kind(type.componentType());
268 }
269 return type.numberKind();
270}
271
272static inline bool is_uniform(const SkSL::Variable& var) {
273 return var.modifiers().fFlags & Modifiers::kUniform_Flag;
274}
275
Brian Osman0a442b72020-12-02 11:12:51 -0500276SkVMGenerator::SkVMGenerator(const Program& program,
Brian Osman0a442b72020-12-02 11:12:51 -0500277 skvm::Builder* builder,
278 SkSpan<skvm::Val> uniforms,
Brian Osman0a442b72020-12-02 11:12:51 -0500279 skvm::Coord device,
280 skvm::Coord local,
John Stiles137482f2021-07-23 10:38:57 -0400281 SampleShaderFn sampleShader,
John Stiles2955c262021-07-23 15:51:05 -0400282 SampleColorFilterFn sampleColorFilter,
283 SampleBlenderFn sampleBlender)
Brian Osman0a442b72020-12-02 11:12:51 -0500284 : fProgram(program)
Brian Osman0a442b72020-12-02 11:12:51 -0500285 , fBuilder(builder)
286 , fLocalCoord(local)
John Stiles137482f2021-07-23 10:38:57 -0400287 , fSampleShader(std::move(sampleShader))
John Stiles2955c262021-07-23 15:51:05 -0400288 , fSampleColorFilter(std::move(sampleColorFilter))
289 , fSampleBlender(std::move(sampleBlender)) {
Brian Osman9333c872021-01-13 15:06:17 -0500290 fConditionMask = fLoopMask = fBuilder->splat(0xffff'ffff);
Brian Osman0a442b72020-12-02 11:12:51 -0500291
292 // Now, add storage for each global variable (including uniforms) to fSlots, and entries in
293 // fVariableMap to remember where every variable is stored.
294 const skvm::Val* uniformIter = uniforms.begin();
295 size_t fpCount = 0;
296 for (const ProgramElement* e : fProgram.elements()) {
297 if (e->is<GlobalVarDeclaration>()) {
Brian Osmanc0576692021-02-17 13:52:35 -0500298 const GlobalVarDeclaration& gvd = e->as<GlobalVarDeclaration>();
299 const VarDeclaration& decl = gvd.declaration()->as<VarDeclaration>();
300 const Variable& var = decl.var();
Brian Osman0a442b72020-12-02 11:12:51 -0500301 SkASSERT(fVariableMap.find(&var) == fVariableMap.end());
302
Brian Osman14d00962021-04-02 17:04:35 -0400303 // For most variables, fVariableMap stores an index into fSlots, but for children,
John Stiles2955c262021-07-23 15:51:05 -0400304 // fVariableMap stores the index to pass to fSample(Shader|ColorFilter|Blender)
Brian Osman14d00962021-04-02 17:04:35 -0400305 if (var.type().isEffectChild()) {
Brian Osman0a442b72020-12-02 11:12:51 -0500306 fVariableMap[&var] = fpCount++;
307 continue;
308 }
309
310 // Opaque types include fragment processors, GL objects (samplers, textures, etc), and
311 // special types like 'void'. Of those, only fragment processors are legal variables.
312 SkASSERT(!var.type().isOpaque());
313
Brian Osmanc0576692021-02-17 13:52:35 -0500314 // getSlot() allocates space for the variable's value in fSlots, initializes it to zero,
315 // and populates fVariableMap.
316 size_t slot = this->getSlot(var),
John Stiles47b087e2021-04-06 13:19:35 -0400317 nslots = var.type().slotCount();
Brian Osman0a442b72020-12-02 11:12:51 -0500318
319 if (int builtin = var.modifiers().fLayout.fBuiltin; builtin >= 0) {
320 // builtin variables are system-defined, with special semantics. The only builtin
321 // variable exposed to runtime effects is sk_FragCoord.
322 switch (builtin) {
323 case SK_FRAGCOORD_BUILTIN:
324 SkASSERT(nslots == 4);
Brian Osmanc0576692021-02-17 13:52:35 -0500325 fSlots[slot + 0] = device.x.id;
326 fSlots[slot + 1] = device.y.id;
327 fSlots[slot + 2] = fBuilder->splat(0.0f).id;
328 fSlots[slot + 3] = fBuilder->splat(1.0f).id;
Brian Osman0a442b72020-12-02 11:12:51 -0500329 break;
330 default:
331 SkDEBUGFAIL("Unsupported builtin");
332 }
333 } else if (is_uniform(var)) {
334 // For uniforms, copy the supplied IDs over
335 SkASSERT(uniformIter + nslots <= uniforms.end());
Brian Osmanc0576692021-02-17 13:52:35 -0500336 std::copy(uniformIter, uniformIter + nslots, fSlots.begin() + slot);
Brian Osman0a442b72020-12-02 11:12:51 -0500337 uniformIter += nslots;
Brian Osmanc0576692021-02-17 13:52:35 -0500338 } else if (decl.value()) {
339 // For other globals, populate with the initializer expression (if there is one)
340 Value val = this->writeExpression(*decl.value());
341 for (size_t i = 0; i < nslots; ++i) {
342 fSlots[slot + i] = val[i];
343 }
Brian Osman0a442b72020-12-02 11:12:51 -0500344 }
345 }
346 }
347 SkASSERT(uniformIter == uniforms.end());
Brian Osman0a442b72020-12-02 11:12:51 -0500348}
349
Brian Osmandb2dad52021-01-07 14:08:30 -0500350void SkVMGenerator::writeFunction(const FunctionDefinition& function,
351 SkSpan<skvm::Val> arguments,
352 SkSpan<skvm::Val> outReturn) {
Brian Osmandb2dad52021-01-07 14:08:30 -0500353 const FunctionDeclaration& decl = function.declaration();
John Stiles47b087e2021-04-06 13:19:35 -0400354 SkASSERT(decl.returnType().slotCount() == outReturn.size());
Brian Osmandb2dad52021-01-07 14:08:30 -0500355
Brian Osman54515b72021-01-07 14:38:08 -0500356 fFunctionStack.push_back({outReturn, /*returned=*/fBuilder->splat(0)});
Brian Osmandb2dad52021-01-07 14:08:30 -0500357
358 // For all parameters, copy incoming argument IDs to our vector of (all) variable IDs
Brian Osman5933d4c2021-01-05 13:02:20 -0500359 size_t argIdx = 0;
Brian Osmandb2dad52021-01-07 14:08:30 -0500360 for (const Variable* p : decl.parameters()) {
Brian Osman21f57072021-01-25 13:51:57 -0500361 size_t paramSlot = this->getSlot(*p),
John Stiles47b087e2021-04-06 13:19:35 -0400362 nslots = p->type().slotCount();
Brian Osman5933d4c2021-01-05 13:02:20 -0500363
Brian Osmandb2dad52021-01-07 14:08:30 -0500364 for (size_t i = 0; i < nslots; ++i) {
365 fSlots[paramSlot + i] = arguments[argIdx + i];
366 }
367 argIdx += nslots;
368 }
369 SkASSERT(argIdx == arguments.size());
370
371 this->writeStatement(*function.body());
372
373 // Copy 'out' and 'inout' parameters back to their caller-supplied argument storage
374 argIdx = 0;
375 for (const Variable* p : decl.parameters()) {
John Stiles47b087e2021-04-06 13:19:35 -0400376 size_t nslots = p->type().slotCount();
Brian Osmandb2dad52021-01-07 14:08:30 -0500377
Brian Osman5933d4c2021-01-05 13:02:20 -0500378 if (p->modifiers().fFlags & Modifiers::kOut_Flag) {
Brian Osman21f57072021-01-25 13:51:57 -0500379 size_t paramSlot = this->getSlot(*p);
Brian Osman5933d4c2021-01-05 13:02:20 -0500380 for (size_t i = 0; i < nslots; ++i) {
Brian Osmandb2dad52021-01-07 14:08:30 -0500381 arguments[argIdx + i] = fSlots[paramSlot + i];
Brian Osman5933d4c2021-01-05 13:02:20 -0500382 }
383 }
384 argIdx += nslots;
385 }
Brian Osmandb2dad52021-01-07 14:08:30 -0500386 SkASSERT(argIdx == arguments.size());
Brian Osman54515b72021-01-07 14:38:08 -0500387
388 fFunctionStack.pop_back();
Brian Osman0a442b72020-12-02 11:12:51 -0500389}
390
Brian Osman21f57072021-01-25 13:51:57 -0500391size_t SkVMGenerator::getSlot(const Variable& v) {
Brian Osman0a442b72020-12-02 11:12:51 -0500392 auto entry = fVariableMap.find(&v);
393 if (entry != fVariableMap.end()) {
394 return entry->second;
395 }
396
Brian Osman0a442b72020-12-02 11:12:51 -0500397 size_t slot = fSlots.size(),
John Stiles47b087e2021-04-06 13:19:35 -0400398 nslots = v.type().slotCount();
Brian Osman0a442b72020-12-02 11:12:51 -0500399 fSlots.resize(slot + nslots, fBuilder->splat(0.0f).id);
400 fVariableMap[&v] = slot;
401 return slot;
402}
403
Brian Osman0a442b72020-12-02 11:12:51 -0500404Value SkVMGenerator::writeBinaryExpression(const BinaryExpression& b) {
405 const Expression& left = *b.left();
406 const Expression& right = *b.right();
John Stiles45990502021-02-16 10:55:27 -0500407 Operator op = b.getOperator();
408 if (op.kind() == Token::Kind::TK_EQ) {
Brian Osman0a442b72020-12-02 11:12:51 -0500409 return this->writeStore(left, this->writeExpression(right));
410 }
411
412 const Type& lType = left.type();
413 const Type& rType = right.type();
414 bool lVecOrMtx = (lType.isVector() || lType.isMatrix());
415 bool rVecOrMtx = (rType.isVector() || rType.isMatrix());
John Stiles45990502021-02-16 10:55:27 -0500416 bool isAssignment = op.isAssignment();
Brian Osman0a442b72020-12-02 11:12:51 -0500417 if (isAssignment) {
John Stiles45990502021-02-16 10:55:27 -0500418 op = op.removeAssignment();
Brian Osman0a442b72020-12-02 11:12:51 -0500419 }
420 Type::NumberKind nk = base_number_kind(lType);
421
422 // A few ops require special treatment:
John Stiles45990502021-02-16 10:55:27 -0500423 switch (op.kind()) {
Brian Osman0a442b72020-12-02 11:12:51 -0500424 case Token::Kind::TK_LOGICALAND: {
425 SkASSERT(!isAssignment);
426 SkASSERT(nk == Type::NumberKind::kBoolean);
427 skvm::I32 lVal = i32(this->writeExpression(left));
Brian Osman9333c872021-01-13 15:06:17 -0500428 ScopedCondition shortCircuit(this, lVal);
Brian Osman0a442b72020-12-02 11:12:51 -0500429 skvm::I32 rVal = i32(this->writeExpression(right));
430 return lVal & rVal;
431 }
432 case Token::Kind::TK_LOGICALOR: {
433 SkASSERT(!isAssignment);
434 SkASSERT(nk == Type::NumberKind::kBoolean);
435 skvm::I32 lVal = i32(this->writeExpression(left));
Brian Osman9333c872021-01-13 15:06:17 -0500436 ScopedCondition shortCircuit(this, ~lVal);
Brian Osman0a442b72020-12-02 11:12:51 -0500437 skvm::I32 rVal = i32(this->writeExpression(right));
438 return lVal | rVal;
439 }
John Stiles94e72b92021-01-30 11:06:18 -0500440 case Token::Kind::TK_COMMA:
441 // We write the left side of the expression to preserve its side effects, even though we
442 // immediately discard the result.
443 this->writeExpression(left);
444 return this->writeExpression(right);
Brian Osman0a442b72020-12-02 11:12:51 -0500445 default:
446 break;
447 }
448
449 // All of the other ops always evaluate both sides of the expression
450 Value lVal = this->writeExpression(left),
451 rVal = this->writeExpression(right);
452
453 // Special case for M*V, V*M, M*M (but not V*V!)
John Stiles45990502021-02-16 10:55:27 -0500454 if (op.kind() == Token::Kind::TK_STAR
Brian Osman0a442b72020-12-02 11:12:51 -0500455 && lVecOrMtx && rVecOrMtx && !(lType.isVector() && rType.isVector())) {
456 int rCols = rType.columns(),
457 rRows = rType.rows(),
458 lCols = lType.columns(),
459 lRows = lType.rows();
460 // M*V treats the vector as a column
461 if (rType.isVector()) {
462 std::swap(rCols, rRows);
463 }
464 SkASSERT(lCols == rRows);
John Stiles47b087e2021-04-06 13:19:35 -0400465 SkASSERT(b.type().slotCount() == static_cast<size_t>(lRows * rCols));
Brian Osman0a442b72020-12-02 11:12:51 -0500466 Value result(lRows * rCols);
467 size_t resultIdx = 0;
468 for (int c = 0; c < rCols; ++c)
469 for (int r = 0; r < lRows; ++r) {
470 skvm::F32 sum = fBuilder->splat(0.0f);
471 for (int j = 0; j < lCols; ++j) {
472 sum += f32(lVal[j*lRows + r]) * f32(rVal[c*rRows + j]);
473 }
474 result[resultIdx++] = sum;
475 }
476 SkASSERT(resultIdx == result.slots());
477 return isAssignment ? this->writeStore(left, result) : result;
478 }
479
480 size_t nslots = std::max(lVal.slots(), rVal.slots());
481
Brian Osman0a442b72020-12-02 11:12:51 -0500482 auto binary = [&](auto&& f_fn, auto&& i_fn) {
483 Value result(nslots);
484 for (size_t i = 0; i < nslots; ++i) {
485 // If one side is scalar, replicate it to all channels
486 skvm::Val L = lVal.slots() == 1 ? lVal[0] : lVal[i],
487 R = rVal.slots() == 1 ? rVal[0] : rVal[i];
488 if (nk == Type::NumberKind::kFloat) {
489 result[i] = f_fn(f32(L), f32(R));
490 } else {
491 result[i] = i_fn(i32(L), i32(R));
492 }
493 }
494 return isAssignment ? this->writeStore(left, result) : result;
495 };
496
497 auto unsupported_f = [&](skvm::F32, skvm::F32) {
498 SkDEBUGFAIL("Unsupported operator");
499 return skvm::F32{};
500 };
501
John Stiles45990502021-02-16 10:55:27 -0500502 switch (op.kind()) {
Brian Osman0a442b72020-12-02 11:12:51 -0500503 case Token::Kind::TK_EQEQ: {
504 SkASSERT(!isAssignment);
505 Value cmp = binary([](skvm::F32 x, skvm::F32 y) { return x == y; },
506 [](skvm::I32 x, skvm::I32 y) { return x == y; });
507 skvm::I32 folded = i32(cmp[0]);
508 for (size_t i = 1; i < nslots; ++i) {
509 folded &= i32(cmp[i]);
510 }
511 return folded;
512 }
513 case Token::Kind::TK_NEQ: {
514 SkASSERT(!isAssignment);
515 Value cmp = binary([](skvm::F32 x, skvm::F32 y) { return x != y; },
516 [](skvm::I32 x, skvm::I32 y) { return x != y; });
517 skvm::I32 folded = i32(cmp[0]);
518 for (size_t i = 1; i < nslots; ++i) {
519 folded |= i32(cmp[i]);
520 }
521 return folded;
522 }
523 case Token::Kind::TK_GT:
524 return binary([](skvm::F32 x, skvm::F32 y) { return x > y; },
525 [](skvm::I32 x, skvm::I32 y) { return x > y; });
526 case Token::Kind::TK_GTEQ:
527 return binary([](skvm::F32 x, skvm::F32 y) { return x >= y; },
528 [](skvm::I32 x, skvm::I32 y) { return x >= y; });
529 case Token::Kind::TK_LT:
530 return binary([](skvm::F32 x, skvm::F32 y) { return x < y; },
531 [](skvm::I32 x, skvm::I32 y) { return x < y; });
532 case Token::Kind::TK_LTEQ:
533 return binary([](skvm::F32 x, skvm::F32 y) { return x <= y; },
534 [](skvm::I32 x, skvm::I32 y) { return x <= y; });
535
536 case Token::Kind::TK_PLUS:
537 return binary([](skvm::F32 x, skvm::F32 y) { return x + y; },
538 [](skvm::I32 x, skvm::I32 y) { return x + y; });
539 case Token::Kind::TK_MINUS:
540 return binary([](skvm::F32 x, skvm::F32 y) { return x - y; },
541 [](skvm::I32 x, skvm::I32 y) { return x - y; });
542 case Token::Kind::TK_STAR:
Mike Kleinff4decc2021-02-10 16:13:35 -0600543 return binary([](skvm::F32 x, skvm::F32 y) { return x ** y; },
Brian Osman0a442b72020-12-02 11:12:51 -0500544 [](skvm::I32 x, skvm::I32 y) { return x * y; });
545 case Token::Kind::TK_SLASH:
546 // Minimum spec (GLSL ES 1.0) has very loose requirements for integer operations.
547 // (Low-end GPUs may not have integer ALUs). Given that, we are allowed to do floating
548 // point division plus rounding. Section 10.28 of the spec even clarifies that the
549 // rounding mode is undefined (but round-towards-zero is the obvious/common choice).
550 return binary([](skvm::F32 x, skvm::F32 y) { return x / y; },
551 [](skvm::I32 x, skvm::I32 y) {
552 return skvm::trunc(skvm::to_F32(x) / skvm::to_F32(y));
553 });
554
555 case Token::Kind::TK_BITWISEXOR:
556 case Token::Kind::TK_LOGICALXOR:
557 return binary(unsupported_f, [](skvm::I32 x, skvm::I32 y) { return x ^ y; });
558 case Token::Kind::TK_BITWISEAND:
559 return binary(unsupported_f, [](skvm::I32 x, skvm::I32 y) { return x & y; });
560 case Token::Kind::TK_BITWISEOR:
561 return binary(unsupported_f, [](skvm::I32 x, skvm::I32 y) { return x | y; });
562
563 // These three operators are all 'reserved' (illegal) in our minimum spec, but will require
564 // implementation in the future.
565 case Token::Kind::TK_PERCENT:
566 case Token::Kind::TK_SHL:
567 case Token::Kind::TK_SHR:
568 default:
569 SkDEBUGFAIL("Unsupported operator");
570 return {};
571 }
572}
573
John Stilesd986f472021-04-06 15:54:43 -0400574Value SkVMGenerator::writeAggregationConstructor(const AnyConstructor& c) {
John Stiles47b087e2021-04-06 13:19:35 -0400575 Value result(c.type().slotCount());
John Stiles626b62e2021-03-31 22:06:07 -0400576 size_t resultIdx = 0;
John Stilesd986f472021-04-06 15:54:43 -0400577 for (const auto &arg : c.argumentSpan()) {
John Stiles626b62e2021-03-31 22:06:07 -0400578 Value tmp = this->writeExpression(*arg);
579 for (size_t tmpSlot = 0; tmpSlot < tmp.slots(); ++tmpSlot) {
580 result[resultIdx++] = tmp[tmpSlot];
581 }
582 }
583 return result;
584}
585
John Stilesfd7252f2021-04-04 22:24:40 -0400586Value SkVMGenerator::writeTypeConversion(const Value& src,
587 Type::NumberKind srcKind,
588 Type::NumberKind dstKind) {
589 // Conversion among "similar" types (floatN <-> halfN), (shortN <-> intN), etc. is a no-op.
590 if (srcKind == dstKind) {
591 return src;
592 }
593
594 // TODO: Handle signed vs. unsigned. GLSL ES 1.0 only has 'int', so no problem yet.
595 Value dst(src.slots());
596 switch (dstKind) {
597 case Type::NumberKind::kFloat:
598 if (srcKind == Type::NumberKind::kSigned) {
599 // int -> float
600 for (size_t i = 0; i < src.slots(); ++i) {
601 dst[i] = skvm::to_F32(i32(src[i]));
602 }
603 return dst;
604 }
605 if (srcKind == Type::NumberKind::kBoolean) {
606 // bool -> float
607 for (size_t i = 0; i < src.slots(); ++i) {
608 dst[i] = skvm::select(i32(src[i]), 1.0f, 0.0f);
609 }
610 return dst;
611 }
612 break;
613
614 case Type::NumberKind::kSigned:
615 if (srcKind == Type::NumberKind::kFloat) {
616 // float -> int
617 for (size_t i = 0; i < src.slots(); ++i) {
618 dst[i] = skvm::trunc(f32(src[i]));
619 }
620 return dst;
621 }
622 if (srcKind == Type::NumberKind::kBoolean) {
623 // bool -> int
624 for (size_t i = 0; i < src.slots(); ++i) {
625 dst[i] = skvm::select(i32(src[i]), 1, 0);
626 }
627 return dst;
628 }
629 break;
630
631 case Type::NumberKind::kBoolean:
632 if (srcKind == Type::NumberKind::kSigned) {
633 // int -> bool
634 for (size_t i = 0; i < src.slots(); ++i) {
635 dst[i] = i32(src[i]) != 0;
636 }
637 return dst;
638 }
639 if (srcKind == Type::NumberKind::kFloat) {
640 // float -> bool
641 for (size_t i = 0; i < src.slots(); ++i) {
642 dst[i] = f32(src[i]) != 0.0;
643 }
644 return dst;
645 }
646 break;
647
648 default:
649 break;
650 }
John Stiles7bf79992021-06-25 11:05:20 -0400651 SkDEBUGFAILF("Unsupported type conversion: %d -> %d", (int)srcKind, (int)dstKind);
John Stilesfd7252f2021-04-04 22:24:40 -0400652 return {};
653}
654
John Stilesb14a8192021-04-05 11:40:46 -0400655Value SkVMGenerator::writeConstructorCast(const AnyConstructor& c) {
656 auto arguments = c.argumentSpan();
657 SkASSERT(arguments.size() == 1);
658 const Expression& argument = *arguments.front();
659
660 const Type& srcType = argument.type();
John Stilesfd7252f2021-04-04 22:24:40 -0400661 const Type& dstType = c.type();
662 Type::NumberKind srcKind = base_number_kind(srcType);
663 Type::NumberKind dstKind = base_number_kind(dstType);
John Stilesb14a8192021-04-05 11:40:46 -0400664 Value src = this->writeExpression(argument);
John Stilesfd7252f2021-04-04 22:24:40 -0400665 return this->writeTypeConversion(src, srcKind, dstKind);
666}
667
John Stiles2938eea2021-04-01 18:58:25 -0400668Value SkVMGenerator::writeConstructorSplat(const ConstructorSplat& c) {
669 SkASSERT(c.type().isVector());
670 SkASSERT(c.argument()->type().isScalar());
671 int columns = c.type().columns();
672
673 // Splat the argument across all components of a vector.
674 Value src = this->writeExpression(*c.argument());
675 Value dst(columns);
676 for (int i = 0; i < columns; ++i) {
677 dst[i] = src[0];
678 }
679 return dst;
680}
681
John Stilese1182782021-03-30 22:09:37 -0400682Value SkVMGenerator::writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c) {
683 const Type& dstType = c.type();
684 SkASSERT(dstType.isMatrix());
685 SkASSERT(c.argument()->type() == dstType.componentType());
686
687 Value src = this->writeExpression(*c.argument());
688 Value dst(dstType.rows() * dstType.columns());
689 size_t dstIndex = 0;
690
691 // Matrix-from-scalar builds a diagonal scale matrix
692 for (int c = 0; c < dstType.columns(); ++c) {
693 for (int r = 0; r < dstType.rows(); ++r) {
694 dst[dstIndex++] = (c == r ? f32(src) : fBuilder->splat(0.0f));
695 }
696 }
697
698 SkASSERT(dstIndex == dst.slots());
699 return dst;
700}
701
John Stiles5abb9e12021-04-06 13:47:19 -0400702Value SkVMGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c) {
703 const Type& srcType = c.argument()->type();
704 const Type& dstType = c.type();
705 Value src = this->writeExpression(*c.argument());
706 Value dst(dstType.rows() * dstType.columns());
707
708 // Matrix-from-matrix uses src where it overlaps, and fills in missing fields with identity.
709 size_t dstIndex = 0;
710 for (int c = 0; c < dstType.columns(); ++c) {
711 for (int r = 0; r < dstType.rows(); ++r) {
712 if (c < srcType.columns() && r < srcType.rows()) {
713 dst[dstIndex++] = src[c * srcType.rows() + r];
714 } else {
715 dst[dstIndex++] = fBuilder->splat(c == r ? 1.0f : 0.0f);
716 }
717 }
718 }
719
720 SkASSERT(dstIndex == dst.slots());
721 return dst;
722}
723
Brian Osmanfa71ffa2021-01-26 14:05:31 -0500724size_t SkVMGenerator::fieldSlotOffset(const FieldAccess& expr) {
Brian Osman21f57072021-01-25 13:51:57 -0500725 size_t offset = 0;
Brian Osmanfa71ffa2021-01-26 14:05:31 -0500726 for (int i = 0; i < expr.fieldIndex(); ++i) {
John Stiles47b087e2021-04-06 13:19:35 -0400727 offset += (*expr.base()->type().fields()[i].fType).slotCount();
Brian Osmanfa71ffa2021-01-26 14:05:31 -0500728 }
729 return offset;
730}
731
732Value SkVMGenerator::writeFieldAccess(const FieldAccess& expr) {
733 Value base = this->writeExpression(*expr.base());
John Stiles47b087e2021-04-06 13:19:35 -0400734 Value field(expr.type().slotCount());
Brian Osmanfa71ffa2021-01-26 14:05:31 -0500735 size_t offset = this->fieldSlotOffset(expr);
736 for (size_t i = 0; i < field.slots(); ++i) {
737 field[i] = base[offset + i];
738 }
739 return field;
740}
741
742size_t SkVMGenerator::indexSlotOffset(const IndexExpression& expr) {
743 Value index = this->writeExpression(*expr.index());
744 int indexValue = -1;
745 SkAssertResult(fBuilder->allImm(index[0], &indexValue));
746
747 // When indexing by a literal, the front-end guarantees that we don't go out of bounds.
748 // But when indexing by a loop variable, it's possible to generate out-of-bounds access.
749 // The GLSL spec leaves that behavior undefined - we'll just clamp everything here.
750 indexValue = SkTPin(indexValue, 0, expr.base()->type().columns() - 1);
751
John Stiles47b087e2021-04-06 13:19:35 -0400752 size_t stride = expr.type().slotCount();
Brian Osmanfa71ffa2021-01-26 14:05:31 -0500753 return indexValue * stride;
754}
755
756Value SkVMGenerator::writeIndexExpression(const IndexExpression& expr) {
757 Value base = this->writeExpression(*expr.base());
John Stiles47b087e2021-04-06 13:19:35 -0400758 Value element(expr.type().slotCount());
Brian Osmanfa71ffa2021-01-26 14:05:31 -0500759 size_t offset = this->indexSlotOffset(expr);
760 for (size_t i = 0; i < element.slots(); ++i) {
761 element[i] = base[offset + i];
762 }
763 return element;
764}
765
766Value SkVMGenerator::writeVariableExpression(const VariableReference& expr) {
Brian Osman21f57072021-01-25 13:51:57 -0500767 size_t slot = this->getSlot(*expr.variable());
John Stiles47b087e2021-04-06 13:19:35 -0400768 Value val(expr.type().slotCount());
Brian Osman0a442b72020-12-02 11:12:51 -0500769 for (size_t i = 0; i < val.slots(); ++i) {
770 val[i] = fSlots[slot + i];
771 }
772 return val;
773}
774
775Value SkVMGenerator::writeMatrixInverse2x2(const Value& m) {
776 SkASSERT(m.slots() == 4);
777 skvm::F32 a = f32(m[0]),
778 b = f32(m[1]),
779 c = f32(m[2]),
780 d = f32(m[3]);
781 skvm::F32 idet = 1.0f / (a*d - b*c);
782
783 Value result(m.slots());
Mike Kleinff4decc2021-02-10 16:13:35 -0600784 result[0] = ( d ** idet);
785 result[1] = (-b ** idet);
786 result[2] = (-c ** idet);
787 result[3] = ( a ** idet);
Brian Osman0a442b72020-12-02 11:12:51 -0500788 return result;
789}
790
791Value SkVMGenerator::writeMatrixInverse3x3(const Value& m) {
792 SkASSERT(m.slots() == 9);
793 skvm::F32 a11 = f32(m[0]), a12 = f32(m[3]), a13 = f32(m[6]),
794 a21 = f32(m[1]), a22 = f32(m[4]), a23 = f32(m[7]),
795 a31 = f32(m[2]), a32 = f32(m[5]), a33 = f32(m[8]);
796 skvm::F32 idet = 1.0f / (a11*a22*a33 + a12*a23*a31 + a13*a21*a32 -
797 a11*a23*a32 - a12*a21*a33 - a13*a22*a31);
798
799 Value result(m.slots());
Mike Kleinff4decc2021-02-10 16:13:35 -0600800 result[0] = ((a22**a33 - a23**a32) ** idet);
801 result[1] = ((a23**a31 - a21**a33) ** idet);
802 result[2] = ((a21**a32 - a22**a31) ** idet);
803 result[3] = ((a13**a32 - a12**a33) ** idet);
804 result[4] = ((a11**a33 - a13**a31) ** idet);
805 result[5] = ((a12**a31 - a11**a32) ** idet);
806 result[6] = ((a12**a23 - a13**a22) ** idet);
807 result[7] = ((a13**a21 - a11**a23) ** idet);
808 result[8] = ((a11**a22 - a12**a21) ** idet);
Brian Osman0a442b72020-12-02 11:12:51 -0500809 return result;
810}
811
812Value SkVMGenerator::writeMatrixInverse4x4(const Value& m) {
813 SkASSERT(m.slots() == 16);
814 skvm::F32 a00 = f32(m[0]), a10 = f32(m[4]), a20 = f32(m[ 8]), a30 = f32(m[12]),
815 a01 = f32(m[1]), a11 = f32(m[5]), a21 = f32(m[ 9]), a31 = f32(m[13]),
816 a02 = f32(m[2]), a12 = f32(m[6]), a22 = f32(m[10]), a32 = f32(m[14]),
817 a03 = f32(m[3]), a13 = f32(m[7]), a23 = f32(m[11]), a33 = f32(m[15]);
818
Mike Kleinff4decc2021-02-10 16:13:35 -0600819 skvm::F32 b00 = a00**a11 - a01**a10,
820 b01 = a00**a12 - a02**a10,
821 b02 = a00**a13 - a03**a10,
822 b03 = a01**a12 - a02**a11,
823 b04 = a01**a13 - a03**a11,
824 b05 = a02**a13 - a03**a12,
825 b06 = a20**a31 - a21**a30,
826 b07 = a20**a32 - a22**a30,
827 b08 = a20**a33 - a23**a30,
828 b09 = a21**a32 - a22**a31,
829 b10 = a21**a33 - a23**a31,
830 b11 = a22**a33 - a23**a32;
Brian Osman0a442b72020-12-02 11:12:51 -0500831
Mike Kleinff4decc2021-02-10 16:13:35 -0600832 skvm::F32 idet = 1.0f / (b00**b11 - b01**b10 + b02**b09 + b03**b08 - b04**b07 + b05**b06);
Brian Osman0a442b72020-12-02 11:12:51 -0500833
834 b00 *= idet;
835 b01 *= idet;
836 b02 *= idet;
837 b03 *= idet;
838 b04 *= idet;
839 b05 *= idet;
840 b06 *= idet;
841 b07 *= idet;
842 b08 *= idet;
843 b09 *= idet;
844 b10 *= idet;
845 b11 *= idet;
846
847 Value result(m.slots());
848 result[ 0] = (a11*b11 - a12*b10 + a13*b09);
849 result[ 1] = (a02*b10 - a01*b11 - a03*b09);
850 result[ 2] = (a31*b05 - a32*b04 + a33*b03);
851 result[ 3] = (a22*b04 - a21*b05 - a23*b03);
852 result[ 4] = (a12*b08 - a10*b11 - a13*b07);
853 result[ 5] = (a00*b11 - a02*b08 + a03*b07);
854 result[ 6] = (a32*b02 - a30*b05 - a33*b01);
855 result[ 7] = (a20*b05 - a22*b02 + a23*b01);
856 result[ 8] = (a10*b10 - a11*b08 + a13*b06);
857 result[ 9] = (a01*b08 - a00*b10 - a03*b06);
858 result[10] = (a30*b04 - a31*b02 + a33*b00);
859 result[11] = (a21*b02 - a20*b04 - a23*b00);
860 result[12] = (a11*b07 - a10*b09 - a12*b06);
861 result[13] = (a00*b09 - a01*b07 + a02*b06);
862 result[14] = (a31*b01 - a30*b03 - a32*b00);
863 result[15] = (a20*b03 - a21*b01 + a22*b00);
864 return result;
865}
866
867Value SkVMGenerator::writeIntrinsicCall(const FunctionCall& c) {
John Stiles032fcba2021-05-06 11:33:08 -0400868 IntrinsicKind intrinsicKind = c.function().intrinsicKind();
869 SkASSERT(intrinsicKind != kNotIntrinsic);
Brian Osman0a442b72020-12-02 11:12:51 -0500870
871 const size_t nargs = c.arguments().size();
872
John Stiles032fcba2021-05-06 11:33:08 -0400873 if (intrinsicKind == k_sample_IntrinsicKind) {
John Stilesbb2ef922021-07-26 08:32:07 -0400874 // Sample is very special. The first argument is a child (shader/colorFilter/blender),
875 // which is opaque and can't be evaluated.
John Stilesce9a5c92021-07-30 11:20:19 -0400876 SkASSERT(nargs >= 2);
Brian Osmanc9125aa2021-04-21 09:57:19 -0400877 const Expression* child = c.arguments()[0].get();
878 SkASSERT(child->type().isEffectChild());
879 SkASSERT(child->is<VariableReference>());
Brian Osman0a442b72020-12-02 11:12:51 -0500880
Brian Osmanc9125aa2021-04-21 09:57:19 -0400881 auto fp_it = fVariableMap.find(child->as<VariableReference>().variable());
Greg Danielc2cca5a2021-05-04 13:36:16 +0000882 SkASSERT(fp_it != fVariableMap.end());
883
Brian Osmanc9125aa2021-04-21 09:57:19 -0400884 // Shaders require a coordinate argument. Color filters require a color argument.
885 // When we call sampleChild, the other value remains the incoming default.
Brian Osmanc9125aa2021-04-21 09:57:19 -0400886 const Expression* arg = c.arguments()[1].get();
887 Value argVal = this->writeExpression(*arg);
John Stiles137482f2021-07-23 10:38:57 -0400888 skvm::Color color;
Brian Osmanc9125aa2021-04-21 09:57:19 -0400889
John Stilesce9a5c92021-07-30 11:20:19 -0400890 switch (child->type().typeKind()) {
891 case Type::TypeKind::kShader: {
892 SkASSERT(nargs == 2);
893 SkASSERT(arg->type() == *fProgram.fContext->fTypes.fFloat2);
894 skvm::Coord coord = {f32(argVal[0]), f32(argVal[1])};
895 color = fSampleShader(fp_it->second, coord);
896 break;
897 }
898 case Type::TypeKind::kColorFilter: {
899 SkASSERT(nargs == 2);
900 SkASSERT(arg->type() == *fProgram.fContext->fTypes.fHalf4 ||
901 arg->type() == *fProgram.fContext->fTypes.fFloat4);
902 skvm::Color inColor = {f32(argVal[0]), f32(argVal[1]),
903 f32(argVal[2]), f32(argVal[3])};
904 color = fSampleColorFilter(fp_it->second, inColor);
905 break;
906 }
907 case Type::TypeKind::kBlender: {
908 SkASSERT(nargs == 3);
909 SkASSERT(arg->type() == *fProgram.fContext->fTypes.fHalf4 ||
910 arg->type() == *fProgram.fContext->fTypes.fFloat4);
911 skvm::Color srcColor = {f32(argVal[0]), f32(argVal[1]),
912 f32(argVal[2]), f32(argVal[3])};
913
914 arg = c.arguments()[2].get();
915 argVal = this->writeExpression(*arg);
916 SkASSERT(arg->type() == *fProgram.fContext->fTypes.fHalf4 ||
917 arg->type() == *fProgram.fContext->fTypes.fFloat4);
918 skvm::Color dstColor = {f32(argVal[0]), f32(argVal[1]),
919 f32(argVal[2]), f32(argVal[3])};
920
921 color = fSampleBlender(fp_it->second, srcColor, dstColor);
922 break;
923 }
924 default: {
925 SkDEBUGFAILF("cannot sample from type '%s'", child->type().description().c_str());
926 }
Greg Danielc2cca5a2021-05-04 13:36:16 +0000927 }
928
Brian Osman0a442b72020-12-02 11:12:51 -0500929 Value result(4);
930 result[0] = color.r;
931 result[1] = color.g;
932 result[2] = color.b;
933 result[3] = color.a;
934 return result;
935 }
936
937 const size_t kMaxArgs = 3; // eg: clamp, mix, smoothstep
938 Value args[kMaxArgs];
939 SkASSERT(nargs >= 1 && nargs <= SK_ARRAY_COUNT(args));
940
941 // All other intrinsics have at most three args, and those can all be evaluated up front:
942 for (size_t i = 0; i < nargs; ++i) {
943 args[i] = this->writeExpression(*c.arguments()[i]);
944 }
945 Type::NumberKind nk = base_number_kind(c.arguments()[0]->type());
946
947 auto binary = [&](auto&& fn) {
948 // Binary intrinsics are (vecN, vecN), (vecN, float), or (float, vecN)
949 size_t nslots = std::max(args[0].slots(), args[1].slots());
950 Value result(nslots);
951 SkASSERT(args[0].slots() == nslots || args[0].slots() == 1);
952 SkASSERT(args[1].slots() == nslots || args[1].slots() == 1);
953
954 for (size_t i = 0; i < nslots; ++i) {
955 result[i] = fn({fBuilder, args[0][args[0].slots() == 1 ? 0 : i]},
956 {fBuilder, args[1][args[1].slots() == 1 ? 0 : i]});
957 }
958 return result;
959 };
960
961 auto ternary = [&](auto&& fn) {
962 // Ternary intrinsics are some combination of vecN and float
963 size_t nslots = std::max({args[0].slots(), args[1].slots(), args[2].slots()});
964 Value result(nslots);
965 SkASSERT(args[0].slots() == nslots || args[0].slots() == 1);
966 SkASSERT(args[1].slots() == nslots || args[1].slots() == 1);
967 SkASSERT(args[2].slots() == nslots || args[2].slots() == 1);
968
969 for (size_t i = 0; i < nslots; ++i) {
970 result[i] = fn({fBuilder, args[0][args[0].slots() == 1 ? 0 : i]},
971 {fBuilder, args[1][args[1].slots() == 1 ? 0 : i]},
972 {fBuilder, args[2][args[2].slots() == 1 ? 0 : i]});
973 }
974 return result;
975 };
976
977 auto dot = [&](const Value& x, const Value& y) {
978 SkASSERT(x.slots() == y.slots());
979 skvm::F32 result = f32(x[0]) * f32(y[0]);
980 for (size_t i = 1; i < x.slots(); ++i) {
981 result += f32(x[i]) * f32(y[i]);
982 }
983 return result;
984 };
985
John Stiles032fcba2021-05-06 11:33:08 -0400986 switch (intrinsicKind) {
987 case k_radians_IntrinsicKind:
Brian Osman22cc3be2020-12-30 10:38:15 -0500988 return unary(args[0], [](skvm::F32 deg) { return deg * (SK_FloatPI / 180); });
John Stiles032fcba2021-05-06 11:33:08 -0400989 case k_degrees_IntrinsicKind:
Brian Osman22cc3be2020-12-30 10:38:15 -0500990 return unary(args[0], [](skvm::F32 rad) { return rad * (180 / SK_FloatPI); });
991
John Stiles032fcba2021-05-06 11:33:08 -0400992 case k_sin_IntrinsicKind: return unary(args[0], skvm::approx_sin);
993 case k_cos_IntrinsicKind: return unary(args[0], skvm::approx_cos);
994 case k_tan_IntrinsicKind: return unary(args[0], skvm::approx_tan);
Brian Osman0a442b72020-12-02 11:12:51 -0500995
John Stiles032fcba2021-05-06 11:33:08 -0400996 case k_asin_IntrinsicKind: return unary(args[0], skvm::approx_asin);
997 case k_acos_IntrinsicKind: return unary(args[0], skvm::approx_acos);
Brian Osman0a442b72020-12-02 11:12:51 -0500998
John Stiles032fcba2021-05-06 11:33:08 -0400999 case k_atan_IntrinsicKind: return nargs == 1 ? unary(args[0], skvm::approx_atan)
Brian Osman0a442b72020-12-02 11:12:51 -05001000 : binary(skvm::approx_atan2);
1001
John Stiles032fcba2021-05-06 11:33:08 -04001002 case k_pow_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001003 return binary([](skvm::F32 x, skvm::F32 y) { return skvm::approx_powf(x, y); });
John Stiles032fcba2021-05-06 11:33:08 -04001004 case k_exp_IntrinsicKind: return unary(args[0], skvm::approx_exp);
1005 case k_log_IntrinsicKind: return unary(args[0], skvm::approx_log);
1006 case k_exp2_IntrinsicKind: return unary(args[0], skvm::approx_pow2);
1007 case k_log2_IntrinsicKind: return unary(args[0], skvm::approx_log2);
Brian Osman0a442b72020-12-02 11:12:51 -05001008
John Stiles032fcba2021-05-06 11:33:08 -04001009 case k_sqrt_IntrinsicKind: return unary(args[0], skvm::sqrt);
1010 case k_inversesqrt_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001011 return unary(args[0], [](skvm::F32 x) { return 1.0f / skvm::sqrt(x); });
1012
John Stiles032fcba2021-05-06 11:33:08 -04001013 case k_abs_IntrinsicKind: return unary(args[0], skvm::abs);
1014 case k_sign_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001015 return unary(args[0], [](skvm::F32 x) { return select(x < 0, -1.0f,
1016 select(x > 0, +1.0f, 0.0f)); });
John Stiles032fcba2021-05-06 11:33:08 -04001017 case k_floor_IntrinsicKind: return unary(args[0], skvm::floor);
1018 case k_ceil_IntrinsicKind: return unary(args[0], skvm::ceil);
1019 case k_fract_IntrinsicKind: return unary(args[0], skvm::fract);
1020 case k_mod_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001021 return binary([](skvm::F32 x, skvm::F32 y) { return x - y*skvm::floor(x / y); });
1022
John Stiles032fcba2021-05-06 11:33:08 -04001023 case k_min_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001024 return binary([](skvm::F32 x, skvm::F32 y) { return skvm::min(x, y); });
John Stiles032fcba2021-05-06 11:33:08 -04001025 case k_max_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001026 return binary([](skvm::F32 x, skvm::F32 y) { return skvm::max(x, y); });
John Stiles032fcba2021-05-06 11:33:08 -04001027 case k_clamp_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001028 return ternary(
1029 [](skvm::F32 x, skvm::F32 lo, skvm::F32 hi) { return skvm::clamp(x, lo, hi); });
John Stiles032fcba2021-05-06 11:33:08 -04001030 case k_saturate_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001031 return unary(args[0], [](skvm::F32 x) { return skvm::clamp01(x); });
John Stiles032fcba2021-05-06 11:33:08 -04001032 case k_mix_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001033 return ternary(
1034 [](skvm::F32 x, skvm::F32 y, skvm::F32 t) { return skvm::lerp(x, y, t); });
John Stiles032fcba2021-05-06 11:33:08 -04001035 case k_step_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001036 return binary([](skvm::F32 edge, skvm::F32 x) { return select(x < edge, 0.0f, 1.0f); });
John Stiles032fcba2021-05-06 11:33:08 -04001037 case k_smoothstep_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001038 return ternary([](skvm::F32 edge0, skvm::F32 edge1, skvm::F32 x) {
1039 skvm::F32 t = skvm::clamp01((x - edge0) / (edge1 - edge0));
Mike Kleinff4decc2021-02-10 16:13:35 -06001040 return t ** t ** (3 - 2 ** t);
Brian Osman0a442b72020-12-02 11:12:51 -05001041 });
1042
John Stiles032fcba2021-05-06 11:33:08 -04001043 case k_length_IntrinsicKind: return skvm::sqrt(dot(args[0], args[0]));
1044 case k_distance_IntrinsicKind: {
Brian Osman0a442b72020-12-02 11:12:51 -05001045 Value vec = binary([](skvm::F32 x, skvm::F32 y) { return x - y; });
1046 return skvm::sqrt(dot(vec, vec));
1047 }
John Stiles032fcba2021-05-06 11:33:08 -04001048 case k_dot_IntrinsicKind: return dot(args[0], args[1]);
1049 case k_cross_IntrinsicKind: {
Brian Osman22cc3be2020-12-30 10:38:15 -05001050 skvm::F32 ax = f32(args[0][0]), ay = f32(args[0][1]), az = f32(args[0][2]),
1051 bx = f32(args[1][0]), by = f32(args[1][1]), bz = f32(args[1][2]);
1052 Value result(3);
Mike Kleinff4decc2021-02-10 16:13:35 -06001053 result[0] = ay**bz - az**by;
1054 result[1] = az**bx - ax**bz;
1055 result[2] = ax**by - ay**bx;
Brian Osman22cc3be2020-12-30 10:38:15 -05001056 return result;
1057 }
John Stiles032fcba2021-05-06 11:33:08 -04001058 case k_normalize_IntrinsicKind: {
Brian Osman0a442b72020-12-02 11:12:51 -05001059 skvm::F32 invLen = 1.0f / skvm::sqrt(dot(args[0], args[0]));
Mike Kleinff4decc2021-02-10 16:13:35 -06001060 return unary(args[0], [&](skvm::F32 x) { return x ** invLen; });
Brian Osman0a442b72020-12-02 11:12:51 -05001061 }
John Stiles032fcba2021-05-06 11:33:08 -04001062 case k_faceforward_IntrinsicKind: {
Brian Osman22cc3be2020-12-30 10:38:15 -05001063 const Value &N = args[0],
1064 &I = args[1],
1065 &Nref = args[2];
1066
1067 skvm::F32 dotNrefI = dot(Nref, I);
1068 return unary(N, [&](skvm::F32 n) { return select(dotNrefI<0, n, -n); });
1069 }
John Stiles032fcba2021-05-06 11:33:08 -04001070 case k_reflect_IntrinsicKind: {
Brian Osman22cc3be2020-12-30 10:38:15 -05001071 const Value &I = args[0],
1072 &N = args[1];
1073
1074 skvm::F32 dotNI = dot(N, I);
1075 return binary([&](skvm::F32 i, skvm::F32 n) {
Mike Kleinff4decc2021-02-10 16:13:35 -06001076 return i - 2**dotNI**n;
Brian Osman22cc3be2020-12-30 10:38:15 -05001077 });
1078 }
John Stiles032fcba2021-05-06 11:33:08 -04001079 case k_refract_IntrinsicKind: {
Brian Osman22cc3be2020-12-30 10:38:15 -05001080 const Value &I = args[0],
1081 &N = args[1];
1082 skvm::F32 eta = f32(args[2]);
1083
1084 skvm::F32 dotNI = dot(N, I),
Mike Kleinff4decc2021-02-10 16:13:35 -06001085 k = 1 - eta**eta**(1 - dotNI**dotNI);
Brian Osman22cc3be2020-12-30 10:38:15 -05001086 return binary([&](skvm::F32 i, skvm::F32 n) {
Mike Kleinff4decc2021-02-10 16:13:35 -06001087 return select(k<0, 0.0f, eta**i - (eta**dotNI + sqrt(k))**n);
Brian Osman22cc3be2020-12-30 10:38:15 -05001088 });
1089 }
Brian Osman0a442b72020-12-02 11:12:51 -05001090
John Stiles032fcba2021-05-06 11:33:08 -04001091 case k_matrixCompMult_IntrinsicKind:
Mike Kleinff4decc2021-02-10 16:13:35 -06001092 return binary([](skvm::F32 x, skvm::F32 y) { return x ** y; });
John Stiles032fcba2021-05-06 11:33:08 -04001093 case k_inverse_IntrinsicKind: {
Brian Osman0a442b72020-12-02 11:12:51 -05001094 switch (args[0].slots()) {
1095 case 4: return this->writeMatrixInverse2x2(args[0]);
1096 case 9: return this->writeMatrixInverse3x3(args[0]);
1097 case 16: return this->writeMatrixInverse4x4(args[0]);
1098 default:
1099 SkDEBUGFAIL("Invalid call to inverse");
1100 return {};
1101 }
1102 }
1103
John Stiles032fcba2021-05-06 11:33:08 -04001104 case k_lessThan_IntrinsicKind:
Brian Osman30b67292020-12-23 13:02:09 -05001105 return nk == Type::NumberKind::kFloat
1106 ? binary([](skvm::F32 x, skvm::F32 y) { return x < y; })
1107 : binary([](skvm::I32 x, skvm::I32 y) { return x < y; });
John Stiles032fcba2021-05-06 11:33:08 -04001108 case k_lessThanEqual_IntrinsicKind:
Brian Osman30b67292020-12-23 13:02:09 -05001109 return nk == Type::NumberKind::kFloat
1110 ? binary([](skvm::F32 x, skvm::F32 y) { return x <= y; })
1111 : binary([](skvm::I32 x, skvm::I32 y) { return x <= y; });
John Stiles032fcba2021-05-06 11:33:08 -04001112 case k_greaterThan_IntrinsicKind:
Brian Osman30b67292020-12-23 13:02:09 -05001113 return nk == Type::NumberKind::kFloat
1114 ? binary([](skvm::F32 x, skvm::F32 y) { return x > y; })
1115 : binary([](skvm::I32 x, skvm::I32 y) { return x > y; });
John Stiles032fcba2021-05-06 11:33:08 -04001116 case k_greaterThanEqual_IntrinsicKind:
Brian Osman30b67292020-12-23 13:02:09 -05001117 return nk == Type::NumberKind::kFloat
1118 ? binary([](skvm::F32 x, skvm::F32 y) { return x >= y; })
1119 : binary([](skvm::I32 x, skvm::I32 y) { return x >= y; });
Brian Osman0a442b72020-12-02 11:12:51 -05001120
John Stiles032fcba2021-05-06 11:33:08 -04001121 case k_equal_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001122 return nk == Type::NumberKind::kFloat
1123 ? binary([](skvm::F32 x, skvm::F32 y) { return x == y; })
1124 : binary([](skvm::I32 x, skvm::I32 y) { return x == y; });
John Stiles032fcba2021-05-06 11:33:08 -04001125 case k_notEqual_IntrinsicKind:
Brian Osman0a442b72020-12-02 11:12:51 -05001126 return nk == Type::NumberKind::kFloat
1127 ? binary([](skvm::F32 x, skvm::F32 y) { return x != y; })
1128 : binary([](skvm::I32 x, skvm::I32 y) { return x != y; });
1129
John Stiles032fcba2021-05-06 11:33:08 -04001130 case k_any_IntrinsicKind: {
Brian Osman0a442b72020-12-02 11:12:51 -05001131 skvm::I32 result = i32(args[0][0]);
1132 for (size_t i = 1; i < args[0].slots(); ++i) {
1133 result |= i32(args[0][i]);
1134 }
1135 return result;
1136 }
John Stiles032fcba2021-05-06 11:33:08 -04001137 case k_all_IntrinsicKind: {
Brian Osman0a442b72020-12-02 11:12:51 -05001138 skvm::I32 result = i32(args[0][0]);
1139 for (size_t i = 1; i < args[0].slots(); ++i) {
1140 result &= i32(args[0][i]);
1141 }
1142 return result;
1143 }
John Stiles032fcba2021-05-06 11:33:08 -04001144 case k_not_IntrinsicKind: return unary(args[0], [](skvm::I32 x) { return ~x; });
Brian Osman0a442b72020-12-02 11:12:51 -05001145
John Stiles032fcba2021-05-06 11:33:08 -04001146 default:
1147 SkDEBUGFAILF("unsupported intrinsic %s", c.function().description().c_str());
Brian Osman0a442b72020-12-02 11:12:51 -05001148 return {};
1149 }
1150 SkUNREACHABLE;
1151}
1152
1153Value SkVMGenerator::writeFunctionCall(const FunctionCall& f) {
John Stiles032fcba2021-05-06 11:33:08 -04001154 if (f.function().isIntrinsic() && !f.function().definition()) {
Brian Osman0a442b72020-12-02 11:12:51 -05001155 return this->writeIntrinsicCall(f);
1156 }
1157
Brian Osman54515b72021-01-07 14:38:08 -05001158 const FunctionDeclaration& decl = f.function();
1159
1160 // Evaluate all arguments, gather the results into a contiguous list of IDs
1161 std::vector<skvm::Val> argVals;
1162 for (const auto& arg : f.arguments()) {
1163 Value v = this->writeExpression(*arg);
1164 for (size_t i = 0; i < v.slots(); ++i) {
1165 argVals.push_back(v[i]);
1166 }
1167 }
1168
1169 // Create storage for the return value
John Stiles47b087e2021-04-06 13:19:35 -04001170 size_t nslots = f.type().slotCount();
Brian Osman54515b72021-01-07 14:38:08 -05001171 Value result(nslots);
1172 for (size_t i = 0; i < nslots; ++i) {
1173 result[i] = fBuilder->splat(0.0f);
1174 }
1175
1176 {
Brian Osman9333c872021-01-13 15:06:17 -05001177 // This merges currentFunction().fReturned into fConditionMask. Lanes that conditionally
Brian Osman54515b72021-01-07 14:38:08 -05001178 // returned in the current function would otherwise resume execution within the child.
Brian Osman9333c872021-01-13 15:06:17 -05001179 ScopedCondition m(this, ~currentFunction().fReturned);
Ethan Nicholas624a5292021-04-16 14:54:43 -04001180 SkASSERTF(f.function().definition(), "no definition for function '%s'",
1181 f.function().description().c_str());
Brian Osmanae87bf12021-05-11 13:36:10 -04001182 this->writeFunction(*f.function().definition(), SkMakeSpan(argVals), result.asSpan());
Brian Osman54515b72021-01-07 14:38:08 -05001183 }
1184
1185 // Propagate new values of any 'out' params back to the original arguments
1186 const std::unique_ptr<Expression>* argIter = f.arguments().begin();
1187 size_t valIdx = 0;
1188 for (const Variable* p : decl.parameters()) {
John Stiles47b087e2021-04-06 13:19:35 -04001189 size_t nslots = p->type().slotCount();
Brian Osman54515b72021-01-07 14:38:08 -05001190 if (p->modifiers().fFlags & Modifiers::kOut_Flag) {
1191 Value v(nslots);
1192 for (size_t i = 0; i < nslots; ++i) {
1193 v[i] = argVals[valIdx + i];
1194 }
1195 const std::unique_ptr<Expression>& arg = *argIter;
1196 this->writeStore(*arg, v);
1197 }
1198 valIdx += nslots;
1199 argIter++;
1200 }
1201
1202 return result;
Brian Osman0a442b72020-12-02 11:12:51 -05001203}
1204
Brian Osmandd50b0c2021-01-11 17:04:29 -05001205Value SkVMGenerator::writeExternalFunctionCall(const ExternalFunctionCall& c) {
1206 // Evaluate all arguments, gather the results into a contiguous list of F32
1207 std::vector<skvm::F32> args;
1208 for (const auto& arg : c.arguments()) {
1209 Value v = this->writeExpression(*arg);
1210 for (size_t i = 0; i < v.slots(); ++i) {
1211 args.push_back(f32(v[i]));
1212 }
1213 }
1214
1215 // Create storage for the return value
John Stiles47b087e2021-04-06 13:19:35 -04001216 size_t nslots = c.type().slotCount();
Brian Osmandd50b0c2021-01-11 17:04:29 -05001217 std::vector<skvm::F32> result(nslots, fBuilder->splat(0.0f));
1218
1219 c.function().call(fBuilder, args.data(), result.data(), this->mask());
1220
1221 // Convert from 'vector of F32' to Value
1222 Value resultVal(nslots);
1223 for (size_t i = 0; i < nslots; ++i) {
1224 resultVal[i] = result[i];
1225 }
1226
1227 return resultVal;
1228}
1229
Brian Osman0a442b72020-12-02 11:12:51 -05001230Value SkVMGenerator::writePrefixExpression(const PrefixExpression& p) {
1231 Value val = this->writeExpression(*p.operand());
1232
John Stiles45990502021-02-16 10:55:27 -05001233 switch (p.getOperator().kind()) {
Brian Osman0a442b72020-12-02 11:12:51 -05001234 case Token::Kind::TK_PLUSPLUS:
1235 case Token::Kind::TK_MINUSMINUS: {
John Stiles45990502021-02-16 10:55:27 -05001236 bool incr = p.getOperator().kind() == Token::Kind::TK_PLUSPLUS;
Brian Osman0a442b72020-12-02 11:12:51 -05001237
1238 switch (base_number_kind(p.type())) {
1239 case Type::NumberKind::kFloat:
1240 val = f32(val) + fBuilder->splat(incr ? 1.0f : -1.0f);
1241 break;
1242 case Type::NumberKind::kSigned:
1243 val = i32(val) + fBuilder->splat(incr ? 1 : -1);
1244 break;
1245 default:
1246 SkASSERT(false);
1247 return {};
1248 }
1249 return this->writeStore(*p.operand(), val);
1250 }
1251 case Token::Kind::TK_MINUS: {
1252 switch (base_number_kind(p.type())) {
1253 case Type::NumberKind::kFloat:
1254 return this->unary(val, [](skvm::F32 x) { return -x; });
1255 case Type::NumberKind::kSigned:
1256 return this->unary(val, [](skvm::I32 x) { return -x; });
1257 default:
1258 SkASSERT(false);
1259 return {};
1260 }
1261 }
1262 case Token::Kind::TK_LOGICALNOT:
1263 case Token::Kind::TK_BITWISENOT:
1264 return this->unary(val, [](skvm::I32 x) { return ~x; });
1265 default:
1266 SkASSERT(false);
1267 return {};
1268 }
1269}
1270
1271Value SkVMGenerator::writePostfixExpression(const PostfixExpression& p) {
John Stiles45990502021-02-16 10:55:27 -05001272 switch (p.getOperator().kind()) {
Brian Osman0a442b72020-12-02 11:12:51 -05001273 case Token::Kind::TK_PLUSPLUS:
1274 case Token::Kind::TK_MINUSMINUS: {
1275 Value old = this->writeExpression(*p.operand()),
1276 val = old;
1277 SkASSERT(val.slots() == 1);
John Stiles45990502021-02-16 10:55:27 -05001278 bool incr = p.getOperator().kind() == Token::Kind::TK_PLUSPLUS;
Brian Osman0a442b72020-12-02 11:12:51 -05001279
1280 switch (base_number_kind(p.type())) {
1281 case Type::NumberKind::kFloat:
1282 val = f32(val) + fBuilder->splat(incr ? 1.0f : -1.0f);
1283 break;
1284 case Type::NumberKind::kSigned:
1285 val = i32(val) + fBuilder->splat(incr ? 1 : -1);
1286 break;
1287 default:
1288 SkASSERT(false);
1289 return {};
1290 }
1291 this->writeStore(*p.operand(), val);
1292 return old;
1293 }
1294 default:
1295 SkASSERT(false);
1296 return {};
1297 }
1298}
1299
1300Value SkVMGenerator::writeSwizzle(const Swizzle& s) {
1301 Value base = this->writeExpression(*s.base());
1302 Value swizzled(s.components().size());
1303 for (size_t i = 0; i < s.components().size(); ++i) {
1304 swizzled[i] = base[s.components()[i]];
1305 }
1306 return swizzled;
1307}
1308
1309Value SkVMGenerator::writeTernaryExpression(const TernaryExpression& t) {
1310 skvm::I32 test = i32(this->writeExpression(*t.test()));
1311 Value ifTrue, ifFalse;
1312
1313 {
Brian Osman9333c872021-01-13 15:06:17 -05001314 ScopedCondition m(this, test);
Brian Osman0a442b72020-12-02 11:12:51 -05001315 ifTrue = this->writeExpression(*t.ifTrue());
1316 }
1317 {
Brian Osman9333c872021-01-13 15:06:17 -05001318 ScopedCondition m(this, ~test);
Brian Osman0a442b72020-12-02 11:12:51 -05001319 ifFalse = this->writeExpression(*t.ifFalse());
1320 }
1321
1322 size_t nslots = ifTrue.slots();
1323 SkASSERT(nslots == ifFalse.slots());
1324
1325 Value result(nslots);
1326 for (size_t i = 0; i < nslots; ++i) {
1327 result[i] = skvm::select(test, i32(ifTrue[i]), i32(ifFalse[i]));
1328 }
1329 return result;
1330}
1331
1332Value SkVMGenerator::writeExpression(const Expression& e) {
1333 switch (e.kind()) {
1334 case Expression::Kind::kBinary:
1335 return this->writeBinaryExpression(e.as<BinaryExpression>());
1336 case Expression::Kind::kBoolLiteral:
1337 return fBuilder->splat(e.as<BoolLiteral>().value() ? ~0 : 0);
John Stiles7384b372021-04-01 13:48:15 -04001338 case Expression::Kind::kConstructorArray:
John Stiles8cad6372021-04-07 12:31:13 -04001339 case Expression::Kind::kConstructorCompound:
John Stilesd47330f2021-04-08 23:25:52 -04001340 case Expression::Kind::kConstructorStruct:
John Stilesd986f472021-04-06 15:54:43 -04001341 return this->writeAggregationConstructor(e.asAnyConstructor());
John Stilese1182782021-03-30 22:09:37 -04001342 case Expression::Kind::kConstructorDiagonalMatrix:
1343 return this->writeConstructorDiagonalMatrix(e.as<ConstructorDiagonalMatrix>());
John Stiles5abb9e12021-04-06 13:47:19 -04001344 case Expression::Kind::kConstructorMatrixResize:
1345 return this->writeConstructorMatrixResize(e.as<ConstructorMatrixResize>());
John Stilesfd7252f2021-04-04 22:24:40 -04001346 case Expression::Kind::kConstructorScalarCast:
John Stiles8cad6372021-04-07 12:31:13 -04001347 case Expression::Kind::kConstructorCompoundCast:
John Stilesb14a8192021-04-05 11:40:46 -04001348 return this->writeConstructorCast(e.asAnyConstructor());
John Stiles2938eea2021-04-01 18:58:25 -04001349 case Expression::Kind::kConstructorSplat:
1350 return this->writeConstructorSplat(e.as<ConstructorSplat>());
Brian Osman0a442b72020-12-02 11:12:51 -05001351 case Expression::Kind::kFieldAccess:
Brian Osmanfa71ffa2021-01-26 14:05:31 -05001352 return this->writeFieldAccess(e.as<FieldAccess>());
Brian Osman0a442b72020-12-02 11:12:51 -05001353 case Expression::Kind::kIndex:
Brian Osmanfa71ffa2021-01-26 14:05:31 -05001354 return this->writeIndexExpression(e.as<IndexExpression>());
Brian Osman0a442b72020-12-02 11:12:51 -05001355 case Expression::Kind::kVariableReference:
Brian Osmanfa71ffa2021-01-26 14:05:31 -05001356 return this->writeVariableExpression(e.as<VariableReference>());
Brian Osman0a442b72020-12-02 11:12:51 -05001357 case Expression::Kind::kFloatLiteral:
1358 return fBuilder->splat(e.as<FloatLiteral>().value());
1359 case Expression::Kind::kFunctionCall:
1360 return this->writeFunctionCall(e.as<FunctionCall>());
Brian Osmandd50b0c2021-01-11 17:04:29 -05001361 case Expression::Kind::kExternalFunctionCall:
1362 return this->writeExternalFunctionCall(e.as<ExternalFunctionCall>());
Brian Osman0a442b72020-12-02 11:12:51 -05001363 case Expression::Kind::kIntLiteral:
1364 return fBuilder->splat(static_cast<int>(e.as<IntLiteral>().value()));
Brian Osman0a442b72020-12-02 11:12:51 -05001365 case Expression::Kind::kPrefix:
1366 return this->writePrefixExpression(e.as<PrefixExpression>());
1367 case Expression::Kind::kPostfix:
1368 return this->writePostfixExpression(e.as<PostfixExpression>());
1369 case Expression::Kind::kSwizzle:
1370 return this->writeSwizzle(e.as<Swizzle>());
1371 case Expression::Kind::kTernary:
1372 return this->writeTernaryExpression(e.as<TernaryExpression>());
Brian Osmanbe0b3b72021-01-06 14:27:35 -05001373 case Expression::Kind::kExternalFunctionReference:
Brian Osman0a442b72020-12-02 11:12:51 -05001374 default:
1375 SkDEBUGFAIL("Unsupported expression");
1376 return {};
1377 }
1378}
1379
1380Value SkVMGenerator::writeStore(const Expression& lhs, const Value& rhs) {
John Stiles47b087e2021-04-06 13:19:35 -04001381 SkASSERTF(rhs.slots() == lhs.type().slotCount(),
John Stiles7bf79992021-06-25 11:05:20 -04001382 "lhs=%s (%s)\nrhs=%zu slot",
John Stiles94e72b92021-01-30 11:06:18 -05001383 lhs.type().description().c_str(), lhs.description().c_str(), rhs.slots());
Brian Osman0a442b72020-12-02 11:12:51 -05001384
Brian Osman21f57072021-01-25 13:51:57 -05001385 // We need to figure out the collection of slots that we're storing into. The l-value (lhs)
1386 // is always a VariableReference, possibly wrapped by one or more Swizzle, FieldAccess, or
1387 // IndexExpressions. The underlying VariableReference has a range of slots for its storage,
1388 // and each expression wrapped around that selects a sub-set of those slots (Field/Index),
1389 // or rearranges them (Swizzle).
1390 SkSTArray<4, size_t, true> slots;
1391 slots.resize(rhs.slots());
1392
1393 // Start with the identity slot map - this basically says that the values from rhs belong in
1394 // slots [0, 1, 2 ... N] of the lhs.
1395 for (size_t i = 0; i < slots.size(); ++i) {
1396 slots[i] = i;
1397 }
1398
1399 // Now, as we peel off each outer expression, adjust 'slots' to be the locations relative to
1400 // the next (inner) expression:
1401 const Expression* expr = &lhs;
1402 while (!expr->is<VariableReference>()) {
1403 switch (expr->kind()) {
1404 case Expression::Kind::kFieldAccess: {
1405 const FieldAccess& fld = expr->as<FieldAccess>();
1406 size_t offset = this->fieldSlotOffset(fld);
1407 for (size_t& s : slots) {
1408 s += offset;
1409 }
1410 expr = fld.base().get();
1411 } break;
1412 case Expression::Kind::kIndex: {
1413 const IndexExpression& idx = expr->as<IndexExpression>();
1414 size_t offset = this->indexSlotOffset(idx);
1415 for (size_t& s : slots) {
1416 s += offset;
1417 }
1418 expr = idx.base().get();
1419 } break;
1420 case Expression::Kind::kSwizzle: {
1421 const Swizzle& swz = expr->as<Swizzle>();
1422 for (size_t& s : slots) {
1423 s = swz.components()[s];
1424 }
1425 expr = swz.base().get();
1426 } break;
1427 default:
1428 // No other kinds of expressions are valid in lvalues. (see Analysis::IsAssignable)
1429 SkDEBUGFAIL("Invalid expression type");
1430 return {};
1431 }
1432 }
1433
1434 // When we get here, 'slots' are all relative to the first slot holding 'var's storage
1435 const Variable& var = *expr->as<VariableReference>().variable();
1436 size_t varSlot = this->getSlot(var);
Brian Osman0a442b72020-12-02 11:12:51 -05001437 skvm::I32 mask = this->mask();
1438 for (size_t i = rhs.slots(); i --> 0;) {
John Stiles47b087e2021-04-06 13:19:35 -04001439 SkASSERT(slots[i] < var.type().slotCount());
Brian Osman21f57072021-01-25 13:51:57 -05001440 skvm::F32 curr = f32(fSlots[varSlot + slots[i]]),
Brian Osman0a442b72020-12-02 11:12:51 -05001441 next = f32(rhs[i]);
Brian Osman21f57072021-01-25 13:51:57 -05001442 fSlots[varSlot + slots[i]] = select(mask, next, curr).id;
Brian Osman0a442b72020-12-02 11:12:51 -05001443 }
1444 return rhs;
1445}
1446
1447void SkVMGenerator::writeBlock(const Block& b) {
1448 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1449 this->writeStatement(*stmt);
1450 }
1451}
1452
Brian Osman9333c872021-01-13 15:06:17 -05001453void SkVMGenerator::writeBreakStatement() {
1454 // Any active lanes stop executing for the duration of the current loop
1455 fLoopMask &= ~this->mask();
1456}
1457
1458void SkVMGenerator::writeContinueStatement() {
1459 // Any active lanes stop executing for the current iteration.
1460 // Remember them in fContinueMask, to be re-enabled later.
1461 skvm::I32 mask = this->mask();
1462 fLoopMask &= ~mask;
1463 fContinueMask |= mask;
1464}
1465
1466void SkVMGenerator::writeForStatement(const ForStatement& f) {
1467 // We require that all loops be ES2-compliant (unrollable), and actually unroll them here
1468 Analysis::UnrollableLoopInfo loop;
John Stiles232b4ce2021-03-01 22:14:22 -05001469 SkAssertResult(Analysis::ForLoopIsValidForES2(f.fOffset, f.initializer().get(), f.test().get(),
1470 f.next().get(), f.statement().get(), &loop,
1471 /*errors=*/nullptr));
John Stiles47b087e2021-04-06 13:19:35 -04001472 SkASSERT(loop.fIndex->type().slotCount() == 1);
Brian Osman9333c872021-01-13 15:06:17 -05001473
Brian Osman21f57072021-01-25 13:51:57 -05001474 size_t indexSlot = this->getSlot(*loop.fIndex);
Brian Osman9333c872021-01-13 15:06:17 -05001475 double val = loop.fStart;
1476
1477 skvm::I32 oldLoopMask = fLoopMask,
1478 oldContinueMask = fContinueMask;
1479
1480 for (int i = 0; i < loop.fCount; ++i) {
Brian Osman21f57072021-01-25 13:51:57 -05001481 fSlots[indexSlot] = loop.fIndex->type().isInteger()
1482 ? fBuilder->splat(static_cast<int>(val)).id
1483 : fBuilder->splat(static_cast<float>(val)).id;
Brian Osman9333c872021-01-13 15:06:17 -05001484
1485 fContinueMask = fBuilder->splat(0);
1486 this->writeStatement(*f.statement());
1487 fLoopMask |= fContinueMask;
1488
1489 val += loop.fDelta;
1490 }
1491
1492 fLoopMask = oldLoopMask;
1493 fContinueMask = oldContinueMask;
1494}
1495
Brian Osman0a442b72020-12-02 11:12:51 -05001496void SkVMGenerator::writeIfStatement(const IfStatement& i) {
1497 Value test = this->writeExpression(*i.test());
1498 {
Brian Osman9333c872021-01-13 15:06:17 -05001499 ScopedCondition ifTrue(this, i32(test));
Brian Osman0a442b72020-12-02 11:12:51 -05001500 this->writeStatement(*i.ifTrue());
1501 }
1502 if (i.ifFalse()) {
Brian Osman9333c872021-01-13 15:06:17 -05001503 ScopedCondition ifFalse(this, ~i32(test));
Brian Osman0a442b72020-12-02 11:12:51 -05001504 this->writeStatement(*i.ifFalse());
1505 }
1506}
1507
1508void SkVMGenerator::writeReturnStatement(const ReturnStatement& r) {
Brian Osman54515b72021-01-07 14:38:08 -05001509 skvm::I32 returnsHere = this->mask();
Brian Osman0a442b72020-12-02 11:12:51 -05001510
Brian Osman54515b72021-01-07 14:38:08 -05001511 if (r.expression()) {
1512 Value val = this->writeExpression(*r.expression());
Brian Osman0a442b72020-12-02 11:12:51 -05001513
Brian Osman54515b72021-01-07 14:38:08 -05001514 int i = 0;
1515 for (skvm::Val& slot : currentFunction().fReturnValue) {
1516 slot = select(returnsHere, f32(val[i]), f32(slot)).id;
1517 i++;
1518 }
Brian Osman0a442b72020-12-02 11:12:51 -05001519 }
1520
Brian Osman54515b72021-01-07 14:38:08 -05001521 currentFunction().fReturned |= returnsHere;
Brian Osman0a442b72020-12-02 11:12:51 -05001522}
1523
1524void SkVMGenerator::writeVarDeclaration(const VarDeclaration& decl) {
Brian Osman21f57072021-01-25 13:51:57 -05001525 size_t slot = this->getSlot(decl.var()),
John Stiles47b087e2021-04-06 13:19:35 -04001526 nslots = decl.var().type().slotCount();
Brian Osman0a442b72020-12-02 11:12:51 -05001527
1528 Value val = decl.value() ? this->writeExpression(*decl.value()) : Value{};
1529 for (size_t i = 0; i < nslots; ++i) {
1530 fSlots[slot + i] = val ? val[i] : fBuilder->splat(0.0f).id;
1531 }
1532}
1533
1534void SkVMGenerator::writeStatement(const Statement& s) {
1535 switch (s.kind()) {
1536 case Statement::Kind::kBlock:
1537 this->writeBlock(s.as<Block>());
1538 break;
Brian Osman9333c872021-01-13 15:06:17 -05001539 case Statement::Kind::kBreak:
1540 this->writeBreakStatement();
1541 break;
1542 case Statement::Kind::kContinue:
1543 this->writeContinueStatement();
1544 break;
Brian Osman0a442b72020-12-02 11:12:51 -05001545 case Statement::Kind::kExpression:
1546 this->writeExpression(*s.as<ExpressionStatement>().expression());
1547 break;
Brian Osman9333c872021-01-13 15:06:17 -05001548 case Statement::Kind::kFor:
1549 this->writeForStatement(s.as<ForStatement>());
1550 break;
Brian Osman0a442b72020-12-02 11:12:51 -05001551 case Statement::Kind::kIf:
1552 this->writeIfStatement(s.as<IfStatement>());
1553 break;
1554 case Statement::Kind::kReturn:
1555 this->writeReturnStatement(s.as<ReturnStatement>());
1556 break;
1557 case Statement::Kind::kVarDeclaration:
1558 this->writeVarDeclaration(s.as<VarDeclaration>());
1559 break;
Brian Osman0a442b72020-12-02 11:12:51 -05001560 case Statement::Kind::kDiscard:
1561 case Statement::Kind::kDo:
Brian Osman0a442b72020-12-02 11:12:51 -05001562 case Statement::Kind::kSwitch:
Brian Osman57e353f2021-01-07 15:55:20 -05001563 SkDEBUGFAIL("Unsupported control flow");
Brian Osman0a442b72020-12-02 11:12:51 -05001564 break;
1565 case Statement::Kind::kInlineMarker:
1566 case Statement::Kind::kNop:
1567 break;
1568 default:
1569 SkASSERT(false);
1570 }
1571}
1572
1573skvm::Color ProgramToSkVM(const Program& program,
1574 const FunctionDefinition& function,
1575 skvm::Builder* builder,
1576 SkSpan<skvm::Val> uniforms,
1577 skvm::Coord device,
1578 skvm::Coord local,
Brian Osman577c6062021-04-12 17:17:19 -04001579 skvm::Color inputColor,
John Stiles50d0d092021-06-09 17:24:31 -04001580 skvm::Color destColor,
John Stiles137482f2021-07-23 10:38:57 -04001581 SampleShaderFn sampleShader,
John Stiles2955c262021-07-23 15:51:05 -04001582 SampleColorFilterFn sampleColorFilter,
1583 SampleBlenderFn sampleBlender) {
Mike Kleinaebcf732021-01-14 10:15:00 -06001584 skvm::Val zero = builder->splat(0.0f).id;
1585 skvm::Val result[4] = {zero,zero,zero,zero};
Brian Osman577c6062021-04-12 17:17:19 -04001586
John Stilesf7f36ae2021-06-08 14:06:22 -04001587 skvm::Val args[8]; // At most 8 arguments (half4 srcColor, half4 dstColor)
Brian Osman577c6062021-04-12 17:17:19 -04001588 size_t argSlots = 0;
Brian Osman0a442b72020-12-02 11:12:51 -05001589 for (const SkSL::Variable* param : function.declaration().parameters()) {
Brian Osman577c6062021-04-12 17:17:19 -04001590 switch (param->modifiers().fLayout.fBuiltin) {
1591 case SK_MAIN_COORDS_BUILTIN:
1592 SkASSERT(param->type().slotCount() == 2);
John Stilesf7f36ae2021-06-08 14:06:22 -04001593 SkASSERT((argSlots + 2) <= SK_ARRAY_COUNT(args));
Brian Osman577c6062021-04-12 17:17:19 -04001594 args[argSlots++] = local.x.id;
1595 args[argSlots++] = local.y.id;
1596 break;
1597 case SK_INPUT_COLOR_BUILTIN:
1598 SkASSERT(param->type().slotCount() == 4);
John Stilesf7f36ae2021-06-08 14:06:22 -04001599 SkASSERT((argSlots + 4) <= SK_ARRAY_COUNT(args));
Brian Osman577c6062021-04-12 17:17:19 -04001600 args[argSlots++] = inputColor.r.id;
1601 args[argSlots++] = inputColor.g.id;
1602 args[argSlots++] = inputColor.b.id;
1603 args[argSlots++] = inputColor.a.id;
1604 break;
John Stiles50d0d092021-06-09 17:24:31 -04001605 case SK_DEST_COLOR_BUILTIN:
1606 SkASSERT(param->type().slotCount() == 4);
1607 SkASSERT((argSlots + 4) <= SK_ARRAY_COUNT(args));
1608 args[argSlots++] = destColor.r.id;
1609 args[argSlots++] = destColor.g.id;
1610 args[argSlots++] = destColor.b.id;
1611 args[argSlots++] = destColor.a.id;
1612 break;
Brian Osman577c6062021-04-12 17:17:19 -04001613 default:
1614 SkDEBUGFAIL("Invalid parameter to main()");
1615 return {};
1616 }
Brian Osman0a442b72020-12-02 11:12:51 -05001617 }
Brian Osman577c6062021-04-12 17:17:19 -04001618 SkASSERT(argSlots <= SK_ARRAY_COUNT(args));
Brian Osman0a442b72020-12-02 11:12:51 -05001619
John Stilesd9a56b92021-07-23 15:50:39 -04001620 SkVMGenerator generator(program, builder, uniforms, device, local, std::move(sampleShader),
John Stiles2955c262021-07-23 15:51:05 -04001621 std::move(sampleColorFilter), std::move(sampleBlender));
Brian Osmanae87bf12021-05-11 13:36:10 -04001622 generator.writeFunction(function, {args, argSlots}, SkMakeSpan(result));
Brian Osman0a442b72020-12-02 11:12:51 -05001623
Brian Osman57e353f2021-01-07 15:55:20 -05001624 return skvm::Color{{builder, result[0]},
1625 {builder, result[1]},
1626 {builder, result[2]},
1627 {builder, result[3]}};
Brian Osman0a442b72020-12-02 11:12:51 -05001628}
1629
Brian Osmanf4a77732020-12-28 09:03:00 -05001630bool ProgramToSkVM(const Program& program,
1631 const FunctionDefinition& function,
1632 skvm::Builder* b,
Brian Osmanc92df392021-01-11 13:16:28 -05001633 SkSpan<skvm::Val> uniforms,
Brian Osmanf4a77732020-12-28 09:03:00 -05001634 SkVMSignature* outSignature) {
Brian Osmanf4a77732020-12-28 09:03:00 -05001635 SkVMSignature ignored,
1636 *signature = outSignature ? outSignature : &ignored;
1637
Mike Klein00e43df2021-01-08 13:45:42 -06001638 std::vector<skvm::Ptr> argPtrs;
Brian Osmanf4a77732020-12-28 09:03:00 -05001639 std::vector<skvm::Val> argVals;
1640
1641 for (const Variable* p : function.declaration().parameters()) {
John Stiles47b087e2021-04-06 13:19:35 -04001642 size_t slots = p->type().slotCount();
Brian Osmanf4a77732020-12-28 09:03:00 -05001643 signature->fParameterSlots += slots;
1644 for (size_t i = 0; i < slots; ++i) {
1645 argPtrs.push_back(b->varying<float>());
1646 argVals.push_back(b->loadF(argPtrs.back()).id);
1647 }
1648 }
1649
Mike Klein00e43df2021-01-08 13:45:42 -06001650 std::vector<skvm::Ptr> returnPtrs;
Brian Osmanf4a77732020-12-28 09:03:00 -05001651 std::vector<skvm::Val> returnVals;
1652
John Stiles47b087e2021-04-06 13:19:35 -04001653 signature->fReturnSlots = function.declaration().returnType().slotCount();
Brian Osmanf4a77732020-12-28 09:03:00 -05001654 for (size_t i = 0; i < signature->fReturnSlots; ++i) {
1655 returnPtrs.push_back(b->varying<float>());
1656 returnVals.push_back(b->splat(0.0f).id);
1657 }
1658
Brian Osmanc9125aa2021-04-21 09:57:19 -04001659 skvm::F32 zero = b->splat(0.0f);
1660 skvm::Coord zeroCoord = {zero, zero};
Brian Osmanc92df392021-01-11 13:16:28 -05001661 SkVMGenerator generator(program, b, uniforms, /*device=*/zeroCoord, /*local=*/zeroCoord,
John Stiles2955c262021-07-23 15:51:05 -04001662 /*sampleShader=*/nullptr, /*sampleColorFilter=*/nullptr,
1663 /*sampleBlender=*/nullptr);
Brian Osmanae87bf12021-05-11 13:36:10 -04001664 generator.writeFunction(function, SkMakeSpan(argVals), SkMakeSpan(returnVals));
Brian Osmanf4a77732020-12-28 09:03:00 -05001665
1666 // generateCode has updated the contents of 'argVals' for any 'out' or 'inout' parameters.
1667 // Propagate those changes back to our varying buffers:
1668 size_t argIdx = 0;
1669 for (const Variable* p : function.declaration().parameters()) {
John Stiles47b087e2021-04-06 13:19:35 -04001670 size_t nslots = p->type().slotCount();
Brian Osmanf4a77732020-12-28 09:03:00 -05001671 if (p->modifiers().fFlags & Modifiers::kOut_Flag) {
1672 for (size_t i = 0; i < nslots; ++i) {
1673 b->storeF(argPtrs[argIdx + i], skvm::F32{b, argVals[argIdx + i]});
1674 }
1675 }
1676 argIdx += nslots;
1677 }
1678
1679 // It's also updated the contents of 'returnVals' with the return value of the entry point.
1680 // Store that as well:
1681 for (size_t i = 0; i < signature->fReturnSlots; ++i) {
1682 b->storeF(returnPtrs[i], skvm::F32{b, returnVals[i]});
1683 }
1684
1685 return true;
1686}
1687
Brian Osman5933d4c2021-01-05 13:02:20 -05001688const FunctionDefinition* Program_GetFunction(const Program& program, const char* function) {
1689 for (const ProgramElement* e : program.elements()) {
1690 if (e->is<FunctionDefinition>() &&
1691 e->as<FunctionDefinition>().declaration().name() == function) {
1692 return &e->as<FunctionDefinition>();
1693 }
1694 }
1695 return nullptr;
1696}
1697
Brian Osmane89d8ea2021-01-20 14:01:30 -05001698static void gather_uniforms(UniformInfo* info, const Type& type, const String& name) {
1699 switch (type.typeKind()) {
1700 case Type::TypeKind::kStruct:
1701 for (const auto& f : type.fields()) {
1702 gather_uniforms(info, *f.fType, name + "." + f.fName);
1703 }
1704 break;
1705 case Type::TypeKind::kArray:
1706 for (int i = 0; i < type.columns(); ++i) {
1707 gather_uniforms(info, type.componentType(),
1708 String::printf("%s[%d]", name.c_str(), i));
1709 }
1710 break;
1711 case Type::TypeKind::kScalar:
1712 case Type::TypeKind::kVector:
1713 case Type::TypeKind::kMatrix:
1714 info->fUniforms.push_back({name, base_number_kind(type), type.rows(), type.columns(),
1715 info->fUniformSlotCount});
1716 info->fUniformSlotCount += type.columns() * type.rows();
1717 break;
1718 default:
1719 break;
1720 }
1721}
1722
1723std::unique_ptr<UniformInfo> Program_GetUniformInfo(const Program& program) {
1724 auto info = std::make_unique<UniformInfo>();
1725 for (const ProgramElement* e : program.elements()) {
1726 if (!e->is<GlobalVarDeclaration>()) {
1727 continue;
1728 }
1729 const GlobalVarDeclaration& decl = e->as<GlobalVarDeclaration>();
1730 const Variable& var = decl.declaration()->as<VarDeclaration>().var();
1731 if (var.modifiers().fFlags & Modifiers::kUniform_Flag) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -04001732 gather_uniforms(info.get(), var.type(), String(var.name()));
Brian Osmane89d8ea2021-01-20 14:01:30 -05001733 }
1734 }
1735 return info;
1736}
1737
Brian Osman47726a12020-12-17 16:02:08 -05001738/*
1739 * Testing utility function that emits program's "main" with a minimal harness. Used to create
1740 * representative skvm op sequences for SkSL tests.
1741 */
1742bool testingOnly_ProgramToSkVMShader(const Program& program, skvm::Builder* builder) {
Brian Osman5933d4c2021-01-05 13:02:20 -05001743 const SkSL::FunctionDefinition* main = Program_GetFunction(program, "main");
1744 if (!main) {
1745 return false;
1746 }
1747
Brian Osman47726a12020-12-17 16:02:08 -05001748 size_t uniformSlots = 0;
1749 int childSlots = 0;
1750 for (const SkSL::ProgramElement* e : program.elements()) {
Brian Osman47726a12020-12-17 16:02:08 -05001751 if (e->is<GlobalVarDeclaration>()) {
1752 const GlobalVarDeclaration& decl = e->as<GlobalVarDeclaration>();
1753 const Variable& var = decl.declaration()->as<VarDeclaration>().var();
Brian Osman14d00962021-04-02 17:04:35 -04001754 if (var.type().isEffectChild()) {
Brian Osman47726a12020-12-17 16:02:08 -05001755 childSlots++;
1756 } else if (is_uniform(var)) {
John Stiles47b087e2021-04-06 13:19:35 -04001757 uniformSlots += var.type().slotCount();
Brian Osman47726a12020-12-17 16:02:08 -05001758 }
1759 }
1760 }
Brian Osman0a442b72020-12-02 11:12:51 -05001761
Mike Kleinae562bd2021-01-08 14:15:55 -06001762 skvm::Uniforms uniforms(builder->uniform(), 0);
Brian Osman47726a12020-12-17 16:02:08 -05001763
1764 auto new_uni = [&]() { return builder->uniformF(uniforms.pushF(0.0f)); };
1765
1766 // Assume identity CTM
1767 skvm::Coord device = {pun_to_F32(builder->index()), new_uni()};
1768 skvm::Coord local = device;
1769
1770 struct Child {
1771 skvm::Uniform addr;
1772 skvm::I32 rowBytesAsPixels;
1773 };
1774
1775 std::vector<Child> children;
1776 for (int i = 0; i < childSlots; ++i) {
1777 children.push_back({uniforms.pushPtr(nullptr), builder->uniform32(uniforms.push(0))});
1778 }
1779
John Stilesd9a56b92021-07-23 15:50:39 -04001780 auto sampleShader = [&](int i, skvm::Coord coord) {
Mike Klein447f3312021-02-08 09:46:59 -06001781 skvm::PixelFormat pixelFormat = skvm::SkColorType_to_PixelFormat(kRGBA_F32_SkColorType);
Brian Osman3f904db2021-01-28 13:24:31 -05001782 skvm::I32 index = trunc(coord.x);
1783 index += trunc(coord.y) * children[i].rowBytesAsPixels;
Brian Osman47726a12020-12-17 16:02:08 -05001784 return gather(pixelFormat, children[i].addr, index);
1785 };
1786
1787 std::vector<skvm::Val> uniformVals;
1788 for (size_t i = 0; i < uniformSlots; ++i) {
1789 uniformVals.push_back(new_uni().id);
1790 }
1791
Brian Osman577c6062021-04-12 17:17:19 -04001792 skvm::Color inColor = builder->uniformColor(SkColors::kWhite, &uniforms);
John Stiles50d0d092021-06-09 17:24:31 -04001793 skvm::Color destColor = builder->uniformColor(SkColors::kBlack, &uniforms);
Brian Osman577c6062021-04-12 17:17:19 -04001794
John Stiles50d0d092021-06-09 17:24:31 -04001795 skvm::Color result = SkSL::ProgramToSkVM(program, *main, builder, SkMakeSpan(uniformVals),
John Stiles137482f2021-07-23 10:38:57 -04001796 device, local, inColor, destColor, sampleShader,
John Stiles2955c262021-07-23 15:51:05 -04001797 /*sampleColorFilter=*/nullptr,
1798 /*sampleBlender=*/nullptr);
Brian Osman47726a12020-12-17 16:02:08 -05001799
1800 storeF(builder->varying<float>(), result.r);
1801 storeF(builder->varying<float>(), result.g);
1802 storeF(builder->varying<float>(), result.b);
1803 storeF(builder->varying<float>(), result.a);
1804
1805 return true;
1806
1807}
1808
1809} // namespace SkSL