blob: c0486d0ed37513f57580c763f58338a3c904b367 [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
Mike Klein6ad99092016-10-26 10:35:22 -04007
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLCompiler.h"
ethannicholasb3058bd2016-07-01 08:22:01 -07009
John Stilesfbd050b2020-08-03 13:21:46 -040010#include <memory>
John Stilesb8e010c2020-08-11 18:05:39 -040011#include <unordered_set>
John Stilesfbd050b2020-08-03 13:21:46 -040012
Ethan Nicholas55a63af2021-05-18 10:12:58 -040013#include "include/sksl/DSLCore.h"
Leon Scrogginsb66214e2021-02-11 17:14:18 -050014#include "src/core/SkTraceEvent.h"
John Stilesb92641c2020-08-31 18:09:01 -040015#include "src/sksl/SkSLAnalysis.h"
John Stilesf3a28db2021-03-10 23:00:47 -050016#include "src/sksl/SkSLConstantFolder.h"
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -040017#include "src/sksl/SkSLDSLParser.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "src/sksl/SkSLIRGenerator.h"
Brian Osman00185012021-02-04 16:07:11 -050019#include "src/sksl/SkSLOperators.h"
John Stiles270cec22021-02-17 12:59:36 -050020#include "src/sksl/SkSLProgramSettings.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040021#include "src/sksl/SkSLRehydrator.h"
John Stiles3738ef52021-04-13 10:41:57 -040022#include "src/sksl/codegen/SkSLGLSLCodeGenerator.h"
John Stiles3738ef52021-04-13 10:41:57 -040023#include "src/sksl/codegen/SkSLMetalCodeGenerator.h"
24#include "src/sksl/codegen/SkSLSPIRVCodeGenerator.h"
25#include "src/sksl/codegen/SkSLSPIRVtoHLSL.h"
Ethan Nicholas55a63af2021-05-18 10:12:58 -040026#include "src/sksl/dsl/priv/DSLWriter.h"
27#include "src/sksl/dsl/priv/DSL_priv.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050028#include "src/sksl/ir/SkSLExpression.h"
29#include "src/sksl/ir/SkSLExpressionStatement.h"
30#include "src/sksl/ir/SkSLFunctionCall.h"
John Stiles7591d4b2021-09-13 13:32:06 -040031#include "src/sksl/ir/SkSLLiteral.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050032#include "src/sksl/ir/SkSLModifiersDeclaration.h"
33#include "src/sksl/ir/SkSLNop.h"
34#include "src/sksl/ir/SkSLSymbolTable.h"
35#include "src/sksl/ir/SkSLTernaryExpression.h"
36#include "src/sksl/ir/SkSLUnresolvedFunction.h"
37#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stilese6150002020-10-05 12:03:53 -040038#include "src/utils/SkBitSet.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070039
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040040#include <fstream>
41
Ethan Nicholasa11035b2019-11-26 16:27:47 -050042#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
43#include "include/gpu/GrContextOptions.h"
44#include "src/gpu/GrShaderCaps.h"
45#endif
46
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040047#ifdef SK_ENABLE_SPIRV_VALIDATION
48#include "spirv-tools/libspirv.hpp"
49#endif
50
Brian Osman3d87e9f2020-10-08 11:50:22 -040051#if defined(SKSL_STANDALONE)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040052
Brian Osman3d87e9f2020-10-08 11:50:22 -040053// In standalone mode, we load the textual sksl source files. GN generates or copies these files
54// to the skslc executable directory. The "data" in this mode is just the filename.
55#define MODULE_DATA(name) MakeModulePath("sksl_" #name ".sksl")
56
57#else
58
59// At runtime, we load the dehydrated sksl data files. The data is a (pointer, size) pair.
Ethan Nicholasc18bb512020-07-28 14:46:53 -040060#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040061#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
Brian Osmanb06301e2020-11-06 11:45:36 -050062#include "src/sksl/generated/sksl_public.dehydrated.sksl"
Brian Osmancbb60bd2021-04-12 09:49:20 -040063#include "src/sksl/generated/sksl_rt_shader.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040064#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
65
Brian Osman3d87e9f2020-10-08 11:50:22 -040066#define MODULE_DATA(name) MakeModuleData(SKSL_INCLUDE_sksl_##name,\
67 SKSL_INCLUDE_sksl_##name##_LENGTH)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040068
69#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040070
ethannicholasb3058bd2016-07-01 08:22:01 -070071namespace SkSL {
72
John Stiles7247b482021-03-08 10:40:35 -050073// These flags allow tools like Viewer or Nanobench to override the compiler's ProgramSettings.
John Stiles2ee4d7a2021-03-30 10:30:47 -040074Compiler::OverrideFlag Compiler::sOptimizer = OverrideFlag::kDefault;
75Compiler::OverrideFlag Compiler::sInliner = OverrideFlag::kDefault;
John Stiles8ef4d6c2021-03-05 16:01:45 -050076
John Stiles47c0a742021-02-09 09:30:35 -050077using RefKind = VariableReference::RefKind;
78
Brian Osman88cda172020-10-09 12:05:16 -040079class AutoSource {
80public:
Ethan Nicholasb449fff2021-08-04 15:06:37 -040081 AutoSource(Compiler* compiler, const char* source)
John Stilesa289ac22021-05-06 07:35:35 -040082 : fCompiler(compiler) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040083 SkASSERT(!fCompiler->errorReporter().source());
84 fCompiler->errorReporter().setSource(source);
Brian Osman88cda172020-10-09 12:05:16 -040085 }
86
John Stilesa289ac22021-05-06 07:35:35 -040087 ~AutoSource() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040088 fCompiler->errorReporter().setSource(nullptr);
John Stilesa289ac22021-05-06 07:35:35 -040089 }
Brian Osman88cda172020-10-09 12:05:16 -040090
91 Compiler* fCompiler;
Brian Osman88cda172020-10-09 12:05:16 -040092};
93
John Stilesa935c3f2021-02-25 10:35:49 -050094class AutoProgramConfig {
95public:
96 AutoProgramConfig(std::shared_ptr<Context>& context, ProgramConfig* config)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040097 : fContext(context.get())
98 , fOldConfig(fContext->fConfig) {
John Stilesa935c3f2021-02-25 10:35:49 -050099 fContext->fConfig = config;
100 }
101
102 ~AutoProgramConfig() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400103 fContext->fConfig = fOldConfig;
John Stilesa935c3f2021-02-25 10:35:49 -0500104 }
105
106 Context* fContext;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400107 ProgramConfig* fOldConfig;
John Stilesa935c3f2021-02-25 10:35:49 -0500108};
109
John Stiles10d39d92021-05-04 16:13:14 -0400110class AutoModifiersPool {
111public:
112 AutoModifiersPool(std::shared_ptr<Context>& context, ModifiersPool* modifiersPool)
113 : fContext(context.get()) {
114 SkASSERT(!fContext->fModifiersPool);
115 fContext->fModifiersPool = modifiersPool;
116 }
117
118 ~AutoModifiersPool() {
119 fContext->fModifiersPool = nullptr;
120 }
121
122 Context* fContext;
123};
124
John Stilesd6a5f4492021-02-11 15:46:11 -0500125Compiler::Compiler(const ShaderCapsClass* caps)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400126 : fErrorReporter(this)
John Stiles2dda4b62021-09-16 13:18:10 -0400127 , fContext(std::make_shared<Context>(fErrorReporter, *caps, fMangler))
John Stilesa47b3512021-05-04 16:15:00 -0400128 , fInliner(fContext.get()) {
John Stilesc1a98b82021-02-24 13:35:02 -0500129 SkASSERT(caps);
John Stilesb624b722021-08-13 12:16:13 -0400130 fRootModule.fSymbols = this->makeRootSymbolTable();
131 fPrivateModule.fSymbols = this->makePrivateSymbolTable(fRootModule.fSymbols);
John Stilesc1a98b82021-02-24 13:35:02 -0500132 fIRGenerator = std::make_unique<IRGenerator>(fContext.get());
John Stilesb624b722021-08-13 12:16:13 -0400133}
134
135Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700136
John Stiles54e7c052021-01-11 14:22:36 -0500137#define TYPE(t) fContext->fTypes.f ## t .get()
ethannicholasb3058bd2016-07-01 08:22:01 -0700138
John Stilesb624b722021-08-13 12:16:13 -0400139std::shared_ptr<SymbolTable> Compiler::makeRootSymbolTable() {
Ethan Nicholasc7774a72021-08-27 15:34:05 -0400140 auto rootSymbolTable = std::make_shared<SymbolTable>(*fContext, /*builtin=*/true);
John Stilesb624b722021-08-13 12:16:13 -0400141
Brian Osmanb06301e2020-11-06 11:45:36 -0500142 const SkSL::Symbol* rootTypes[] = {
143 TYPE(Void),
Brian Salomonbf7b6202016-11-11 16:08:03 -0500144
Brian Osmanb06301e2020-11-06 11:45:36 -0500145 TYPE( Float), TYPE( Float2), TYPE( Float3), TYPE( Float4),
146 TYPE( Half), TYPE( Half2), TYPE( Half3), TYPE( Half4),
147 TYPE( Int), TYPE( Int2), TYPE( Int3), TYPE( Int4),
John Stiles823c5042021-08-17 12:09:00 -0400148 TYPE( UInt), TYPE( UInt2), TYPE( UInt3), TYPE( UInt4),
149 TYPE( Short), TYPE( Short2), TYPE( Short3), TYPE( Short4),
150 TYPE(UShort), TYPE(UShort2), TYPE(UShort3), TYPE(UShort4),
Brian Osmanb06301e2020-11-06 11:45:36 -0500151 TYPE( Bool), TYPE( Bool2), TYPE( Bool3), TYPE( Bool4),
Brian Salomon2a51de82016-11-16 12:06:01 -0500152
John Stiles823c5042021-08-17 12:09:00 -0400153 TYPE(Float2x2), TYPE(Float2x3), TYPE(Float2x4),
154 TYPE(Float3x2), TYPE(Float3x3), TYPE(Float3x4),
155 TYPE(Float4x2), TYPE(Float4x3), TYPE(Float4x4),
156
157 TYPE(Half2x2), TYPE(Half2x3), TYPE(Half2x4),
158 TYPE(Half3x2), TYPE(Half3x3), TYPE(Half3x4),
159 TYPE(Half4x2), TYPE(Half4x3), TYPE(Half4x4),
Greg Daniel64773e62016-11-22 09:44:03 -0500160
Brian Osmanc63f4312020-12-23 11:44:14 -0500161 TYPE(SquareMat), TYPE(SquareHMat),
John Stiles823c5042021-08-17 12:09:00 -0400162 TYPE(Mat), TYPE(HMat),
ethannicholasb3058bd2016-07-01 08:22:01 -0700163
John Stiles823c5042021-08-17 12:09:00 -0400164 // TODO(skia:12349): generic short/ushort
165 TYPE(GenType), TYPE(GenIType), TYPE(GenUType),
166 TYPE(GenHType), /* (GenSType) (GenUSType) */
167 TYPE(GenBType),
168
169 TYPE(Vec), TYPE(IVec), TYPE(UVec),
170 TYPE(HVec), TYPE(SVec), TYPE(USVec),
171 TYPE(BVec),
Brian Osmanb06301e2020-11-06 11:45:36 -0500172
Brian Osman14d00962021-04-02 17:04:35 -0400173 TYPE(ColorFilter),
174 TYPE(Shader),
John Stilesbb2ef922021-07-26 08:32:07 -0400175 TYPE(Blender),
Brian Osmanb06301e2020-11-06 11:45:36 -0500176 };
177
John Stilesb624b722021-08-13 12:16:13 -0400178 for (const SkSL::Symbol* type : rootTypes) {
179 rootSymbolTable->addWithoutOwnership(type);
180 }
181
182 return rootSymbolTable;
183}
184
185std::shared_ptr<SymbolTable> Compiler::makePrivateSymbolTable(std::shared_ptr<SymbolTable> parent) {
186 auto privateSymbolTable = std::make_shared<SymbolTable>(parent, /*builtin=*/true);
187
Brian Osmanb06301e2020-11-06 11:45:36 -0500188 const SkSL::Symbol* privateTypes[] = {
189 TYPE(Sampler1D), TYPE(Sampler2D), TYPE(Sampler3D),
190 TYPE(SamplerExternalOES),
Brian Osmanb06301e2020-11-06 11:45:36 -0500191 TYPE(Sampler2DRect),
Brian Osmanb06301e2020-11-06 11:45:36 -0500192
193 TYPE(ISampler2D),
Brian Osmanb06301e2020-11-06 11:45:36 -0500194 TYPE(SubpassInput), TYPE(SubpassInputMS),
195
Brian Osmanb06301e2020-11-06 11:45:36 -0500196 TYPE(Sampler),
197 TYPE(Texture2D),
198 };
199
Brian Osmanb06301e2020-11-06 11:45:36 -0500200 for (const SkSL::Symbol* type : privateTypes) {
John Stilesb624b722021-08-13 12:16:13 -0400201 privateSymbolTable->addWithoutOwnership(type);
Brian Osmanb06301e2020-11-06 11:45:36 -0500202 }
203
Brian Osman3887a012020-09-30 13:22:27 -0400204 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
205 // treat it as builtin (ie, no need to clone it into the Program).
Brian Osmancc914522021-09-24 18:58:37 +0000206 privateSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
John Stilesb624b722021-08-13 12:16:13 -0400207 fCoreModifiers.add(Modifiers{}),
208 "sk_Caps",
209 fContext->fTypes.fSkCaps.get(),
210 /*builtin=*/false,
211 Variable::Storage::kGlobal));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500212
John Stilesb624b722021-08-13 12:16:13 -0400213 return privateSymbolTable;
ethannicholasb3058bd2016-07-01 08:22:01 -0700214}
215
John Stilesb624b722021-08-13 12:16:13 -0400216#undef TYPE
ethannicholasb3058bd2016-07-01 08:22:01 -0700217
Brian Osman56269982020-11-20 12:38:07 -0500218const ParsedModule& Compiler::loadGPUModule() {
219 if (!fGPUModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500220 fGPUModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(gpu), fPrivateModule);
Brian Osman56269982020-11-20 12:38:07 -0500221 }
222 return fGPUModule;
223}
224
225const ParsedModule& Compiler::loadFragmentModule() {
226 if (!fFragmentModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500227 fFragmentModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(frag),
Brian Osman56269982020-11-20 12:38:07 -0500228 this->loadGPUModule());
229 }
230 return fFragmentModule;
231}
232
233const ParsedModule& Compiler::loadVertexModule() {
234 if (!fVertexModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500235 fVertexModule = this->parseModule(ProgramKind::kVertex, MODULE_DATA(vert),
Brian Osman56269982020-11-20 12:38:07 -0500236 this->loadGPUModule());
237 }
238 return fVertexModule;
239}
240
Brian Osmancbb60bd2021-04-12 09:49:20 -0400241static void add_glsl_type_aliases(SkSL::SymbolTable* symbols, const SkSL::BuiltinTypes& types) {
242 // Add some aliases to the runtime effect modules so that it's friendlier, and more like GLSL
243 symbols->addAlias("vec2", types.fFloat2.get());
244 symbols->addAlias("vec3", types.fFloat3.get());
245 symbols->addAlias("vec4", types.fFloat4.get());
246
247 symbols->addAlias("ivec2", types.fInt2.get());
248 symbols->addAlias("ivec3", types.fInt3.get());
249 symbols->addAlias("ivec4", types.fInt4.get());
250
251 symbols->addAlias("bvec2", types.fBool2.get());
252 symbols->addAlias("bvec3", types.fBool3.get());
253 symbols->addAlias("bvec4", types.fBool4.get());
254
255 symbols->addAlias("mat2", types.fFloat2x2.get());
256 symbols->addAlias("mat3", types.fFloat3x3.get());
257 symbols->addAlias("mat4", types.fFloat4x4.get());
258}
259
Brian Osmana8b897b2021-08-30 16:40:44 -0400260const ParsedModule& Compiler::loadPublicModule() {
261 if (!fPublicModule.fSymbols) {
262 fPublicModule = this->parseModule(ProgramKind::kGeneric, MODULE_DATA(public), fRootModule);
263 add_glsl_type_aliases(fPublicModule.fSymbols.get(), fContext->fTypes);
Brian Osmancbb60bd2021-04-12 09:49:20 -0400264 }
Brian Osmana8b897b2021-08-30 16:40:44 -0400265 return fPublicModule;
Brian Osmancbb60bd2021-04-12 09:49:20 -0400266}
267
268const ParsedModule& Compiler::loadRuntimeShaderModule() {
269 if (!fRuntimeShaderModule.fSymbols) {
270 fRuntimeShaderModule = this->parseModule(
271 ProgramKind::kRuntimeShader, MODULE_DATA(rt_shader), this->loadPublicModule());
Brian Osmancbb60bd2021-04-12 09:49:20 -0400272 }
273 return fRuntimeShaderModule;
274}
275
John Stilesdbd4e6f2021-02-16 13:29:15 -0500276const ParsedModule& Compiler::moduleForProgramKind(ProgramKind kind) {
Brian Osman88cda172020-10-09 12:05:16 -0400277 switch (kind) {
Brian Osmana8b897b2021-08-30 16:40:44 -0400278 case ProgramKind::kVertex: return this->loadVertexModule(); break;
279 case ProgramKind::kFragment: return this->loadFragmentModule(); break;
280 case ProgramKind::kRuntimeColorFilter: return this->loadPublicModule(); break;
281 case ProgramKind::kRuntimeShader: return this->loadRuntimeShaderModule(); break;
282 case ProgramKind::kRuntimeBlender: return this->loadPublicModule(); break;
283 case ProgramKind::kGeneric: return this->loadPublicModule(); break;
Brian Osman88cda172020-10-09 12:05:16 -0400284 }
285 SkUNREACHABLE;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400286}
287
John Stilesdbd4e6f2021-02-16 13:29:15 -0500288LoadedModule Compiler::loadModule(ProgramKind kind,
Brian Osman3d87e9f2020-10-08 11:50:22 -0400289 ModuleData data,
John Stilesa935c3f2021-02-25 10:35:49 -0500290 std::shared_ptr<SymbolTable> base,
291 bool dehydrate) {
292 if (dehydrate) {
293 // NOTE: This is a workaround. When dehydrating includes, skslc doesn't know which module
294 // it's preparing, nor what the correct base module is. We can't use 'Root', because many
295 // GPU intrinsics reference private types, like samplers or textures. Today, 'Private' does
296 // contain the union of all known types, so this is safe. If we ever have types that only
297 // exist in 'Public' (for example), this logic needs to be smarter (by choosing the correct
298 // base for the module we're compiling).
John Stilesb624b722021-08-13 12:16:13 -0400299 base = fPrivateModule.fSymbols;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400300 }
John Stilesa935c3f2021-02-25 10:35:49 -0500301 SkASSERT(base);
302
John Stilesa47b3512021-05-04 16:15:00 -0400303 // Put the core-module modifier pool into the context.
304 AutoModifiersPool autoPool(fContext, &fCoreModifiers);
John Stiles10d39d92021-05-04 16:13:14 -0400305
John Stilesa935c3f2021-02-25 10:35:49 -0500306 // Built-in modules always use default program settings.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400307 Program::Settings settings;
308 settings.fReplaceSettings = !dehydrate;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400309
310#if defined(SKSL_STANDALONE)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400311 SkASSERT(this->errorCount() == 0);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400312 SkASSERT(data.fPath);
313 std::ifstream in(data.fPath);
John Stilesd51c9792021-03-18 11:40:14 -0400314 String text{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400315 if (in.rdstate()) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400316 printf("error reading %s\n", data.fPath);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400317 abort();
318 }
Brian Osman88cda172020-10-09 12:05:16 -0400319 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
Ethan Nicholas051aeb72021-09-24 16:39:19 -0400320 LoadedModule result = DSLParser(this, settings, kind,
321 std::move(text)).moduleInheritingFrom(std::move(baseModule));
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400322 if (this->errorCount()) {
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400323 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400324 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400325 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400326#else
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400327 ProgramConfig config;
328 config.fKind = kind;
329 config.fSettings = settings;
330 AutoProgramConfig autoConfig(fContext, &config);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400331 SkASSERT(data.fData && (data.fSize != 0));
John Stiles10d39d92021-05-04 16:13:14 -0400332 Rehydrator rehydrator(fContext.get(), base, data.fData, data.fSize);
Ethan Nicholas051aeb72021-09-24 16:39:19 -0400333 LoadedModule result = { kind, rehydrator.symbolTable(), rehydrator.elements() };
Brian Osman3d87e9f2020-10-08 11:50:22 -0400334#endif
335
Ethan Nicholas051aeb72021-09-24 16:39:19 -0400336 return result;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400337}
338
John Stilesdbd4e6f2021-02-16 13:29:15 -0500339ParsedModule Compiler::parseModule(ProgramKind kind, ModuleData data, const ParsedModule& base) {
John Stilesa935c3f2021-02-25 10:35:49 -0500340 LoadedModule module = this->loadModule(kind, data, base.fSymbols, /*dehydrate=*/false);
Brian Osman0006ad02020-11-18 15:38:39 -0500341 this->optimize(module);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400342
343 // For modules that just declare (but don't define) intrinsic functions, there will be no new
344 // program elements. In that case, we can share our parent's intrinsic map:
Brian Osman0006ad02020-11-18 15:38:39 -0500345 if (module.fElements.empty()) {
John Stiles10d39d92021-05-04 16:13:14 -0400346 return ParsedModule{module.fSymbols, base.fIntrinsics};
Brian Osman3d87e9f2020-10-08 11:50:22 -0400347 }
348
349 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
350
351 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
352 // global objects to the declaring ProgramElement.
Brian Osman0006ad02020-11-18 15:38:39 -0500353 for (std::unique_ptr<ProgramElement>& element : module.fElements) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400354 switch (element->kind()) {
355 case ProgramElement::Kind::kFunction: {
356 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400357 SkASSERT(f.declaration().isBuiltin());
358 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400359 break;
360 }
John Stiles569249b2020-11-03 12:18:22 -0500361 case ProgramElement::Kind::kFunctionPrototype: {
362 // These are already in the symbol table.
363 break;
364 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400365 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400366 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
367 const Variable& var = global.declaration()->as<VarDeclaration>().var();
368 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400369 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400370 break;
371 }
372 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400373 const Variable& var = element->as<InterfaceBlock>().variable();
374 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400375 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400376 break;
377 }
378 default:
379 printf("Unsupported element: %s\n", element->description().c_str());
380 SkASSERT(false);
381 break;
382 }
383 }
384
John Stiles10d39d92021-05-04 16:13:14 -0400385 return ParsedModule{module.fSymbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400386}
387
Brian Osman32d53552020-09-23 13:55:20 -0400388std::unique_ptr<Program> Compiler::convertProgram(
John Stilesdbd4e6f2021-02-16 13:29:15 -0500389 ProgramKind kind,
Brian Osman32d53552020-09-23 13:55:20 -0400390 String text,
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400391 Program::Settings settings) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400392 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::convertProgram");
Leon Scrogginsb66214e2021-02-11 17:14:18 -0500393
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400394 SkASSERT(!settings.fExternalFunctions || (kind == ProgramKind::kGeneric));
Ethan Nicholas91164d12019-05-15 15:29:54 -0400395
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400396#if !SKSL_DSL_PARSER
Brian Osman0006ad02020-11-18 15:38:39 -0500397 // Loading and optimizing our base module might reset the inliner, so do that first,
398 // *then* configure the inliner with the settings for this program.
399 const ParsedModule& baseModule = this->moduleForProgramKind(kind);
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400400#endif
Brian Osman0006ad02020-11-18 15:38:39 -0500401
John Stiles2ee4d7a2021-03-30 10:30:47 -0400402 // Honor our optimization-override flags.
403 switch (sOptimizer) {
404 case OverrideFlag::kDefault:
405 break;
406 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400407 settings.fOptimize = false;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400408 break;
409 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400410 settings.fOptimize = true;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400411 break;
412 }
413
414 switch (sInliner) {
415 case OverrideFlag::kDefault:
416 break;
417 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400418 settings.fInlineThreshold = 0;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400419 break;
420 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400421 if (settings.fInlineThreshold == 0) {
422 settings.fInlineThreshold = kDefaultInlineThreshold;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400423 }
424 break;
425 }
John Stiles7247b482021-03-08 10:40:35 -0500426
427 // Disable optimization settings that depend on a parent setting which has been disabled.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400428 settings.fInlineThreshold *= (int)settings.fOptimize;
429 settings.fRemoveDeadFunctions &= settings.fOptimize;
430 settings.fRemoveDeadVariables &= settings.fOptimize;
John Stiles7247b482021-03-08 10:40:35 -0500431
John Stilesaddccaf2021-08-02 19:03:30 -0400432 // Runtime effects always allow narrowing conversions.
433 if (ProgramConfig::IsRuntimeEffect(kind)) {
434 settings.fAllowNarrowingConversions = true;
435 }
436
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400437 this->resetErrors();
John Stiles10d39d92021-05-04 16:13:14 -0400438 fInliner.reset();
Brian Osman88cda172020-10-09 12:05:16 -0400439
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400440#if SKSL_DSL_PARSER
441 settings.fDSLMangling = false;
Ethan Nicholas051aeb72021-09-24 16:39:19 -0400442 return DSLParser(this, settings, kind, std::move(text)).program();
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400443#else
John Stiles10d39d92021-05-04 16:13:14 -0400444 auto textPtr = std::make_unique<String>(std::move(text));
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400445 AutoSource as(this, textPtr->c_str());
Brian Osman88cda172020-10-09 12:05:16 -0400446
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400447 dsl::Start(this, kind, settings);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400448 dsl::SetErrorReporter(&fErrorReporter);
John Stilesd1204642021-02-17 16:30:02 -0500449 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/false,
Ethan Nicholas6823b502021-06-15 11:42:07 -0400450 *textPtr);
Ethan Nicholas4f3e6a22021-06-15 09:17:05 -0400451 // Ideally, we would just use dsl::ReleaseProgram and not have to do any manual mucking about
452 // with the memory pool, but we've got some impedance mismatches to solve first
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400453 Pool* memoryPool = dsl::DSLWriter::MemoryPool().get();
John Stiles270cec22021-02-17 12:59:36 -0500454 auto program = std::make_unique<Program>(std::move(textPtr),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400455 std::move(dsl::DSLWriter::GetProgramConfig()),
John Stiles5c7bb322020-10-22 11:09:15 -0400456 fContext,
457 std::move(ir.fElements),
Brian Osman133724c2020-10-28 14:14:39 -0400458 std::move(ir.fSharedElements),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400459 std::move(dsl::DSLWriter::GetModifiersPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400460 std::move(ir.fSymbolTable),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400461 std::move(dsl::DSLWriter::MemoryPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400462 ir.fInputs);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400463 this->errorReporter().reportPendingErrors(PositionInfo());
John Stiles5c7bb322020-10-22 11:09:15 -0400464 bool success = false;
John Stiles2ecc5952021-09-01 14:41:36 -0400465 if (!this->finalize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400466 // Do not return programs that failed to compile.
John Stiles7247b482021-03-08 10:40:35 -0500467 } else if (!this->optimize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400468 // Do not return programs that failed to optimize.
469 } else {
470 // We have a successful program!
471 success = true;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500472 }
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400473 dsl::End();
474 if (memoryPool) {
475 memoryPool->detachFromThread();
Brian Osman28f702c2021-02-02 11:52:07 -0500476 }
John Stiles5c7bb322020-10-22 11:09:15 -0400477 return success ? std::move(program) : nullptr;
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400478#endif // SKSL_DSL_PARSER
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500479}
480
Brian Osman0006ad02020-11-18 15:38:39 -0500481bool Compiler::optimize(LoadedModule& module) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400482 SkASSERT(!this->errorCount());
Brian Osman0006ad02020-11-18 15:38:39 -0500483
John Stiles270cec22021-02-17 12:59:36 -0500484 // Create a temporary program configuration with default settings.
485 ProgramConfig config;
486 config.fKind = module.fKind;
John Stilesa935c3f2021-02-25 10:35:49 -0500487 AutoProgramConfig autoConfig(fContext, &config);
John Stiles270cec22021-02-17 12:59:36 -0500488
John Stilesd1204642021-02-17 16:30:02 -0500489 // Reset the Inliner.
John Stiles10d39d92021-05-04 16:13:14 -0400490 fInliner.reset();
John Stiles270cec22021-02-17 12:59:36 -0500491
492 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
Brian Osman0006ad02020-11-18 15:38:39 -0500493
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400494 while (this->errorCount() == 0) {
Brian Osman0006ad02020-11-18 15:38:39 -0500495 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles3ff77f42021-09-06 22:17:58 -0400496 if (!this->runInliner(module.fElements, module.fSymbols, usage.get())) {
Brian Osman0006ad02020-11-18 15:38:39 -0500497 break;
498 }
499 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400500 return this->errorCount() == 0;
Brian Osman0006ad02020-11-18 15:38:39 -0500501}
502
John Stiles0bfeae62021-03-11 09:09:42 -0500503bool Compiler::removeDeadFunctions(Program& program, ProgramUsage* usage) {
504 bool madeChanges = false;
505
506 if (program.fConfig->fSettings.fRemoveDeadFunctions) {
507 auto isDeadFunction = [&](const ProgramElement* element) {
508 if (!element->is<FunctionDefinition>()) {
509 return false;
510 }
511 const FunctionDefinition& fn = element->as<FunctionDefinition>();
John Stilese8da4d22021-03-24 09:19:45 -0400512 if (fn.declaration().isMain() || usage->get(fn.declaration()) > 0) {
John Stiles0bfeae62021-03-11 09:09:42 -0500513 return false;
514 }
515 usage->remove(*element);
516 madeChanges = true;
517 return true;
518 };
519
520 program.fElements.erase(std::remove_if(program.fElements.begin(),
521 program.fElements.end(),
522 [&](const std::unique_ptr<ProgramElement>& element) {
523 return isDeadFunction(element.get());
524 }),
525 program.fElements.end());
526 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
527 program.fSharedElements.end(),
528 isDeadFunction),
529 program.fSharedElements.end());
530 }
531 return madeChanges;
532}
533
534bool Compiler::removeDeadGlobalVariables(Program& program, ProgramUsage* usage) {
535 bool madeChanges = false;
536
537 if (program.fConfig->fSettings.fRemoveDeadVariables) {
538 auto isDeadVariable = [&](const ProgramElement* element) {
539 if (!element->is<GlobalVarDeclaration>()) {
540 return false;
541 }
542 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
543 const VarDeclaration& varDecl = global.declaration()->as<VarDeclaration>();
544 if (!usage->isDead(varDecl.var())) {
545 return false;
546 }
547 madeChanges = true;
548 return true;
549 };
550
551 program.fElements.erase(std::remove_if(program.fElements.begin(),
552 program.fElements.end(),
553 [&](const std::unique_ptr<ProgramElement>& element) {
554 return isDeadVariable(element.get());
555 }),
556 program.fElements.end());
557 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
558 program.fSharedElements.end(),
559 isDeadVariable),
560 program.fSharedElements.end());
561 }
562 return madeChanges;
563}
564
John Stiles26541872021-03-16 12:19:54 -0400565bool Compiler::removeDeadLocalVariables(Program& program, ProgramUsage* usage) {
566 class DeadLocalVariableEliminator : public ProgramWriter {
567 public:
568 DeadLocalVariableEliminator(const Context& context, ProgramUsage* usage)
569 : fContext(context)
570 , fUsage(usage) {}
571
572 using ProgramWriter::visitProgramElement;
573
574 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
575 // We don't need to look inside expressions at all.
576 return false;
577 }
578
579 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
580 if (stmt->is<VarDeclaration>()) {
581 VarDeclaration& varDecl = stmt->as<VarDeclaration>();
582 const Variable* var = &varDecl.var();
583 ProgramUsage::VariableCounts* counts = fUsage->fVariableCounts.find(var);
584 SkASSERT(counts);
585 SkASSERT(counts->fDeclared);
586 if (CanEliminate(var, *counts)) {
587 if (var->initialValue()) {
588 // The variable has an initial-value expression, which might have side
589 // effects. ExpressionStatement::Make will preserve side effects, but
590 // replaces pure expressions with Nop.
591 fUsage->remove(stmt.get());
592 stmt = ExpressionStatement::Make(fContext, std::move(varDecl.value()));
593 fUsage->add(stmt.get());
594 } else {
595 // The variable has no initial-value and can be cleanly eliminated.
596 fUsage->remove(stmt.get());
597 stmt = std::make_unique<Nop>();
598 }
599 fMadeChanges = true;
600 }
601 return false;
602 }
603 return INHERITED::visitStatementPtr(stmt);
604 }
605
606 static bool CanEliminate(const Variable* var, const ProgramUsage::VariableCounts& counts) {
607 if (!counts.fDeclared || counts.fRead || var->storage() != VariableStorage::kLocal) {
608 return false;
609 }
610 if (var->initialValue()) {
611 SkASSERT(counts.fWrite >= 1);
612 return counts.fWrite == 1;
613 } else {
614 return counts.fWrite == 0;
615 }
616 }
617
618 bool fMadeChanges = false;
619 const Context& fContext;
620 ProgramUsage* fUsage;
621
622 using INHERITED = ProgramWriter;
623 };
624
625 DeadLocalVariableEliminator visitor{*fContext, usage};
626
627 if (program.fConfig->fSettings.fRemoveDeadVariables) {
628 for (auto& [var, counts] : usage->fVariableCounts) {
629 if (DeadLocalVariableEliminator::CanEliminate(var, counts)) {
630 // This program contains at least one dead local variable.
631 // Scan the program for any dead local variables and eliminate them all.
632 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
633 if (pe->is<FunctionDefinition>()) {
634 visitor.visitProgramElement(*pe);
635 }
636 }
637 break;
638 }
639 }
640 }
641
642 return visitor.fMadeChanges;
643}
644
John Stiles25be58e2021-05-20 14:38:40 -0400645void Compiler::removeUnreachableCode(Program& program, ProgramUsage* usage) {
John Stiles25be58e2021-05-20 14:38:40 -0400646 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
647 if (pe->is<FunctionDefinition>()) {
John Stiles49b1a422021-09-22 09:35:39 -0400648 Analysis::EliminateUnreachableCode(pe->as<FunctionDefinition>().body(), usage);
John Stiles25be58e2021-05-20 14:38:40 -0400649 }
650 }
651}
652
Ethan Nicholas00543112018-07-31 09:44:36 -0400653bool Compiler::optimize(Program& program) {
John Stiles7247b482021-03-08 10:40:35 -0500654 // The optimizer only needs to run when it is enabled.
655 if (!program.fConfig->fSettings.fOptimize) {
656 return true;
657 }
658
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400659 SkASSERT(!this->errorCount());
Brian Osman010ce6a2020-10-19 16:34:10 -0400660 ProgramUsage* usage = program.fUsage.get();
John Stiles7954d6c2020-09-01 10:53:02 -0400661
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400662 if (this->errorCount() == 0) {
John Stiles87fc6572021-04-01 14:56:34 +0000663 // Run the inliner only once; it is expensive! Multiple passes can occasionally shake out
664 // more wins, but it's diminishing returns.
John Stiles3ff77f42021-09-06 22:17:58 -0400665 this->runInliner(program.ownedElements(), program.fSymbols, usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400666
John Stiles80970762021-09-18 12:42:10 -0400667 // Unreachable code can confuse some drivers, so it's worth removing. (skia:12012)
668 this->removeUnreachableCode(program, usage);
669
John Stilesb6664582021-03-19 09:46:00 -0400670 while (this->removeDeadFunctions(program, usage)) {
671 // Removing dead functions may cause more functions to become unreferenced. Try again.
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400672 }
John Stilesb6664582021-03-19 09:46:00 -0400673 while (this->removeDeadLocalVariables(program, usage)) {
674 // Removing dead variables may cause more variables to become unreferenced. Try again.
675 }
John Stiles25be58e2021-05-20 14:38:40 -0400676
Brian Osman8c264792021-07-01 16:41:27 -0400677 this->removeDeadGlobalVariables(program, usage);
Ethan Nicholas00543112018-07-31 09:44:36 -0400678 }
John Stilesbb1505f2021-02-12 09:17:53 -0500679
John Stiles2ecc5952021-09-01 14:41:36 -0400680 return this->errorCount() == 0;
681}
682
John Stiles3ff77f42021-09-06 22:17:58 -0400683bool Compiler::runInliner(const std::vector<std::unique_ptr<ProgramElement>>& elements,
684 std::shared_ptr<SymbolTable> symbols,
685 ProgramUsage* usage) {
686 // The program's SymbolTable was taken out of the IRGenerator when the program was bundled, but
687 // the inliner relies (indirectly) on having a valid SymbolTable in the IRGenerator.
688 // In particular, inlining can turn a non-optimizable expression like `normalize(myVec)` into
689 // `normalize(vec2(7))`, which is now optimizable. The optimizer can use DSL to simplify this
690 // expression--e.g., in the case of normalize, using DSL's Length(). The DSL relies on
691 // irGenerator.convertIdentifier() to look up `length`. convertIdentifier() needs a valid symbol
692 // table to find the declaration of `length`. To allow this chain of events to succeed, we
693 // re-insert the program's symbol table back into the IRGenerator temporarily.
694 SkASSERT(!fIRGenerator->fSymbolTable);
695 fIRGenerator->fSymbolTable = symbols;
696
697 bool result = fInliner.analyze(elements, symbols, usage);
698
699 fIRGenerator->fSymbolTable = nullptr;
700 return result;
701}
702
John Stiles2ecc5952021-09-01 14:41:36 -0400703bool Compiler::finalize(Program& program) {
704 // Do a pass looking for @if/@switch statements that didn't optimize away, or dangling
705 // FunctionReference or TypeReference expressions. Report these as errors.
706 Analysis::VerifyStaticTestsAndExpressions(program);
707
John Stiles9d82e612021-09-03 08:39:54 -0400708 // Verify that the program conforms to ES2 limitations.
John Stiles2ecc5952021-09-01 14:41:36 -0400709 if (fContext->fConfig->strictES2Mode() && this->errorCount() == 0) {
John Stiles9d82e612021-09-03 08:39:54 -0400710 // Enforce Appendix A, Section 5 of the GLSL ES 1.00 spec -- Indexing. This logic assumes
711 // that all loops meet the criteria of Section 4, and if they don't, could crash.
John Stiles2ecc5952021-09-01 14:41:36 -0400712 for (const auto& pe : program.ownedElements()) {
713 Analysis::ValidateIndexingForES2(*pe, this->errorReporter());
714 }
John Stiles9d82e612021-09-03 08:39:54 -0400715 // Verify that the program size is reasonable after unrolling and inlining. This also
716 // issues errors for static recursion and overly-deep function-call chains.
John Stiles61e5e202021-09-02 09:56:31 -0400717 Analysis::CheckProgramUnrolledSize(program);
John Stilesbb1505f2021-02-12 09:17:53 -0500718 }
719
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400720 return this->errorCount() == 0;
Ethan Nicholas00543112018-07-31 09:44:36 -0400721}
722
Brian Osmanfb32ddf2019-06-18 10:14:20 -0400723#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
724
Ethan Nicholas00543112018-07-31 09:44:36 -0400725bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400726 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toSPIRV");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400727 AutoSource as(this, program.fSource->c_str());
Brian Salomond8d85b92021-07-07 09:41:17 -0400728 ProgramSettings settings;
729 settings.fDSLUseMemoryPool = false;
730 dsl::Start(this, program.fConfig->fKind, settings);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400731 dsl::SetErrorReporter(&fErrorReporter);
Brian Salomond8d85b92021-07-07 09:41:17 -0400732 dsl::DSLWriter::IRGenerator().fSymbolTable = program.fSymbols;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400733#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400734 StringStream buffer;
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400735 SPIRVCodeGenerator cg(fContext.get(), &program, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400736 bool result = cg.generateCode();
John Stiles270cec22021-02-17 12:59:36 -0500737 if (result && program.fConfig->fSettings.fValidateSPIRV) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400738 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400739 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400740 SkASSERT(0 == data.size() % 4);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500741 String errors;
742 auto dumpmsg = [&errors](spv_message_level_t, const char*, const spv_position_t&,
743 const char* m) {
744 errors.appendf("SPIR-V validation error: %s\n", m);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400745 };
746 tools.SetMessageConsumer(dumpmsg);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500747
748 // Verify that the SPIR-V we produced is valid. At runtime, we will abort() with a message
749 // explaining the error. In standalone mode (skslc), we will send the message, plus the
750 // entire disassembled SPIR-V (for easier context & debugging) as *our* error message.
751 result = tools.Validate((const uint32_t*) data.c_str(), data.size() / 4);
752
753 if (!result) {
754#if defined(SKSL_STANDALONE)
755 // Convert the string-stream to a SPIR-V disassembly.
756 std::string disassembly;
757 if (tools.Disassemble((const uint32_t*)data.data(), data.size() / 4, &disassembly)) {
758 errors.append(disassembly);
759 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400760 this->errorReporter().error(-1, errors);
Ethan Nicholasc973d262021-09-17 16:10:29 -0400761 this->errorReporter().reportPendingErrors(PositionInfo());
Brian Osman8d09d4a2020-11-24 15:51:06 -0500762#else
763 SkDEBUGFAILF("%s", errors.c_str());
764#endif
765 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400766 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400767 }
768#else
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400769 SPIRVCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500770 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400771#endif
Brian Salomond8d85b92021-07-07 09:41:17 -0400772 dsl::End();
Ethan Nicholasce33f102016-12-09 17:22:59 -0500773 return result;
774}
775
Ethan Nicholas00543112018-07-31 09:44:36 -0400776bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400777 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500778 bool result = this->toSPIRV(program, buffer);
779 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400780 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500781 }
782 return result;
783}
784
Ethan Nicholas00543112018-07-31 09:44:36 -0400785bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400786 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toGLSL");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400787 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400788 GLSLCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500789 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500790 return result;
791}
792
Ethan Nicholas00543112018-07-31 09:44:36 -0400793bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400794 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500795 bool result = this->toGLSL(program, buffer);
796 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400797 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500798 }
799 return result;
800}
801
Brian Osmanc0243912020-02-19 15:35:26 -0500802bool Compiler::toHLSL(Program& program, String* out) {
803 String spirv;
804 if (!this->toSPIRV(program, &spirv)) {
805 return false;
806 }
807
808 return SPIRVtoHLSL(spirv, out);
809}
810
Ethan Nicholas00543112018-07-31 09:44:36 -0400811bool Compiler::toMetal(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400812 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toMetal");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400813 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400814 MetalCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -0400815 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -0400816 return result;
817}
818
Ethan Nicholas00543112018-07-31 09:44:36 -0400819bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -0400820 StringStream buffer;
821 bool result = this->toMetal(program, buffer);
822 if (result) {
823 *out = buffer.str();
824 }
825 return result;
826}
827
Ethan Nicholas2a479a52020-08-18 16:29:45 -0400828#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -0400829
Ethan Nicholas32724122021-09-07 13:49:07 -0400830void Compiler::handleError(skstd::string_view msg, PositionInfo pos) {
Ethan Nicholasa40ddcd2021-08-06 09:17:18 -0400831 fErrorText += "error: " + (pos.line() >= 1 ? to_string(pos.line()) + ": " : "") + msg + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -0700832}
833
Ethan Nicholas95046142021-01-07 10:57:27 -0500834String Compiler::errorText(bool showCount) {
835 if (showCount) {
836 this->writeErrorCount();
837 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400838 String result = fErrorText;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400839 this->resetErrors();
ethannicholasb3058bd2016-07-01 08:22:01 -0700840 return result;
841}
842
843void Compiler::writeErrorCount() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400844 int count = this->errorCount();
845 if (count) {
846 fErrorText += to_string(count) + " error";
847 if (count > 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700848 fErrorText += "s";
849 }
850 fErrorText += "\n";
851 }
852}
853
John Stilesa6841be2020-08-06 14:11:56 -0400854} // namespace SkSL