Debian Codegraph @

src/core/SkRuntimeEffect.cpp

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 * Copyright 2019 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 "include/effects/SkRuntimeEffect.h"
9
10 #include "include/core/SkAlphaType.h"
11 #include "include/core/SkBlender.h"
12 #include "include/core/SkCapabilities.h"
13 #include "include/core/SkColor.h"
14 #include "include/core/SkColorFilter.h"
15 #include "include/core/SkData.h"
16 #include "include/private/base/SkAlign.h"
17 #include "include/private/base/SkDebug.h"
18 #include "include/private/base/SkMutex.h"
19 #include "include/private/base/SkOnce.h"
20 #include "include/private/base/SkTArray.h"
21 #include "src/base/SkArenaAlloc.h"
22 #include "src/base/SkEnumBitMask.h"
23 #include "src/base/SkNoDestructor.h"
24 #include "src/core/SkBlenderBase.h"
25 #include "src/core/SkChecksum.h"
26 #include "src/core/SkColorSpacePriv.h"
27 #include "src/core/SkColorSpaceXformSteps.h"
28 #include "src/core/SkEffectPriv.h"
29 #include "src/core/SkLRUCache.h"
30 #include "src/core/SkRasterPipeline.h"
31 #include "src/core/SkRasterPipelineOpList.h"
32 #include "src/core/SkReadBuffer.h"
33 #include "src/core/SkRuntimeBlender.h"
34 #include "src/core/SkRuntimeEffectPriv.h"
35 #include "src/core/SkStreamPriv.h"
36 #include "src/core/SkWriteBuffer.h"
37 #include "src/effects/colorfilters/SkColorFilterBase.h"
38 #include "src/effects/colorfilters/SkRuntimeColorFilter.h"
39 #include "src/shaders/SkLocalMatrixShader.h"
40 #include "src/shaders/SkRuntimeShader.h"
41 #include "src/shaders/SkShaderBase.h"
42 #include "src/sksl/SkSLAnalysis.h"
43 #include "src/sksl/SkSLBuiltinTypes.h"
44 #include "src/sksl/SkSLCompiler.h"
45 #include "src/sksl/SkSLContext.h"
46 #include "src/sksl/SkSLDefines.h"
47 #include "src/sksl/SkSLProgramKind.h"
48 #include "src/sksl/SkSLProgramSettings.h"
49 #include "src/sksl/analysis/SkSLProgramUsage.h"
50 #include "src/sksl/codegen/SkSLRasterPipelineBuilder.h"
51 #include "src/sksl/codegen/SkSLRasterPipelineCodeGenerator.h"
52 #include "src/sksl/ir/SkSLFunctionDeclaration.h"
53 #include "src/sksl/ir/SkSLLayout.h"
54 #include "src/sksl/ir/SkSLModifierFlags.h"
55 #include "src/sksl/ir/SkSLProgram.h"
56 #include "src/sksl/ir/SkSLProgramElement.h"
57 #include "src/sksl/ir/SkSLStatement.h"
58 #include "src/sksl/ir/SkSLType.h"
59 #include "src/sksl/ir/SkSLVarDeclarations.h"
60 #include "src/sksl/ir/SkSLVariable.h"
61 #include "src/sksl/tracing/SkSLDebugTracePriv.h"
62 #include "src/sksl/transform/SkSLTransform.h"
63
64 #include <algorithm>
65
66 using namespace skia_private;
67
68 class SkColorSpace;
69 struct SkIPoint;
70
71 constexpr bool kRPEnableLiveTrace = false;
72
73 using ChildType = SkRuntimeEffect::ChildType;
74
75 static bool init_uniform_type(const SkSL::Context& ctx,
76 const SkSL::Type* type,
77 SkRuntimeEffect::Uniform* v) {
78 using Type = SkRuntimeEffect::Uniform::Type;
79 if (type->matches(*ctx.fTypes.fFloat)) { v->type = Type::kFloat; return true; }
80 if (type->matches(*ctx.fTypes.fHalf)) { v->type = Type::kFloat; return true; }
81 if (type->matches(*ctx.fTypes.fFloat2)) { v->type = Type::kFloat2; return true; }
82 if (type->matches(*ctx.fTypes.fHalf2)) { v->type = Type::kFloat2; return true; }
83 if (type->matches(*ctx.fTypes.fFloat3)) { v->type = Type::kFloat3; return true; }
84 if (type->matches(*ctx.fTypes.fHalf3)) { v->type = Type::kFloat3; return true; }
85 if (type->matches(*ctx.fTypes.fFloat4)) { v->type = Type::kFloat4; return true; }
86 if (type->matches(*ctx.fTypes.fHalf4)) { v->type = Type::kFloat4; return true; }
87 if (type->matches(*ctx.fTypes.fFloat2x2)) { v->type = Type::kFloat2x2; return true; }
88 if (type->matches(*ctx.fTypes.fHalf2x2)) { v->type = Type::kFloat2x2; return true; }
89 if (type->matches(*ctx.fTypes.fFloat3x3)) { v->type = Type::kFloat3x3; return true; }
90 if (type->matches(*ctx.fTypes.fHalf3x3)) { v->type = Type::kFloat3x3; return true; }
91 if (type->matches(*ctx.fTypes.fFloat4x4)) { v->type = Type::kFloat4x4; return true; }
92 if (type->matches(*ctx.fTypes.fHalf4x4)) { v->type = Type::kFloat4x4; return true; }
93
94 if (type->matches(*ctx.fTypes.fInt)) { v->type = Type::kInt; return true; }
95 if (type->matches(*ctx.fTypes.fInt2)) { v->type = Type::kInt2; return true; }
96 if (type->matches(*ctx.fTypes.fInt3)) { v->type = Type::kInt3; return true; }
97 if (type->matches(*ctx.fTypes.fInt4)) { v->type = Type::kInt4; return true; }
98
99 return false;
100 }
101
102 SkRuntimeEffect::Uniform SkRuntimeEffectPriv::VarAsUniform(const SkSL::Variable& var,
103 const SkSL::Context& context,
104 size_t* offset) {
105 using Uniform = SkRuntimeEffect::Uniform;
106 SkASSERT(var.modifierFlags().isUniform());
107 Uniform uni;
108 uni.name = var.name();
109 uni.flags = 0;
110 uni.count = 1;
111
112 const SkSL::Type* type = &var.type();
113 if (type->isArray()) {
114 uni.flags |= Uniform::kArray_Flag;
115 uni.count = type->columns();
116 type = &type->componentType();
117 }
118
119 if (type->hasPrecision() && !type->highPrecision()) {
120 uni.flags |= Uniform::kHalfPrecision_Flag;
121 }
122
123 SkAssertResult(init_uniform_type(context, type, &uni));
124 if (var.layout().fFlags & SkSL::LayoutFlag::kColor) {
125 uni.flags |= Uniform::kColor_Flag;
126 }
127
128 uni.offset = *offset;
129 *offset += uni.sizeInBytes();
130 SkASSERT(SkIsAlign4(*offset));
131 return uni;
132 }
133
134 static ChildType child_type(const SkSL::Type& type) {
135 switch (type.typeKind()) {
136 case SkSL::Type::TypeKind::kBlender: return ChildType::kBlender;
137 case SkSL::Type::TypeKind::kColorFilter: return ChildType::kColorFilter;
138 case SkSL::Type::TypeKind::kShader: return ChildType::kShader;
139 default: SkUNREACHABLE;
140 }
141 }
142
143 const char* SkRuntimeEffectPriv::ChildTypeToStr(ChildType type) {
144 switch (type) {
145 case ChildType::kBlender: return "blender";
146 case ChildType::kColorFilter: return "color filter";
147 case ChildType::kShader: return "shader";
148 default: SkUNREACHABLE;
149 }
150 }
151
152 SkRuntimeEffect::Child SkRuntimeEffectPriv::VarAsChild(const SkSL::Variable& var, int index) {
153 SkRuntimeEffect::Child c;
154 c.name = var.name();
155 c.type = child_type(var.type());
156 c.index = index;
157 return c;
158 }
159
160 sk_sp<const SkData> SkRuntimeEffectPriv::TransformUniforms(
161 SkSpan<const SkRuntimeEffect::Uniform> uniforms,
162 sk_sp<const SkData> originalData,
163 const SkColorSpace* dstCS) {
164 if (!dstCS) {
165 // There's no destination color-space; we can early-out immediately.
166 return originalData;
167 }
168 SkColorSpaceXformSteps steps(sk_srgb_singleton(), kUnpremul_SkAlphaType,
169 dstCS, kUnpremul_SkAlphaType);
170 return TransformUniforms(uniforms, std::move(originalData), steps);
171 }
172
173 sk_sp<const SkData> SkRuntimeEffectPriv::TransformUniforms(
174 SkSpan<const SkRuntimeEffect::Uniform> uniforms,
175 sk_sp<const SkData> originalData,
176 const SkColorSpaceXformSteps& steps) {
177 using Flags = SkRuntimeEffect::Uniform::Flags;
178 using Type = SkRuntimeEffect::Uniform::Type;
179
180 sk_sp<SkData> data = nullptr;
181 auto writableData = [&]() {
182 if (!data) {
183 data = SkData::MakeWithCopy(originalData->data(), originalData->size());
184 }
185 return data->writable_data();
186 };
187
188 for (const auto& u : uniforms) {
189 if (u.flags & Flags::kColor_Flag) {
190 SkASSERT(u.type == Type::kFloat3 || u.type == Type::kFloat4);
191 if (steps.fFlags.mask()) {
192 float* color = SkTAddOffset<float>(writableData(), u.offset);
193 if (u.type == Type::kFloat4) {
194 // RGBA, easy case
195 for (int i = 0; i < u.count; ++i) {
196 steps.apply(color);
197 color += 4;
198 }
199 } else {
200 // RGB, need to pad out to include alpha. Technically, this isn't necessary,
201 // because steps shouldn't include unpremul or premul, and thus shouldn't
202 // read or write the fourth element. But let's be safe.
203 float rgba[4];
204 for (int i = 0; i < u.count; ++i) {
205 memcpy(rgba, color, 3 * sizeof(float));
206 rgba[3] = 1.0f;
207 steps.apply(rgba);
208 memcpy(color, rgba, 3 * sizeof(float));
209 color += 3;
210 }
211 }
212 }
213 }
214 }
215 return data ? data : originalData;
216 }
217
218 const SkSL::RP::Program* SkRuntimeEffect::getRPProgram(SkSL::DebugTracePriv* debugTrace) const {
219 // Lazily compile the program the first time `getRPProgram` is called.
220 // By using an SkOnce, we avoid thread hazards and behave in a conceptually const way, but we
221 // can avoid the cost of invoking the RP code generator until it's actually needed.
222 fCompileRPProgramOnce([&] {
223 // We generally do not run the inliner when an SkRuntimeEffect program is initially created,
224 // because the final compile to native shader code will do this. However, in SkRP, there's
•225 // no additional compilation occurring, so we need to optimize/inline here if we want the
226 // performance boost of inlining. Since fBaseProgram is a shared (const) object, we can't
227 // mutate it in-place (e.g. calling compiler.runInliner). If optimization is neccesary,
228 // we re-compile the program from source with inlining and optimization enabled to get a
229 // freshly optimized copy (it's pretty cheap to re-compile and there's no easy way to copy
230 // an SkSL::Program).
231 const SkSL::Program* programToUse = fBaseProgram.get();
232 const SkSL::FunctionDefinition* mainToUse = &fMain;
233
234 std::unique_ptr<SkSL::Program> optimizedCopy;
235 bool shouldOptimize = !(fFlags & kDisableOptimization_Flag);
236 SkSL::ProgramSettings settings = fBaseProgram->fConfig->fSettings;
237 bool needsOptimization = !settings.fOptimize ||
238 settings.fInlineThreshold < SkSL::kDefaultInlineThreshold;
239 if (shouldOptimize && needsOptimization) {
240 SkSL::Compiler compiler;
•241 settings.fOptimize = true;
242 settings.fInlineThreshold = SkSL::kDefaultInlineThreshold;
243 optimizedCopy = compiler.convertProgram(
244 fBaseProgram->fConfig->fKind, *fBaseProgram->fSource, settings);
245 SkASSERT(optimizedCopy);
246 if (optimizedCopy) {
247 const auto* mainDecl = optimizedCopy->getFunction("main");
248 SkASSERT(mainDecl);
249 if (mainDecl) {
250 programToUse = optimizedCopy.get();
251 mainToUse = mainDecl->definition();
252 }
253 }
254 }
255
256 SkSL::DebugTracePriv tempDebugTrace;
257 if (debugTrace) {
258 const_cast<SkRuntimeEffect*>(this)->fRPProgram = MakeRasterPipelineProgram(
•259 *programToUse, *mainToUse, debugTrace, /*writeTraceOps=*/true);
260 } else if (kRPEnableLiveTrace) {
261 debugTrace = &tempDebugTrace;
262 const_cast<SkRuntimeEffect*>(this)->fRPProgram = MakeRasterPipelineProgram(
•263 *programToUse, *mainToUse, debugTrace, /*writeTraceOps=*/false);
264 } else {
265 const_cast<SkRuntimeEffect*>(this)->fRPProgram = MakeRasterPipelineProgram(
•266 *programToUse, *mainToUse, /*debugTrace=*/nullptr, /*writeTraceOps=*/false);
267 }
268
269 if (kRPEnableLiveTrace) {
270 if (fRPProgram) {
271 SkDebugf("-----\n\n");
272 SkStreamPriv::DebugfStream stream;
273 fRPProgram->dump(&stream, /*writeInstructionCount=*/true);
274 SkDebugf("\n-----\n\n");
275 } else {
276 SkDebugf("----- RP unsupported -----\n\n");
277 }
278 }
279 });
280
281 return fRPProgram.get();
282 }
283
284 SkSpan<const float> SkRuntimeEffectPriv::UniformsAsSpan(
285 SkSpan<const SkRuntimeEffect::Uniform> uniforms,
286 sk_sp<const SkData> originalData,
287 bool alwaysCopyIntoAlloc,
288 const SkColorSpace* destColorSpace,
289 SkArenaAlloc* alloc) {
290 // Transform the uniforms into the destination colorspace.
291 sk_sp<const SkData> transformedData = SkRuntimeEffectPriv::TransformUniforms(uniforms,
292 originalData,
293 destColorSpace);
294 if (alwaysCopyIntoAlloc || originalData != transformedData) {
295 // The transformed uniform data's lifetime is not long enough to reuse; instead, we copy the
296 // uniform data directly into the alloc.
297 size_t numBytes = transformedData->size();
298 size_t numFloats = numBytes / sizeof(float);
299 float* uniformsInAlloc = alloc->makeArrayDefault<float>(numFloats);
300 memcpy(uniformsInAlloc, transformedData->data(), numBytes);
301 return {uniformsInAlloc, numFloats};
302 }
303 // It's safe to return a pointer into existing data.
304 return SkSpan{static_cast<const float*>(originalData->data()),
305 originalData->size() / sizeof(float)};
306 }
307
308 bool RuntimeEffectRPCallbacks::appendShader(int index) {
309 if (SkShader* shader = fChildren[index].shader()) {
310 if (fSampleUsages[index].isPassThrough()) {
311 // Given a passthrough sample, the total-matrix is still as valid as before.
312 return as_SB(shader)->appendStages(fStage, fMatrix);
313 }
314 // For a non-passthrough sample, we need to explicitly mark the total-matrix as invalid.
315 SkShaders::MatrixRec nonPassthroughMatrix = fMatrix;
316 nonPassthroughMatrix.markTotalMatrixInvalid();
317 return as_SB(shader)->appendStages(fStage, nonPassthroughMatrix);
318 }
319 // Return transparent black when a null shader is evaluated.
320 fStage.fPipeline->appendConstantColor(fStage.fAlloc, SkColors::kTransparent);
321 return true;
322 }
323 bool RuntimeEffectRPCallbacks::appendColorFilter(int index) {
324 if (SkColorFilter* colorFilter = fChildren[index].colorFilter()) {
325 return as_CFB(colorFilter)->appendStages(fStage, /*shaderIsOpaque=*/false);
326 }
327 // Return the original color as-is when a null child color filter is evaluated.
328 return true;
329 }
330 bool RuntimeEffectRPCallbacks::appendBlender(int index) {
331 if (SkBlender* blender = fChildren[index].blender()) {
332 return as_BB(blender)->appendStages(fStage);
333 }
334 // Return a source-over blend when a null blender is evaluated.
335 fStage.fPipeline->append(SkRasterPipelineOp::srcover);
336 return true;
337 }
338
339 // TODO: If an effect calls these intrinsics more than once, we could cache and re-use the steps
340 // object(s), rather than re-creating them in the arena repeatedly.
341 void RuntimeEffectRPCallbacks::toLinearSrgb(const void* color) {
342 if (fStage.fDstCS) {
343 SkColorSpaceXformSteps xform{fStage.fDstCS, kUnpremul_SkAlphaType,
344 sk_srgb_linear_singleton(), kUnpremul_SkAlphaType};
345 if (xform.fFlags.mask()) {
346 // We have a non-identity colorspace transform; apply it.
347 this->applyColorSpaceXform(xform, color);
348 }
349 }
350 }
351
352 void RuntimeEffectRPCallbacks::fromLinearSrgb(const void* color) {
353 if (fStage.fDstCS) {
354 SkColorSpaceXformSteps xform{sk_srgb_linear_singleton(), kUnpremul_SkAlphaType,
355 fStage.fDstCS, kUnpremul_SkAlphaType};
356 if (xform.fFlags.mask()) {
357 // We have a non-identity colorspace transform; apply it.
358 this->applyColorSpaceXform(xform, color);
359 }
360 }
361 }
362
363 void RuntimeEffectRPCallbacks::applyColorSpaceXform(const SkColorSpaceXformSteps& tempXform,
364 const void* color) {
365 // Copy the transform steps into our alloc.
366 SkColorSpaceXformSteps* xform = fStage.fAlloc->make<SkColorSpaceXformSteps>(tempXform);
367
368 // Put the color into src.rgba (and temporarily stash the execution mask there instead).
369 fStage.fPipeline->append(SkRasterPipelineOp::exchange_src, color);
370 // Add the color space transform to our raster pipeline.
371 xform->apply(fStage.fPipeline);
372 // Restore the execution mask, and move the color back into program data.
373 fStage.fPipeline->append(SkRasterPipelineOp::exchange_src, color);
374 }
375
376 bool SkRuntimeEffectPriv::CanDraw(const SkCapabilities* caps, const SkSL::Program* program) {
377 SkASSERT(caps && program);
378 SkASSERT(program->fConfig->enforcesSkSLVersion());
379 return program->fConfig->fRequiredSkSLVersion <= caps->skslVersion();
380 }
381
382 bool SkRuntimeEffectPriv::CanDraw(const SkCapabilities* caps, const SkRuntimeEffect* effect) {
383 SkASSERT(effect);
384 return CanDraw(caps, effect->fBaseProgram.get());
385 }
386
387 //////////////////////////////////////////////////////////////////////////////
388
389 static bool flattenable_is_valid_as_child(const SkFlattenable* f) {
390 if (!f) { return true; }
391 switch (f->getFlattenableType()) {
392 case SkFlattenable::kSkShader_Type:
393 case SkFlattenable::kSkColorFilter_Type:
394 case SkFlattenable::kSkBlender_Type:
395 return true;
396 default:
397 return false;
398 }
399 }
400
401 SkRuntimeEffect::ChildPtr::ChildPtr(sk_sp<SkFlattenable> f) : fChild(std::move(f)) {
402 SkASSERT(flattenable_is_valid_as_child(fChild.get()));
403 }
404
405 static bool verify_child_effects(const std::vector<SkRuntimeEffect::Child>& reflected,
406 SkSpan<const SkRuntimeEffect::ChildPtr> effectPtrs) {
407 // Verify that the number of passed-in child-effect pointers matches the SkSL code.
408 if (reflected.size() != effectPtrs.size()) {
409 return false;
410 }
411
412 // Verify that each child object's type matches its declared type in the SkSL.
413 for (size_t i = 0; i < effectPtrs.size(); ++i) {
414 std::optional<ChildType> effectType = effectPtrs[i].type();
415 if (effectType && effectType != reflected[i].type) {
416 return false;
417 }
418 }
419 return true;
420 }
421
422 /**
423 * If `effect` is specified, then the number and type of child objects are validated against the
424 * children() of `effect`. If it's nullptr, this is skipped, allowing deserialization of children,
425 * even when the effect could not be constructed (ie, due to malformed SkSL).
426 */
427 bool SkRuntimeEffectPriv::ReadChildEffects(SkReadBuffer& buffer,
428 const SkRuntimeEffect* effect,
429 TArray<SkRuntimeEffect::ChildPtr>* children) {
430 size_t childCount = buffer.read32();
431 if (effect && !buffer.validate(childCount == effect->children().size())) {
432 return false;
433 }
434
435 children->clear();
436 children->reserve_exact(childCount);
437
438 for (size_t i = 0; i < childCount; i++) {
439 sk_sp<SkFlattenable> obj(buffer.readRawFlattenable());
440 if (!flattenable_is_valid_as_child(obj.get())) {
441 buffer.validate(false);
442 return false;
443 }
444 children->push_back(std::move(obj));
445 }
446
447 // If we are validating against an effect, make sure any (non-null) children are the right type
448 if (effect) {
449 auto childInfo = effect->children();
450 SkASSERT(childInfo.size() == SkToSizeT(children->size()));
451 for (size_t i = 0; i < childCount; i++) {
452 std::optional<ChildType> ct = (*children)[i].type();
453 if (ct.has_value() && (*ct) != childInfo[i].type) {
454 buffer.validate(false);
455 }
456 }
457 }
458
459 return buffer.isValid();
460 }
461
462 void SkRuntimeEffectPriv::WriteChildEffects(
463 SkWriteBuffer& buffer, SkSpan<const SkRuntimeEffect::ChildPtr> children) {
464 buffer.write32(children.size());
465 for (const auto& child : children) {
466 buffer.writeFlattenable(child.flattenable());
467 }
468 }
469
470 SkSL::ProgramSettings SkRuntimeEffect::MakeSettings(const Options& options) {
•471 constexpr int kDisableSKSLInlining = 0;
472 SkSL::ProgramSettings settings;
•473 settings.fInlineThreshold = kDisableSKSLInlining;
474 settings.fForceNoInline = options.forceUnoptimized;
475 settings.fOptimize = !options.forceUnoptimized;
476 settings.fMaxVersionAllowed = options.maxVersionAllowed;
477
478 // SkSL created by the GPU backend is typically parsed, converted to a backend format,
479 // and the IR is immediately discarded. In that situation, it makes sense to use node
480 // pools to accelerate the IR allocations. Here, SkRuntimeEffect instances are often
481 // long-lived (especially those created internally for runtime FPs). In this situation,
482 // we're willing to pay for a slightly longer compile so that we don't waste huge
483 // amounts of memory.
484 settings.fUseMemoryPool = false;
485 return settings;
486 }
487
488 // TODO: Many errors aren't caught until we process the generated Program here. Catching those
489 // in the IR generator would provide better errors messages (with locations).
490 #define RETURN_FAILURE(...) return Result{nullptr, SkStringPrintf(__VA_ARGS__)}
491
492 SkRuntimeEffect::Result SkRuntimeEffect::MakeFromSource(SkString sksl,
493 const Options& options,
494 SkSL::ProgramKind kind) {
495 SkSL::Compiler compiler;
496 SkSL::ProgramSettings settings = MakeSettings(options);
497 std::unique_ptr<SkSL::Program> program =
498 compiler.convertProgram(kind, std::string(sksl.c_str(), sksl.size()), settings);
499
500 if (!program) {
501 RETURN_FAILURE("%s", compiler.errorText().c_str());
502 }
503
504 return MakeInternal(std::move(program), options, kind);
505 }
506
507 SkRuntimeEffect::Result SkRuntimeEffect::MakeInternal(std::unique_ptr<SkSL::Program> program,
508 const Options& options,
509 SkSL::ProgramKind kind) {
510 SkSL::Compiler compiler;
511
512 uint32_t flags = 0;
513 switch (kind) {
514 case SkSL::ProgramKind::kPrivateRuntimeColorFilter:
515 case SkSL::ProgramKind::kRuntimeColorFilter:
516 // TODO(skbug.com/40042585): Figure out a way to run ES3+ color filters on the CPU. This doesn't
517 // need to be fast - it could just be direct IR evaluation. But without it, there's no
518 // way for us to fully implement the SkColorFilter API (eg, `filterColor4f`)
519 if (!SkRuntimeEffectPriv::CanDraw(SkCapabilities::RasterBackend().get(),
520 program.get())) {
521 RETURN_FAILURE("SkSL color filters must target #version 100");
522 }
523 flags |= kAllowColorFilter_Flag;
524 break;
525 case SkSL::ProgramKind::kPrivateRuntimeShader:
526 case SkSL::ProgramKind::kRuntimeShader:
527 flags |= kAllowShader_Flag;
528 break;
529 case SkSL::ProgramKind::kPrivateRuntimeBlender:
530 case SkSL::ProgramKind::kRuntimeBlender:
531 flags |= kAllowBlender_Flag;
532 break;
533 default:
534 SkUNREACHABLE;
535 }
536
537 if (options.forceUnoptimized) {
538 flags |= kDisableOptimization_Flag;
539 }
540
541 // Find 'main', then locate the sample coords parameter. (It might not be present.)
542 const SkSL::FunctionDeclaration* main = program->getFunction("main");
543 if (!main) {
544 RETURN_FAILURE("missing 'main' function");
545 }
546 const SkSL::Variable* coordsParam = main->getMainCoordsParameter();
547
548 const SkSL::ProgramUsage::VariableCounts sampleCoordsUsage =
549 coordsParam ? program->usage()->get(*coordsParam)
550 : SkSL::ProgramUsage::VariableCounts{};
551
552 if (sampleCoordsUsage.fRead || sampleCoordsUsage.fWrite) {
553 flags |= kUsesSampleCoords_Flag;
554 }
555
556 // Color filters and blends are not allowed to depend on position (local or device) in any way.
557 // The signature of main, and the declarations in sksl_rt_colorfilter/sksl_rt_blend should
558 // guarantee this.
559 if (flags & (kAllowColorFilter_Flag | kAllowBlender_Flag)) {
560 SkASSERT(!(flags & kUsesSampleCoords_Flag));
561 SkASSERT(!SkSL::Analysis::ReferencesFragCoords(*program));
562 }
563
564 if (SkSL::Analysis::CallsSampleOutsideMain(*program)) {
565 flags |= kSamplesOutsideMain_Flag;
566 }
567
568 // Look for color filters that preserve the input alpha. This analysis is very conservative, and
569 // only returns true when the input alpha is returned as-is from main() with no intervening
570 // copies or arithmetic.
571 if (flags & kAllowColorFilter_Flag) {
572 if (SkSL::Analysis::ReturnsInputAlpha(*main->definition(), *program->usage())) {
573 flags |= kAlphaUnchanged_Flag;
574 }
575 }
576
577 // Determine if this effect uses of the color transform intrinsics. Effects need to know this
578 // so they can allocate color transform objects, etc.
579 if (SkSL::Analysis::CallsColorTransformIntrinsics(*program)) {
580 flags |= kUsesColorTransform_Flag;
581 }
582
583 // Shaders are the only thing that cares about this, but it's inexpensive (and safe) to call.
584 if (SkSL::Analysis::ReturnsOpaqueColor(*main->definition())) {
585 flags |= kAlwaysOpaque_Flag;
586 }
587
588 // Go through program elements, pulling out information that we need
589 size_t offset = 0;
590 std::vector<Uniform> uniforms;
591 std::vector<Child> children;
592 std::vector<SkSL::SampleUsage> sampleUsages;
593 int elidedSampleCoords = 0;
594 const SkSL::Context& ctx(compiler.context());
595
596 for (const SkSL::ProgramElement* elem : program->elements()) {
597 // Variables (uniform, etc.)
598 if (elem->is<SkSL::GlobalVarDeclaration>()) {
599 const SkSL::GlobalVarDeclaration& global = elem->as<SkSL::GlobalVarDeclaration>();
600 const SkSL::VarDeclaration& varDecl = global.declaration()->as<SkSL::VarDeclaration>();
601 const SkSL::Variable& var = *varDecl.var();
602
603 // Child effects that can be sampled ('shader', 'colorFilter', 'blender')
604 if (var.type().isEffectChild()) {
605 children.push_back(SkRuntimeEffectPriv::VarAsChild(var, children.size()));
606 auto usage = SkSL::Analysis::GetSampleUsage(
607 *program, var, sampleCoordsUsage.fWrite != 0, &elidedSampleCoords);
608 // If the child is never sampled, we pretend that it's actually in PassThrough mode.
609 // Otherwise, the GP code for collecting transforms and emitting transform code gets
610 // very confused, leading to asserts and bad (backend) shaders. There's an implicit
611 // assumption that every FP is used by its parent. (skbug.com/40043510)
612 sampleUsages.push_back(usage.isSampled() ? usage
613 : SkSL::SampleUsage::PassThrough());
614 }
615 // 'uniform' variables
616 else if (var.modifierFlags().isUniform()) {
617 uniforms.push_back(SkRuntimeEffectPriv::VarAsUniform(var, ctx, &offset));
618 }
619 }
620 }
621
622 // If the sample coords are never written to, then we will have converted sample calls that use
623 // them unmodified into "passthrough" sampling. If all references to the sample coords were of
624 // that form, then we don't actually "use" sample coords. We unset the flag to prevent creating
625 // an extra (unused) varying holding the coords.
626 if (elidedSampleCoords == sampleCoordsUsage.fRead && sampleCoordsUsage.fWrite == 0) {
627 flags &= ~kUsesSampleCoords_Flag;
628 }
629
630 #undef RETURN_FAILURE
631
632 sk_sp<SkRuntimeEffect> effect(new SkRuntimeEffect(std::move(program),
633 options,
634 *main->definition(),
635 std::move(uniforms),
636 std::move(children),
637 std::move(sampleUsages),
638 flags));
639 return Result{std::move(effect), SkString()};
640 }
641
642 sk_sp<SkRuntimeEffect> SkRuntimeEffect::makeUnoptimizedClone() {
643 // Compile with maximally-permissive options; any restrictions we need to enforce were already
644 // handled when the original SkRuntimeEffect was made. We don't keep around the Options struct
645 // from when it was initially made so we don't know what was originally requested.
646 Options options;
647 options.forceUnoptimized = true;
648 options.maxVersionAllowed = SkSL::Version::k300;
649 options.allowPrivateAccess = true;
650
651 // We do know the original ProgramKind, so we don't need to re-derive it.
652 SkSL::ProgramKind kind = fBaseProgram->fConfig->fKind;
653
654 // Attempt to recompile the program's source with optimizations off. This ensures that the
655 // Debugger shows results on every line, even for things that could be optimized away (static
656 // branches, unused variables, etc). If recompilation fails, we fall back to the original code.
657 SkSL::Compiler compiler;
658 SkSL::ProgramSettings settings = MakeSettings(options);
659 std::unique_ptr<SkSL::Program> program =
660 compiler.convertProgram(kind, *fBaseProgram->fSource, settings);
661
662 if (!program) {
663 // Turning off compiler optimizations can theoretically expose a program error that
664 // had been optimized away (e.g. "all control paths return a value" might be found on a path
665 // that is completely eliminated in the optimized program).
666 // If this happens, the debugger will just have to show the optimized code.
667 return sk_ref_sp(this);
668 }
669
670 SkRuntimeEffect::Result result = MakeInternal(std::move(program), options, kind);
671 if (!result.effect) {
672 // Nothing in MakeInternal should change as a result of optimizations being toggled.
673 SkDEBUGFAILF("makeUnoptimizedClone: MakeInternal failed\n%s",
674 result.errorText.c_str());
675 return sk_ref_sp(this);
676 }
677
678 return result.effect;
679 }
680
681 SkRuntimeEffect::Result SkRuntimeEffect::MakeForColorFilter(SkString sksl, const Options& options) {
682 auto programKind = options.allowPrivateAccess ? SkSL::ProgramKind::kPrivateRuntimeColorFilter
683 : SkSL::ProgramKind::kRuntimeColorFilter;
684 auto result = MakeFromSource(std::move(sksl), options, programKind);
685 SkASSERT(!result.effect || result.effect->allowColorFilter());
686 return result;
687 }
688
689 SkRuntimeEffect::Result SkRuntimeEffect::MakeForShader(SkString sksl, const Options& options) {
690 auto programKind = options.allowPrivateAccess ? SkSL::ProgramKind::kPrivateRuntimeShader
691 : SkSL::ProgramKind::kRuntimeShader;
692 auto result = MakeFromSource(std::move(sksl), options, programKind);
693 SkASSERT(!result.effect || result.effect->allowShader());
694 return result;
695 }
696
697 SkRuntimeEffect::Result SkRuntimeEffect::MakeForBlender(SkString sksl, const Options& options) {
698 auto programKind = options.allowPrivateAccess ? SkSL::ProgramKind::kPrivateRuntimeBlender
699 : SkSL::ProgramKind::kRuntimeBlender;
700 auto result = MakeFromSource(std::move(sksl), options, programKind);
701 SkASSERT(!result.effect || result.effect->allowBlender());
702 return result;
703 }
704
705 sk_sp<SkRuntimeEffect> SkMakeCachedRuntimeEffect(
706 SkRuntimeEffect::Result (*make)(SkString sksl, const SkRuntimeEffect::Options&),
707 SkString sksl) {
708 static SkNoDestructor<SkMutex> mutex;
709 static SkNoDestructor<SkLRUCache<uint64_t, sk_sp<SkRuntimeEffect>>> cache(11 /*arbitrary*/);
710
711 uint64_t key = SkChecksum::Hash64(sksl.c_str(), sksl.size());
712 {
713 SkAutoMutexExclusive _(*mutex);
714 if (sk_sp<SkRuntimeEffect>* found = cache->find(key)) {
715 return *found;
716 }
717 }
718
719 SkRuntimeEffect::Options options;
720 SkRuntimeEffectPriv::AllowPrivateAccess(&options);
721
722 auto [effect, err] = make(std::move(sksl), options);
723 if (!effect) {
724 SkDEBUGFAILF("%s", err.c_str());
725 return nullptr;
726 }
727 SkASSERT(err.isEmpty());
728
729 {
730 SkAutoMutexExclusive _(*mutex);
731 cache->insert_or_update(key, effect);
732 }
733 return effect;
734 }
735
736 static size_t uniform_element_size(SkRuntimeEffect::Uniform::Type type) {
737 switch (type) {
738 case SkRuntimeEffect::Uniform::Type::kFloat: return sizeof(float);
739 case SkRuntimeEffect::Uniform::Type::kFloat2: return sizeof(float) * 2;
740 case SkRuntimeEffect::Uniform::Type::kFloat3: return sizeof(float) * 3;
741 case SkRuntimeEffect::Uniform::Type::kFloat4: return sizeof(float) * 4;
742
743 case SkRuntimeEffect::Uniform::Type::kFloat2x2: return sizeof(float) * 4;
744 case SkRuntimeEffect::Uniform::Type::kFloat3x3: return sizeof(float) * 9;
745 case SkRuntimeEffect::Uniform::Type::kFloat4x4: return sizeof(float) * 16;
746
747 case SkRuntimeEffect::Uniform::Type::kInt: return sizeof(int);
748 case SkRuntimeEffect::Uniform::Type::kInt2: return sizeof(int) * 2;
749 case SkRuntimeEffect::Uniform::Type::kInt3: return sizeof(int) * 3;
750 case SkRuntimeEffect::Uniform::Type::kInt4: return sizeof(int) * 4;
751 default: SkUNREACHABLE;
752 }
753 }
754
755 size_t SkRuntimeEffect::Uniform::sizeInBytes() const {
756 static_assert(sizeof(int) == sizeof(float));
757 return uniform_element_size(this->type) * this->count;
758 }
759
760 SkRuntimeEffect::SkRuntimeEffect(std::unique_ptr<SkSL::Program> baseProgram,
761 const Options& options,
762 const SkSL::FunctionDefinition& main,
763 std::vector<Uniform>&& uniforms,
764 std::vector<Child>&& children,
765 std::vector<SkSL::SampleUsage>&& sampleUsages,
766 uint32_t flags)
767 : fHash(SkChecksum::Hash32(baseProgram->fSource->c_str(), baseProgram->fSource->size()))
768 , fStableKey(options.fStableKey)
769 , fName(options.fName)
770 , fBaseProgram(std::move(baseProgram))
771 , fMain(main)
772 , fUniforms(std::move(uniforms))
773 , fChildren(std::move(children))
774 , fSampleUsages(std::move(sampleUsages))
775 , fFlags(flags) {
776 SkASSERT(fBaseProgram);
777 SkASSERT(fChildren.size() == fSampleUsages.size());
778
779 // Everything from SkRuntimeEffect::Options which could influence the compiled result needs to
780 // be accounted for in `fHash`. If you've added a new field to Options and caused the static-
781 // assert below to trigger, please incorporate your field into `fHash` and update KnownOptions
782 // to match the layout of Options.
783 struct KnownOptions {
784 bool forceUnoptimized;
785 std::string_view fName;
786 bool allowPrivateAccess;
787 uint32_t fStableKey;
788 SkSL::Version maxVersionAllowed;
789 };
790 static_assert(sizeof(Options) == sizeof(KnownOptions));
791 fHash = SkChecksum::Hash32(&options.forceUnoptimized,
792 sizeof(options.forceUnoptimized), fHash);
793 fHash = SkChecksum::Hash32(&options.allowPrivateAccess,
794 sizeof(options.allowPrivateAccess), fHash);
795 fHash = SkChecksum::Hash32(&options.fStableKey,
796 sizeof(options.fStableKey), fHash);
797 fHash = SkChecksum::Hash32(&options.maxVersionAllowed,
798 sizeof(options.maxVersionAllowed), fHash);
799 }
800
801 SkRuntimeEffect::~SkRuntimeEffect() = default;
802
803 const std::string& SkRuntimeEffect::source() const {
804 return *fBaseProgram->fSource;
805 }
806
807 size_t SkRuntimeEffect::uniformSize() const {
808 return fUniforms.empty() ? 0
809 : SkAlign4(fUniforms.back().offset + fUniforms.back().sizeInBytes());
810 }
811
812 const SkRuntimeEffect::Uniform* SkRuntimeEffect::findUniform(std::string_view name) const {
813 auto iter = std::find_if(fUniforms.begin(), fUniforms.end(), [name](const Uniform& u) {
814 return u.name == name;
815 });
816 return iter == fUniforms.end() ? nullptr : &(*iter);
817 }
818
819 const SkRuntimeEffect::Child* SkRuntimeEffect::findChild(std::string_view name) const {
820 auto iter = std::find_if(fChildren.begin(), fChildren.end(), [name](const Child& c) {
821 return c.name == name;
822 });
823 return iter == fChildren.end() ? nullptr : &(*iter);
824 }
825
826 ///////////////////////////////////////////////////////////////////////////////////////////////////
827
828 sk_sp<SkShader> SkRuntimeEffectPriv::MakeDeferredShader(
829 const SkRuntimeEffect* effect,
830 UniformsCallback uniformsCallback,
831 SkSpan<const SkRuntimeEffect::ChildPtr> children,
832 const SkMatrix* localMatrix) {
833 if (!effect->allowShader()) {
834 return nullptr;
835 }
836 if (!verify_child_effects(effect->fChildren, children)) {
837 return nullptr;
838 }
839 if (!uniformsCallback) {
840 return nullptr;
841 }
842 return SkLocalMatrixShader::MakeWrapped<SkRuntimeShader>(localMatrix,
843 sk_ref_sp(effect),
844 /*debugTrace=*/nullptr,
845 std::move(uniformsCallback),
846 children);
847 }
848
849 sk_sp<SkShader> SkRuntimeEffect::makeShader(sk_sp<const SkData> uniforms,
850 sk_sp<SkShader> childShaders[],
851 size_t childCount,
852 const SkMatrix* localMatrix) const {
853 STArray<4, ChildPtr> children(childCount);
854 for (size_t i = 0; i < childCount; ++i) {
855 children.emplace_back(childShaders[i]);
856 }
857 return this->makeShader(std::move(uniforms), SkSpan(children), localMatrix);
858 }
859
860 sk_sp<SkShader> SkRuntimeEffect::makeShader(sk_sp<const SkData> uniforms,
861 SkSpan<const ChildPtr> children,
862 const SkMatrix* localMatrix) const {
863 if (!this->allowShader()) {
864 return nullptr;
865 }
866 if (!verify_child_effects(fChildren, children)) {
867 return nullptr;
868 }
869 if (!uniforms) {
870 uniforms = SkData::MakeEmpty();
871 }
872 if (uniforms->size() != this->uniformSize()) {
873 return nullptr;
874 }
875 return SkLocalMatrixShader::MakeWrapped<SkRuntimeShader>(localMatrix,
876 sk_ref_sp(this),
877 /*debugTrace=*/nullptr,
878 std::move(uniforms),
879 children);
880 }
881
882 sk_sp<SkColorFilter> SkRuntimeEffect::makeColorFilter(sk_sp<const SkData> uniforms,
883 sk_sp<SkColorFilter> childColorFilters[],
884 size_t childCount) const {
885 STArray<4, ChildPtr> children(childCount);
886 for (size_t i = 0; i < childCount; ++i) {
887 children.emplace_back(childColorFilters[i]);
888 }
889 return this->makeColorFilter(std::move(uniforms), SkSpan(children));
890 }
891
892 sk_sp<SkColorFilter> SkRuntimeEffect::makeColorFilter(sk_sp<const SkData> uniforms,
893 SkSpan<const ChildPtr> children) const {
894 if (!this->allowColorFilter()) {
895 return nullptr;
896 }
897 if (!verify_child_effects(fChildren, children)) {
898 return nullptr;
899 }
900 if (!uniforms) {
901 uniforms = SkData::MakeEmpty();
902 }
903 if (uniforms->size() != this->uniformSize()) {
904 return nullptr;
905 }
906 return sk_make_sp<SkRuntimeColorFilter>(sk_ref_sp(this), std::move(uniforms), children);
907 }
908
909 sk_sp<SkColorFilter> SkRuntimeEffect::makeColorFilter(sk_sp<const SkData> uniforms) const {
910 return this->makeColorFilter(std::move(uniforms), /*children=*/{});
911 }
912
913 sk_sp<SkBlender> SkRuntimeEffect::makeBlender(sk_sp<const SkData> uniforms,
914 SkSpan<const ChildPtr> children) const {
915 if (!this->allowBlender()) {
916 return nullptr;
917 }
918 if (!verify_child_effects(fChildren, children)) {
919 return nullptr;
920 }
921 if (!uniforms) {
922 uniforms = SkData::MakeEmpty();
923 }
924 if (uniforms->size() != this->uniformSize()) {
925 return nullptr;
926 }
927 return sk_make_sp<SkRuntimeBlender>(sk_ref_sp(this), std::move(uniforms), children);
928 }
929
930 ///////////////////////////////////////////////////////////////////////////////////////////////////
931
932 SkRuntimeEffect::TracedShader SkRuntimeEffect::MakeTraced(sk_sp<SkShader> shader,
933 const SkIPoint& traceCoord) {
934 SkRuntimeEffect* effect = as_SB(shader)->asRuntimeEffect();
935 if (!effect) {
936 return TracedShader{nullptr, nullptr};
937 }
938 // An SkShader with an attached SkRuntimeEffect must be an SkRuntimeShader.
939 SkRuntimeShader* rtShader = static_cast<SkRuntimeShader*>(shader.get());
940 return rtShader->makeTracedClone(traceCoord);
941 }
942
943 ///////////////////////////////////////////////////////////////////////////////////////////////////
944
945 std::optional<ChildType> SkRuntimeEffect::ChildPtr::type() const {
946 if (fChild) {
947 switch (fChild->getFlattenableType()) {
948 case SkFlattenable::kSkShader_Type:
949 return ChildType::kShader;
950 case SkFlattenable::kSkColorFilter_Type:
951 return ChildType::kColorFilter;
952 case SkFlattenable::kSkBlender_Type:
953 return ChildType::kBlender;
954 default:
955 break;
956 }
957 }
958 return std::nullopt;
959 }
960
961 SkShader* SkRuntimeEffect::ChildPtr::shader() const {
962 return (fChild && fChild->getFlattenableType() == SkFlattenable::kSkShader_Type)
963 ? static_cast<SkShader*>(fChild.get())
964 : nullptr;
965 }
966
967 SkColorFilter* SkRuntimeEffect::ChildPtr::colorFilter() const {
968 return (fChild && fChild->getFlattenableType() == SkFlattenable::kSkColorFilter_Type)
969 ? static_cast<SkColorFilter*>(fChild.get())
970 : nullptr;
971 }
972
973 SkBlender* SkRuntimeEffect::ChildPtr::blender() const {
974 return (fChild && fChild->getFlattenableType() == SkFlattenable::kSkBlender_Type)
975 ? static_cast<SkBlender*>(fChild.get())
976 : nullptr;
977 }
978
979 ///////////////////////////////////////////////////////////////////////////////////////////////////
980
981 void SkRuntimeEffect::RegisterFlattenables() {
982 SK_REGISTER_FLATTENABLE(SkRuntimeBlender);
983 SK_REGISTER_FLATTENABLE(SkRuntimeColorFilter);
984 SK_REGISTER_FLATTENABLE(SkRuntimeShader);
985
986 // Previous name
987 SkFlattenable::Register("SkRTShader", SkRuntimeShader::CreateProc);
988 }
989
990 sk_sp<SkShader> SkRuntimeEffectBuilder::makeShader(const SkMatrix* localMatrix) const {
991 return this->effect()->makeShader(this->uniforms(), this->children(), localMatrix);
992 }
993
994 sk_sp<SkBlender> SkRuntimeEffectBuilder::makeBlender() const {
995 return this->effect()->makeBlender(this->uniforms(), this->children());
996 }
997
998 sk_sp<SkColorFilter> SkRuntimeEffectBuilder::makeColorFilter() const {
999 return this->effect()->makeColorFilter(this->uniforms(), this->children());
1000 }