blob: 1ea5ac17bfbf27344d7925e022460c42150da920 [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"
John Stiles270cec22021-02-17 12:59:36 -050014#include "src/core/SkScopeExit.h"
Leon Scrogginsb66214e2021-02-11 17:14:18 -050015#include "src/core/SkTraceEvent.h"
John Stilesb92641c2020-08-31 18:09:01 -040016#include "src/sksl/SkSLAnalysis.h"
John Stilesf3a28db2021-03-10 23:00:47 -050017#include "src/sksl/SkSLConstantFolder.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/SkSLCPPCodeGenerator.h"
John Stiles82ab3402021-04-13 17:13:03 -040023#include "src/sksl/codegen/SkSLDSLCPPCodeGenerator.h"
John Stiles3738ef52021-04-13 10:41:57 -040024#include "src/sksl/codegen/SkSLGLSLCodeGenerator.h"
25#include "src/sksl/codegen/SkSLHCodeGenerator.h"
26#include "src/sksl/codegen/SkSLMetalCodeGenerator.h"
27#include "src/sksl/codegen/SkSLSPIRVCodeGenerator.h"
28#include "src/sksl/codegen/SkSLSPIRVtoHLSL.h"
Ethan Nicholas55a63af2021-05-18 10:12:58 -040029#include "src/sksl/dsl/priv/DSLWriter.h"
30#include "src/sksl/dsl/priv/DSL_priv.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050031#include "src/sksl/ir/SkSLEnum.h"
32#include "src/sksl/ir/SkSLExpression.h"
33#include "src/sksl/ir/SkSLExpressionStatement.h"
34#include "src/sksl/ir/SkSLFunctionCall.h"
35#include "src/sksl/ir/SkSLIntLiteral.h"
36#include "src/sksl/ir/SkSLModifiersDeclaration.h"
37#include "src/sksl/ir/SkSLNop.h"
38#include "src/sksl/ir/SkSLSymbolTable.h"
39#include "src/sksl/ir/SkSLTernaryExpression.h"
40#include "src/sksl/ir/SkSLUnresolvedFunction.h"
41#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stilese6150002020-10-05 12:03:53 -040042#include "src/utils/SkBitSet.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070043
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040044#include <fstream>
45
Ethan Nicholasa11035b2019-11-26 16:27:47 -050046#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
47#include "include/gpu/GrContextOptions.h"
48#include "src/gpu/GrShaderCaps.h"
49#endif
50
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040051#ifdef SK_ENABLE_SPIRV_VALIDATION
52#include "spirv-tools/libspirv.hpp"
53#endif
54
Brian Osman3d87e9f2020-10-08 11:50:22 -040055#if defined(SKSL_STANDALONE)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040056
Brian Osman3d87e9f2020-10-08 11:50:22 -040057// In standalone mode, we load the textual sksl source files. GN generates or copies these files
58// to the skslc executable directory. The "data" in this mode is just the filename.
59#define MODULE_DATA(name) MakeModulePath("sksl_" #name ".sksl")
60
61#else
62
63// At runtime, we load the dehydrated sksl data files. The data is a (pointer, size) pair.
Ethan Nicholasc18bb512020-07-28 14:46:53 -040064#include "src/sksl/generated/sksl_fp.dehydrated.sksl"
65#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
66#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
67#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
Brian Osmanb06301e2020-11-06 11:45:36 -050068#include "src/sksl/generated/sksl_public.dehydrated.sksl"
Brian Osmancbb60bd2021-04-12 09:49:20 -040069#include "src/sksl/generated/sksl_rt_colorfilter.dehydrated.sksl"
70#include "src/sksl/generated/sksl_rt_shader.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040071#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
72
Brian Osman3d87e9f2020-10-08 11:50:22 -040073#define MODULE_DATA(name) MakeModuleData(SKSL_INCLUDE_sksl_##name,\
74 SKSL_INCLUDE_sksl_##name##_LENGTH)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040075
76#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040077
ethannicholasb3058bd2016-07-01 08:22:01 -070078namespace SkSL {
79
John Stiles7247b482021-03-08 10:40:35 -050080// These flags allow tools like Viewer or Nanobench to override the compiler's ProgramSettings.
John Stiles2ee4d7a2021-03-30 10:30:47 -040081Compiler::OverrideFlag Compiler::sOptimizer = OverrideFlag::kDefault;
82Compiler::OverrideFlag Compiler::sInliner = OverrideFlag::kDefault;
John Stiles8ef4d6c2021-03-05 16:01:45 -050083
John Stiles47c0a742021-02-09 09:30:35 -050084using RefKind = VariableReference::RefKind;
85
Brian Osman88cda172020-10-09 12:05:16 -040086class AutoSource {
87public:
88 AutoSource(Compiler* compiler, const String* source)
John Stilesa289ac22021-05-06 07:35:35 -040089 : fCompiler(compiler) {
90 SkASSERT(!fCompiler->fSource);
Brian Osman88cda172020-10-09 12:05:16 -040091 fCompiler->fSource = source;
92 }
93
John Stilesa289ac22021-05-06 07:35:35 -040094 ~AutoSource() {
95 fCompiler->fSource = nullptr;
96 }
Brian Osman88cda172020-10-09 12:05:16 -040097
98 Compiler* fCompiler;
Brian Osman88cda172020-10-09 12:05:16 -040099};
100
John Stilesa935c3f2021-02-25 10:35:49 -0500101class AutoProgramConfig {
102public:
103 AutoProgramConfig(std::shared_ptr<Context>& context, ProgramConfig* config)
104 : fContext(context.get()) {
105 SkASSERT(!fContext->fConfig);
106 fContext->fConfig = config;
107 }
108
109 ~AutoProgramConfig() {
110 fContext->fConfig = nullptr;
111 }
112
113 Context* fContext;
114};
115
John Stiles10d39d92021-05-04 16:13:14 -0400116class AutoModifiersPool {
117public:
118 AutoModifiersPool(std::shared_ptr<Context>& context, ModifiersPool* modifiersPool)
119 : fContext(context.get()) {
120 SkASSERT(!fContext->fModifiersPool);
121 fContext->fModifiersPool = modifiersPool;
122 }
123
124 ~AutoModifiersPool() {
125 fContext->fModifiersPool = nullptr;
126 }
127
128 Context* fContext;
129};
130
John Stilesd6a5f4492021-02-11 15:46:11 -0500131Compiler::Compiler(const ShaderCapsClass* caps)
John Stilesc1a98b82021-02-24 13:35:02 -0500132 : fContext(std::make_shared<Context>(/*errors=*/*this, *caps))
John Stilesa47b3512021-05-04 16:15:00 -0400133 , fInliner(fContext.get()) {
John Stilesc1a98b82021-02-24 13:35:02 -0500134 SkASSERT(caps);
John Stiles7c3515b2020-10-16 18:38:39 -0400135 fRootSymbolTable = std::make_shared<SymbolTable>(this, /*builtin=*/true);
Brian Osmanb06301e2020-11-06 11:45:36 -0500136 fPrivateSymbolTable = std::make_shared<SymbolTable>(fRootSymbolTable, /*builtin=*/true);
John Stilesc1a98b82021-02-24 13:35:02 -0500137 fIRGenerator = std::make_unique<IRGenerator>(fContext.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700138
John Stiles54e7c052021-01-11 14:22:36 -0500139#define TYPE(t) fContext->fTypes.f ## t .get()
ethannicholasb3058bd2016-07-01 08:22:01 -0700140
Brian Osmanb06301e2020-11-06 11:45:36 -0500141 const SkSL::Symbol* rootTypes[] = {
142 TYPE(Void),
Brian Salomonbf7b6202016-11-11 16:08:03 -0500143
Brian Osmanb06301e2020-11-06 11:45:36 -0500144 TYPE( Float), TYPE( Float2), TYPE( Float3), TYPE( Float4),
145 TYPE( Half), TYPE( Half2), TYPE( Half3), TYPE( Half4),
146 TYPE( Int), TYPE( Int2), TYPE( Int3), TYPE( Int4),
Brian Osmanb06301e2020-11-06 11:45:36 -0500147 TYPE( Bool), TYPE( Bool2), TYPE( Bool3), TYPE( Bool4),
Brian Salomon2a51de82016-11-16 12:06:01 -0500148
Brian Osmanc0f2b642020-12-22 13:35:55 -0500149 TYPE(Float2x2), TYPE(Float3x3), TYPE(Float4x4),
Brian Osmanc63f4312020-12-23 11:44:14 -0500150 TYPE( Half2x2), TYPE( Half3x3), TYPE(Half4x4),
Greg Daniel64773e62016-11-22 09:44:03 -0500151
Brian Osmanc63f4312020-12-23 11:44:14 -0500152 TYPE(SquareMat), TYPE(SquareHMat),
ethannicholasb3058bd2016-07-01 08:22:01 -0700153
Brian Osman20fad322020-12-23 12:42:33 -0500154 TYPE(GenType), TYPE(GenHType), TYPE(GenIType), TYPE(GenBType),
155 TYPE(Vec), TYPE(HVec), TYPE(IVec), TYPE(BVec),
Brian Osmanb06301e2020-11-06 11:45:36 -0500156
Brian Osman14d00962021-04-02 17:04:35 -0400157 TYPE(ColorFilter),
158 TYPE(Shader),
Brian Osmanb06301e2020-11-06 11:45:36 -0500159 };
160
161 const SkSL::Symbol* privateTypes[] = {
Brian Osman20fad322020-12-23 12:42:33 -0500162 TYPE( UInt), TYPE( UInt2), TYPE( UInt3), TYPE( UInt4),
163 TYPE( Short), TYPE( Short2), TYPE( Short3), TYPE( Short4),
164 TYPE(UShort), TYPE(UShort2), TYPE(UShort3), TYPE(UShort4),
Brian Osman20fad322020-12-23 12:42:33 -0500165
166 TYPE(GenUType), TYPE(UVec),
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400167 TYPE(SVec), TYPE(USVec),
Brian Osman20fad322020-12-23 12:42:33 -0500168
Brian Osmanc0f2b642020-12-22 13:35:55 -0500169 TYPE(Float2x3), TYPE(Float2x4),
170 TYPE(Float3x2), TYPE(Float3x4),
171 TYPE(Float4x2), TYPE(Float4x3),
172
Brian Osmanc63f4312020-12-23 11:44:14 -0500173 TYPE(Half2x3), TYPE(Half2x4),
174 TYPE(Half3x2), TYPE(Half3x4),
175 TYPE(Half4x2), TYPE(Half4x3),
176
Brian Osmanc0f2b642020-12-22 13:35:55 -0500177 TYPE(Mat), TYPE(HMat),
178
Brian Osmanb06301e2020-11-06 11:45:36 -0500179 TYPE(Sampler1D), TYPE(Sampler2D), TYPE(Sampler3D),
180 TYPE(SamplerExternalOES),
Brian Osmanb06301e2020-11-06 11:45:36 -0500181 TYPE(Sampler2DRect),
Brian Osmanb06301e2020-11-06 11:45:36 -0500182
183 TYPE(ISampler2D),
Brian Osmanb06301e2020-11-06 11:45:36 -0500184 TYPE(SubpassInput), TYPE(SubpassInputMS),
185
Brian Osmanb06301e2020-11-06 11:45:36 -0500186 TYPE(Sampler),
187 TYPE(Texture2D),
Brian Osman14d00962021-04-02 17:04:35 -0400188
189 TYPE(FragmentProcessor),
Brian Osmanb06301e2020-11-06 11:45:36 -0500190 };
191
192 for (const SkSL::Symbol* type : rootTypes) {
193 fRootSymbolTable->addWithoutOwnership(type);
194 }
195 for (const SkSL::Symbol* type : privateTypes) {
196 fPrivateSymbolTable->addWithoutOwnership(type);
197 }
198
199#undef TYPE
ethannicholasb3058bd2016-07-01 08:22:01 -0700200
Brian Osman3887a012020-09-30 13:22:27 -0400201 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
202 // treat it as builtin (ie, no need to clone it into the Program).
John Stiles10d39d92021-05-04 16:13:14 -0400203 fPrivateSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
John Stilesa47b3512021-05-04 16:15:00 -0400204 fCoreModifiers.add(Modifiers{}),
John Stiles10d39d92021-05-04 16:13:14 -0400205 "sk_Caps",
206 fContext->fTypes.fSkCaps.get(),
207 /*builtin=*/false,
208 Variable::Storage::kGlobal));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500209
Brian Osman3d87e9f2020-10-08 11:50:22 -0400210 fRootModule = {fRootSymbolTable, /*fIntrinsics=*/nullptr};
Brian Osmanb06301e2020-11-06 11:45:36 -0500211 fPrivateModule = {fPrivateSymbolTable, /*fIntrinsics=*/nullptr};
ethannicholasb3058bd2016-07-01 08:22:01 -0700212}
213
John Stilesdd13dba2020-10-29 10:45:34 -0400214Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700215
Brian Osman56269982020-11-20 12:38:07 -0500216const ParsedModule& Compiler::loadGPUModule() {
217 if (!fGPUModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500218 fGPUModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(gpu), fPrivateModule);
Brian Osman56269982020-11-20 12:38:07 -0500219 }
220 return fGPUModule;
221}
222
223const ParsedModule& Compiler::loadFragmentModule() {
224 if (!fFragmentModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500225 fFragmentModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(frag),
Brian Osman56269982020-11-20 12:38:07 -0500226 this->loadGPUModule());
227 }
228 return fFragmentModule;
229}
230
231const ParsedModule& Compiler::loadVertexModule() {
232 if (!fVertexModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500233 fVertexModule = this->parseModule(ProgramKind::kVertex, MODULE_DATA(vert),
Brian Osman56269982020-11-20 12:38:07 -0500234 this->loadGPUModule());
235 }
236 return fVertexModule;
237}
238
Brian Osman88cda172020-10-09 12:05:16 -0400239const ParsedModule& Compiler::loadGeometryModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400240 if (!fGeometryModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500241 fGeometryModule = this->parseModule(ProgramKind::kGeometry, MODULE_DATA(geom),
Brian Osman56269982020-11-20 12:38:07 -0500242 this->loadGPUModule());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400243 }
Brian Osman88cda172020-10-09 12:05:16 -0400244 return fGeometryModule;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400245}
246
Brian Osman88cda172020-10-09 12:05:16 -0400247const ParsedModule& Compiler::loadFPModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400248 if (!fFPModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500249 fFPModule = this->parseModule(ProgramKind::kFragmentProcessor, MODULE_DATA(fp),
Brian Osman56269982020-11-20 12:38:07 -0500250 this->loadGPUModule());
Brian Osman8e2ef022020-09-30 13:26:43 -0400251 }
Brian Osman88cda172020-10-09 12:05:16 -0400252 return fFPModule;
Brian Osman8e2ef022020-09-30 13:26:43 -0400253}
254
Brian Osmanb06301e2020-11-06 11:45:36 -0500255const ParsedModule& Compiler::loadPublicModule() {
256 if (!fPublicModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500257 fPublicModule = this->parseModule(ProgramKind::kGeneric, MODULE_DATA(public), fRootModule);
Brian Osmanb06301e2020-11-06 11:45:36 -0500258 }
259 return fPublicModule;
260}
261
Brian Osmancbb60bd2021-04-12 09:49:20 -0400262static void add_glsl_type_aliases(SkSL::SymbolTable* symbols, const SkSL::BuiltinTypes& types) {
263 // Add some aliases to the runtime effect modules so that it's friendlier, and more like GLSL
264 symbols->addAlias("vec2", types.fFloat2.get());
265 symbols->addAlias("vec3", types.fFloat3.get());
266 symbols->addAlias("vec4", types.fFloat4.get());
267
268 symbols->addAlias("ivec2", types.fInt2.get());
269 symbols->addAlias("ivec3", types.fInt3.get());
270 symbols->addAlias("ivec4", types.fInt4.get());
271
272 symbols->addAlias("bvec2", types.fBool2.get());
273 symbols->addAlias("bvec3", types.fBool3.get());
274 symbols->addAlias("bvec4", types.fBool4.get());
275
276 symbols->addAlias("mat2", types.fFloat2x2.get());
277 symbols->addAlias("mat3", types.fFloat3x3.get());
278 symbols->addAlias("mat4", types.fFloat4x4.get());
279}
280
Brian Osmancbb60bd2021-04-12 09:49:20 -0400281const ParsedModule& Compiler::loadRuntimeColorFilterModule() {
282 if (!fRuntimeColorFilterModule.fSymbols) {
283 fRuntimeColorFilterModule = this->parseModule(ProgramKind::kRuntimeColorFilter,
284 MODULE_DATA(rt_colorfilter),
285 this->loadPublicModule());
286 add_glsl_type_aliases(fRuntimeColorFilterModule.fSymbols.get(), fContext->fTypes);
287 }
288 return fRuntimeColorFilterModule;
289}
290
291const ParsedModule& Compiler::loadRuntimeShaderModule() {
292 if (!fRuntimeShaderModule.fSymbols) {
293 fRuntimeShaderModule = this->parseModule(
294 ProgramKind::kRuntimeShader, MODULE_DATA(rt_shader), this->loadPublicModule());
295 add_glsl_type_aliases(fRuntimeShaderModule.fSymbols.get(), fContext->fTypes);
296 }
297 return fRuntimeShaderModule;
298}
299
John Stilesdbd4e6f2021-02-16 13:29:15 -0500300const ParsedModule& Compiler::moduleForProgramKind(ProgramKind kind) {
Brian Osman88cda172020-10-09 12:05:16 -0400301 switch (kind) {
Brian Osmancbb60bd2021-04-12 09:49:20 -0400302 case ProgramKind::kVertex: return this->loadVertexModule(); break;
303 case ProgramKind::kFragment: return this->loadFragmentModule(); break;
304 case ProgramKind::kGeometry: return this->loadGeometryModule(); break;
305 case ProgramKind::kFragmentProcessor: return this->loadFPModule(); break;
Brian Osmancbb60bd2021-04-12 09:49:20 -0400306 case ProgramKind::kRuntimeColorFilter: return this->loadRuntimeColorFilterModule(); break;
307 case ProgramKind::kRuntimeShader: return this->loadRuntimeShaderModule(); break;
308 case ProgramKind::kGeneric: return this->loadPublicModule(); break;
Brian Osman88cda172020-10-09 12:05:16 -0400309 }
310 SkUNREACHABLE;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400311}
312
John Stilesdbd4e6f2021-02-16 13:29:15 -0500313LoadedModule Compiler::loadModule(ProgramKind kind,
Brian Osman3d87e9f2020-10-08 11:50:22 -0400314 ModuleData data,
John Stilesa935c3f2021-02-25 10:35:49 -0500315 std::shared_ptr<SymbolTable> base,
316 bool dehydrate) {
317 if (dehydrate) {
318 // NOTE: This is a workaround. When dehydrating includes, skslc doesn't know which module
319 // it's preparing, nor what the correct base module is. We can't use 'Root', because many
320 // GPU intrinsics reference private types, like samplers or textures. Today, 'Private' does
321 // contain the union of all known types, so this is safe. If we ever have types that only
322 // exist in 'Public' (for example), this logic needs to be smarter (by choosing the correct
323 // base for the module we're compiling).
Brian Osmanb06301e2020-11-06 11:45:36 -0500324 base = fPrivateSymbolTable;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400325 }
John Stilesa935c3f2021-02-25 10:35:49 -0500326 SkASSERT(base);
327
John Stilesa47b3512021-05-04 16:15:00 -0400328 // Put the core-module modifier pool into the context.
329 AutoModifiersPool autoPool(fContext, &fCoreModifiers);
John Stiles10d39d92021-05-04 16:13:14 -0400330
John Stilesa935c3f2021-02-25 10:35:49 -0500331 // Built-in modules always use default program settings.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400332 Program::Settings settings;
333 settings.fReplaceSettings = !dehydrate;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400334
335#if defined(SKSL_STANDALONE)
336 SkASSERT(data.fPath);
337 std::ifstream in(data.fPath);
John Stilesd51c9792021-03-18 11:40:14 -0400338 String text{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400339 if (in.rdstate()) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400340 printf("error reading %s\n", data.fPath);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400341 abort();
342 }
Brian Osmane498b3c2020-09-23 14:42:11 -0400343 const String* source = fRootSymbolTable->takeOwnershipOfString(std::move(text));
John Stilesd1204642021-02-17 16:30:02 -0500344
Brian Osman88cda172020-10-09 12:05:16 -0400345 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400346 std::vector<std::unique_ptr<ProgramElement>> elements;
347 std::vector<const ProgramElement*> sharedElements;
348 dsl::StartModule(this, kind, settings, baseModule);
349 AutoSource as(this, source);
John Stilesd1204642021-02-17 16:30:02 -0500350 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/true,
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400351 source->c_str(), source->length());
Brian Osman133724c2020-10-28 14:14:39 -0400352 SkASSERT(ir.fSharedElements.empty());
Brian Osman0006ad02020-11-18 15:38:39 -0500353 LoadedModule module = { kind, std::move(ir.fSymbolTable), std::move(ir.fElements) };
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400354 dsl::End();
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400355 if (this->fErrorCount) {
356 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400357 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400358 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400359#else
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400360 ProgramConfig config;
361 config.fKind = kind;
362 config.fSettings = settings;
363 AutoProgramConfig autoConfig(fContext, &config);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400364 SkASSERT(data.fData && (data.fSize != 0));
John Stiles10d39d92021-05-04 16:13:14 -0400365 Rehydrator rehydrator(fContext.get(), base, data.fData, data.fSize);
Brian Osman0006ad02020-11-18 15:38:39 -0500366 LoadedModule module = { kind, rehydrator.symbolTable(), rehydrator.elements() };
Brian Osman3d87e9f2020-10-08 11:50:22 -0400367#endif
368
369 return module;
370}
371
John Stilesdbd4e6f2021-02-16 13:29:15 -0500372ParsedModule Compiler::parseModule(ProgramKind kind, ModuleData data, const ParsedModule& base) {
John Stilesa935c3f2021-02-25 10:35:49 -0500373 LoadedModule module = this->loadModule(kind, data, base.fSymbols, /*dehydrate=*/false);
Brian Osman0006ad02020-11-18 15:38:39 -0500374 this->optimize(module);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400375
376 // For modules that just declare (but don't define) intrinsic functions, there will be no new
377 // program elements. In that case, we can share our parent's intrinsic map:
Brian Osman0006ad02020-11-18 15:38:39 -0500378 if (module.fElements.empty()) {
John Stiles10d39d92021-05-04 16:13:14 -0400379 return ParsedModule{module.fSymbols, base.fIntrinsics};
Brian Osman3d87e9f2020-10-08 11:50:22 -0400380 }
381
382 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
383
384 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
385 // global objects to the declaring ProgramElement.
Brian Osman0006ad02020-11-18 15:38:39 -0500386 for (std::unique_ptr<ProgramElement>& element : module.fElements) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400387 switch (element->kind()) {
388 case ProgramElement::Kind::kFunction: {
389 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400390 SkASSERT(f.declaration().isBuiltin());
391 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400392 break;
393 }
John Stiles569249b2020-11-03 12:18:22 -0500394 case ProgramElement::Kind::kFunctionPrototype: {
395 // These are already in the symbol table.
396 break;
397 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400398 case ProgramElement::Kind::kEnum: {
399 const Enum& e = element->as<Enum>();
400 SkASSERT(e.isBuiltin());
401 intrinsics->insertOrDie(e.typeName(), std::move(element));
402 break;
403 }
404 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400405 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
406 const Variable& var = global.declaration()->as<VarDeclaration>().var();
407 SkASSERT(var.isBuiltin());
408 intrinsics->insertOrDie(var.name(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400409 break;
410 }
411 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400412 const Variable& var = element->as<InterfaceBlock>().variable();
413 SkASSERT(var.isBuiltin());
414 intrinsics->insertOrDie(var.name(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400415 break;
416 }
417 default:
418 printf("Unsupported element: %s\n", element->description().c_str());
419 SkASSERT(false);
420 break;
421 }
422 }
423
John Stiles10d39d92021-05-04 16:13:14 -0400424 return ParsedModule{module.fSymbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400425}
426
Brian Osman32d53552020-09-23 13:55:20 -0400427std::unique_ptr<Program> Compiler::convertProgram(
John Stilesdbd4e6f2021-02-16 13:29:15 -0500428 ProgramKind kind,
Brian Osman32d53552020-09-23 13:55:20 -0400429 String text,
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400430 Program::Settings settings) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400431 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::convertProgram");
Leon Scrogginsb66214e2021-02-11 17:14:18 -0500432
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400433 SkASSERT(!settings.fExternalFunctions || (kind == ProgramKind::kGeneric));
Ethan Nicholas91164d12019-05-15 15:29:54 -0400434
Brian Osman0006ad02020-11-18 15:38:39 -0500435 // Loading and optimizing our base module might reset the inliner, so do that first,
436 // *then* configure the inliner with the settings for this program.
437 const ParsedModule& baseModule = this->moduleForProgramKind(kind);
438
John Stiles2ee4d7a2021-03-30 10:30:47 -0400439 // Honor our optimization-override flags.
440 switch (sOptimizer) {
441 case OverrideFlag::kDefault:
442 break;
443 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400444 settings.fOptimize = false;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400445 break;
446 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400447 settings.fOptimize = true;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400448 break;
449 }
450
451 switch (sInliner) {
452 case OverrideFlag::kDefault:
453 break;
454 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400455 settings.fInlineThreshold = 0;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400456 break;
457 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400458 if (settings.fInlineThreshold == 0) {
459 settings.fInlineThreshold = kDefaultInlineThreshold;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400460 }
461 break;
462 }
John Stiles7247b482021-03-08 10:40:35 -0500463
464 // Disable optimization settings that depend on a parent setting which has been disabled.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400465 settings.fInlineThreshold *= (int)settings.fOptimize;
466 settings.fRemoveDeadFunctions &= settings.fOptimize;
467 settings.fRemoveDeadVariables &= settings.fOptimize;
John Stiles7247b482021-03-08 10:40:35 -0500468
ethannicholasb3058bd2016-07-01 08:22:01 -0700469 fErrorText = "";
470 fErrorCount = 0;
John Stiles10d39d92021-05-04 16:13:14 -0400471 fInliner.reset();
Brian Osman88cda172020-10-09 12:05:16 -0400472
John Stiles10d39d92021-05-04 16:13:14 -0400473 auto textPtr = std::make_unique<String>(std::move(text));
John Stilesa289ac22021-05-06 07:35:35 -0400474 AutoSource as(this, textPtr.get());
Brian Osman88cda172020-10-09 12:05:16 -0400475
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400476 dsl::Start(this, kind, settings);
John Stilesd1204642021-02-17 16:30:02 -0500477 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/false,
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400478 textPtr->c_str(), textPtr->size());
479 // Ideally, we would just use DSLWriter::ReleaseProgram and not have to do any manual mucking
480 // about with the memory pool, but we've got some impedance mismatches to solve first
481 Pool* memoryPool = dsl::DSLWriter::MemoryPool().get();
John Stiles270cec22021-02-17 12:59:36 -0500482 auto program = std::make_unique<Program>(std::move(textPtr),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400483 std::move(dsl::DSLWriter::GetProgramConfig()),
John Stiles5c7bb322020-10-22 11:09:15 -0400484 fContext,
485 std::move(ir.fElements),
Brian Osman133724c2020-10-28 14:14:39 -0400486 std::move(ir.fSharedElements),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400487 std::move(dsl::DSLWriter::GetModifiersPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400488 std::move(ir.fSymbolTable),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400489 std::move(dsl::DSLWriter::MemoryPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400490 ir.fInputs);
491 bool success = false;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500492 if (fErrorCount) {
John Stiles5c7bb322020-10-22 11:09:15 -0400493 // Do not return programs that failed to compile.
John Stiles7247b482021-03-08 10:40:35 -0500494 } else if (!this->optimize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400495 // Do not return programs that failed to optimize.
496 } else {
497 // We have a successful program!
498 success = true;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500499 }
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400500 dsl::End();
501 if (memoryPool) {
502 memoryPool->detachFromThread();
Brian Osman28f702c2021-02-02 11:52:07 -0500503 }
John Stiles5c7bb322020-10-22 11:09:15 -0400504 return success ? std::move(program) : nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500505}
506
John Stilesbb1505f2021-02-12 09:17:53 -0500507void Compiler::verifyStaticTests(const Program& program) {
508 class StaticTestVerifier : public ProgramVisitor {
509 public:
510 StaticTestVerifier(ErrorReporter* r) : fReporter(r) {}
511
512 using ProgramVisitor::visitProgramElement;
513
514 bool visitStatement(const Statement& stmt) override {
515 switch (stmt.kind()) {
516 case Statement::Kind::kIf:
517 if (stmt.as<IfStatement>().isStatic()) {
518 fReporter->error(stmt.fOffset, "static if has non-static test");
519 }
520 break;
521
522 case Statement::Kind::kSwitch:
523 if (stmt.as<SwitchStatement>().isStatic()) {
524 fReporter->error(stmt.fOffset, "static switch has non-static test");
525 }
526 break;
527
528 default:
529 break;
530 }
531 return INHERITED::visitStatement(stmt);
532 }
533
John Stiles59e34562021-02-12 16:56:39 -0500534 bool visitExpression(const Expression&) override {
535 // We aren't looking for anything inside an Expression, so skip them entirely.
536 return false;
537 }
538
John Stilesbb1505f2021-02-12 09:17:53 -0500539 private:
540 using INHERITED = ProgramVisitor;
541 ErrorReporter* fReporter;
542 };
543
544 // If invalid static tests are permitted, we don't need to check anything.
John Stilesd1204642021-02-17 16:30:02 -0500545 if (fContext->fConfig->fSettings.fPermitInvalidStaticTests) {
John Stilesbb1505f2021-02-12 09:17:53 -0500546 return;
547 }
548
549 // Check all of the program's owned elements. (Built-in elements are assumed to be valid.)
550 StaticTestVerifier visitor{this};
551 for (const std::unique_ptr<ProgramElement>& element : program.ownedElements()) {
552 if (element->is<FunctionDefinition>()) {
553 visitor.visitProgramElement(*element);
554 }
555 }
556}
557
Brian Osman0006ad02020-11-18 15:38:39 -0500558bool Compiler::optimize(LoadedModule& module) {
559 SkASSERT(!fErrorCount);
Brian Osman0006ad02020-11-18 15:38:39 -0500560
John Stiles270cec22021-02-17 12:59:36 -0500561 // Create a temporary program configuration with default settings.
562 ProgramConfig config;
563 config.fKind = module.fKind;
John Stilesa935c3f2021-02-25 10:35:49 -0500564 AutoProgramConfig autoConfig(fContext, &config);
John Stiles270cec22021-02-17 12:59:36 -0500565
John Stilesd1204642021-02-17 16:30:02 -0500566 // Reset the Inliner.
John Stiles10d39d92021-05-04 16:13:14 -0400567 fInliner.reset();
John Stiles270cec22021-02-17 12:59:36 -0500568
569 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
Brian Osman0006ad02020-11-18 15:38:39 -0500570
571 while (fErrorCount == 0) {
Brian Osman0006ad02020-11-18 15:38:39 -0500572 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stilesf3a28db2021-03-10 23:00:47 -0500573 if (!fInliner.analyze(module.fElements, module.fSymbols, usage.get())) {
Brian Osman0006ad02020-11-18 15:38:39 -0500574 break;
575 }
576 }
577 return fErrorCount == 0;
578}
579
John Stiles0bfeae62021-03-11 09:09:42 -0500580bool Compiler::removeDeadFunctions(Program& program, ProgramUsage* usage) {
581 bool madeChanges = false;
582
583 if (program.fConfig->fSettings.fRemoveDeadFunctions) {
584 auto isDeadFunction = [&](const ProgramElement* element) {
585 if (!element->is<FunctionDefinition>()) {
586 return false;
587 }
588 const FunctionDefinition& fn = element->as<FunctionDefinition>();
John Stilese8da4d22021-03-24 09:19:45 -0400589 if (fn.declaration().isMain() || usage->get(fn.declaration()) > 0) {
John Stiles0bfeae62021-03-11 09:09:42 -0500590 return false;
591 }
592 usage->remove(*element);
593 madeChanges = true;
594 return true;
595 };
596
597 program.fElements.erase(std::remove_if(program.fElements.begin(),
598 program.fElements.end(),
599 [&](const std::unique_ptr<ProgramElement>& element) {
600 return isDeadFunction(element.get());
601 }),
602 program.fElements.end());
603 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
604 program.fSharedElements.end(),
605 isDeadFunction),
606 program.fSharedElements.end());
607 }
608 return madeChanges;
609}
610
611bool Compiler::removeDeadGlobalVariables(Program& program, ProgramUsage* usage) {
612 bool madeChanges = false;
613
614 if (program.fConfig->fSettings.fRemoveDeadVariables) {
615 auto isDeadVariable = [&](const ProgramElement* element) {
616 if (!element->is<GlobalVarDeclaration>()) {
617 return false;
618 }
619 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
620 const VarDeclaration& varDecl = global.declaration()->as<VarDeclaration>();
621 if (!usage->isDead(varDecl.var())) {
622 return false;
623 }
624 madeChanges = true;
625 return true;
626 };
627
628 program.fElements.erase(std::remove_if(program.fElements.begin(),
629 program.fElements.end(),
630 [&](const std::unique_ptr<ProgramElement>& element) {
631 return isDeadVariable(element.get());
632 }),
633 program.fElements.end());
634 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
635 program.fSharedElements.end(),
636 isDeadVariable),
637 program.fSharedElements.end());
638 }
639 return madeChanges;
640}
641
John Stiles26541872021-03-16 12:19:54 -0400642bool Compiler::removeDeadLocalVariables(Program& program, ProgramUsage* usage) {
643 class DeadLocalVariableEliminator : public ProgramWriter {
644 public:
645 DeadLocalVariableEliminator(const Context& context, ProgramUsage* usage)
646 : fContext(context)
647 , fUsage(usage) {}
648
649 using ProgramWriter::visitProgramElement;
650
651 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
652 // We don't need to look inside expressions at all.
653 return false;
654 }
655
656 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
657 if (stmt->is<VarDeclaration>()) {
658 VarDeclaration& varDecl = stmt->as<VarDeclaration>();
659 const Variable* var = &varDecl.var();
660 ProgramUsage::VariableCounts* counts = fUsage->fVariableCounts.find(var);
661 SkASSERT(counts);
662 SkASSERT(counts->fDeclared);
663 if (CanEliminate(var, *counts)) {
664 if (var->initialValue()) {
665 // The variable has an initial-value expression, which might have side
666 // effects. ExpressionStatement::Make will preserve side effects, but
667 // replaces pure expressions with Nop.
668 fUsage->remove(stmt.get());
669 stmt = ExpressionStatement::Make(fContext, std::move(varDecl.value()));
670 fUsage->add(stmt.get());
671 } else {
672 // The variable has no initial-value and can be cleanly eliminated.
673 fUsage->remove(stmt.get());
674 stmt = std::make_unique<Nop>();
675 }
676 fMadeChanges = true;
677 }
678 return false;
679 }
680 return INHERITED::visitStatementPtr(stmt);
681 }
682
683 static bool CanEliminate(const Variable* var, const ProgramUsage::VariableCounts& counts) {
684 if (!counts.fDeclared || counts.fRead || var->storage() != VariableStorage::kLocal) {
685 return false;
686 }
687 if (var->initialValue()) {
688 SkASSERT(counts.fWrite >= 1);
689 return counts.fWrite == 1;
690 } else {
691 return counts.fWrite == 0;
692 }
693 }
694
695 bool fMadeChanges = false;
696 const Context& fContext;
697 ProgramUsage* fUsage;
698
699 using INHERITED = ProgramWriter;
700 };
701
702 DeadLocalVariableEliminator visitor{*fContext, usage};
703
704 if (program.fConfig->fSettings.fRemoveDeadVariables) {
705 for (auto& [var, counts] : usage->fVariableCounts) {
706 if (DeadLocalVariableEliminator::CanEliminate(var, counts)) {
707 // This program contains at least one dead local variable.
708 // Scan the program for any dead local variables and eliminate them all.
709 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
710 if (pe->is<FunctionDefinition>()) {
711 visitor.visitProgramElement(*pe);
712 }
713 }
714 break;
715 }
716 }
717 }
718
719 return visitor.fMadeChanges;
720}
721
Ethan Nicholas00543112018-07-31 09:44:36 -0400722bool Compiler::optimize(Program& program) {
John Stiles7247b482021-03-08 10:40:35 -0500723 // The optimizer only needs to run when it is enabled.
724 if (!program.fConfig->fSettings.fOptimize) {
725 return true;
726 }
727
Ethan Nicholas00543112018-07-31 09:44:36 -0400728 SkASSERT(!fErrorCount);
Brian Osman010ce6a2020-10-19 16:34:10 -0400729 ProgramUsage* usage = program.fUsage.get();
John Stiles7954d6c2020-09-01 10:53:02 -0400730
John Stilesb6664582021-03-19 09:46:00 -0400731 if (fErrorCount == 0) {
John Stiles87fc6572021-04-01 14:56:34 +0000732 // Run the inliner only once; it is expensive! Multiple passes can occasionally shake out
733 // more wins, but it's diminishing returns.
734 fInliner.analyze(program.ownedElements(), program.fSymbols, usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400735
John Stilesb6664582021-03-19 09:46:00 -0400736 while (this->removeDeadFunctions(program, usage)) {
737 // Removing dead functions may cause more functions to become unreferenced. Try again.
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400738 }
John Stilesb6664582021-03-19 09:46:00 -0400739 while (this->removeDeadLocalVariables(program, usage)) {
740 // Removing dead variables may cause more variables to become unreferenced. Try again.
741 }
742 if (program.fConfig->fKind != ProgramKind::kFragmentProcessor) {
743 this->removeDeadGlobalVariables(program, usage);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500744 }
Ethan Nicholas00543112018-07-31 09:44:36 -0400745 }
John Stilesbb1505f2021-02-12 09:17:53 -0500746
747 if (fErrorCount == 0) {
748 this->verifyStaticTests(program);
749 }
750
Ethan Nicholas00543112018-07-31 09:44:36 -0400751 return fErrorCount == 0;
752}
753
Brian Osmanfb32ddf2019-06-18 10:14:20 -0400754#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
755
Ethan Nicholas00543112018-07-31 09:44:36 -0400756bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400757 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toSPIRV");
John Stilesa289ac22021-05-06 07:35:35 -0400758 AutoSource as(this, program.fSource.get());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400759#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400760 StringStream buffer;
Brian Osman8b43dad2020-10-09 13:31:42 -0400761 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400762 bool result = cg.generateCode();
John Stiles270cec22021-02-17 12:59:36 -0500763 if (result && program.fConfig->fSettings.fValidateSPIRV) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400764 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400765 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400766 SkASSERT(0 == data.size() % 4);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500767 String errors;
768 auto dumpmsg = [&errors](spv_message_level_t, const char*, const spv_position_t&,
769 const char* m) {
770 errors.appendf("SPIR-V validation error: %s\n", m);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400771 };
772 tools.SetMessageConsumer(dumpmsg);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500773
774 // Verify that the SPIR-V we produced is valid. At runtime, we will abort() with a message
775 // explaining the error. In standalone mode (skslc), we will send the message, plus the
776 // entire disassembled SPIR-V (for easier context & debugging) as *our* error message.
777 result = tools.Validate((const uint32_t*) data.c_str(), data.size() / 4);
778
779 if (!result) {
780#if defined(SKSL_STANDALONE)
781 // Convert the string-stream to a SPIR-V disassembly.
782 std::string disassembly;
783 if (tools.Disassemble((const uint32_t*)data.data(), data.size() / 4, &disassembly)) {
784 errors.append(disassembly);
785 }
786 this->error(-1, errors);
787#else
788 SkDEBUGFAILF("%s", errors.c_str());
789#endif
790 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400791 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400792 }
793#else
Brian Osman8b43dad2020-10-09 13:31:42 -0400794 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500795 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400796#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -0500797 return result;
798}
799
Ethan Nicholas00543112018-07-31 09:44:36 -0400800bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400801 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500802 bool result = this->toSPIRV(program, buffer);
803 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400804 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500805 }
806 return result;
807}
808
Ethan Nicholas00543112018-07-31 09:44:36 -0400809bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400810 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toGLSL");
Brian Osman88cda172020-10-09 12:05:16 -0400811 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400812 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500813 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500814 return result;
815}
816
Ethan Nicholas00543112018-07-31 09:44:36 -0400817bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400818 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500819 bool result = this->toGLSL(program, buffer);
820 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400821 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500822 }
823 return result;
824}
825
Brian Osmanc0243912020-02-19 15:35:26 -0500826bool Compiler::toHLSL(Program& program, String* out) {
827 String spirv;
828 if (!this->toSPIRV(program, &spirv)) {
829 return false;
830 }
831
832 return SPIRVtoHLSL(spirv, out);
833}
834
Ethan Nicholas00543112018-07-31 09:44:36 -0400835bool Compiler::toMetal(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400836 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toMetal");
John Stilesa289ac22021-05-06 07:35:35 -0400837 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400838 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -0400839 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -0400840 return result;
841}
842
Ethan Nicholas00543112018-07-31 09:44:36 -0400843bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -0400844 StringStream buffer;
845 bool result = this->toMetal(program, buffer);
846 if (result) {
847 *out = buffer.str();
848 }
849 return result;
850}
851
Greg Daniela28ea672020-09-25 11:12:56 -0400852#if defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -0400853bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -0400854 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400855 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400856 bool result = cg.generateCode();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400857 return result;
858}
859
John Stiles82ab3402021-04-13 17:13:03 -0400860bool Compiler::toDSLCPP(Program& program, String name, OutputStream& out) {
861 AutoSource as(this, program.fSource.get());
862 DSLCPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
863 bool result = cg.generateCode();
864 return result;
865}
866
Ethan Nicholas00543112018-07-31 09:44:36 -0400867bool Compiler::toH(Program& program, String name, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -0400868 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400869 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400870 bool result = cg.generateCode();
Ethan Nicholas00543112018-07-31 09:44:36 -0400871 return result;
872}
Greg Daniela28ea672020-09-25 11:12:56 -0400873#endif // defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -0400874
Ethan Nicholas2a479a52020-08-18 16:29:45 -0400875#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -0400876
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700877Position Compiler::position(int offset) {
Ethan Nicholas3c729892020-12-07 12:47:17 -0500878 if (fSource && offset >= 0) {
879 int line = 1;
880 int column = 1;
881 for (int i = 0; i < offset; i++) {
882 if ((*fSource)[i] == '\n') {
883 ++line;
884 column = 1;
885 }
886 else {
887 ++column;
888 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700889 }
Ethan Nicholas3c729892020-12-07 12:47:17 -0500890 return Position(line, column);
891 } else {
892 return Position(-1, -1);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700893 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700894}
895
896void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700897 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700898 Position pos = this->position(offset);
John Stiles8d3642e2021-01-22 09:50:04 -0500899 fErrorTextLength.push_back(fErrorText.length());
Ethan Nicholas3c729892020-12-07 12:47:17 -0500900 fErrorText += "error: " + (pos.fLine >= 1 ? to_string(pos.fLine) + ": " : "") + msg + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -0700901}
902
John Stiles8d3642e2021-01-22 09:50:04 -0500903void Compiler::setErrorCount(int c) {
904 if (c < fErrorCount) {
905 fErrorText.resize(fErrorTextLength[c]);
906 fErrorTextLength.resize(c);
907 fErrorCount = c;
908 }
909}
910
Ethan Nicholas95046142021-01-07 10:57:27 -0500911String Compiler::errorText(bool showCount) {
912 if (showCount) {
913 this->writeErrorCount();
914 }
Ethan Nicholas00543112018-07-31 09:44:36 -0400915 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400916 String result = fErrorText;
Ethan Nicholas95046142021-01-07 10:57:27 -0500917 fErrorText = "";
ethannicholasb3058bd2016-07-01 08:22:01 -0700918 return result;
919}
920
921void Compiler::writeErrorCount() {
922 if (fErrorCount) {
923 fErrorText += to_string(fErrorCount) + " error";
924 if (fErrorCount > 1) {
925 fErrorText += "s";
926 }
927 fErrorText += "\n";
928 }
929}
930
John Stilesa6841be2020-08-06 14:11:56 -0400931} // namespace SkSL