blob: 89e5dad59865d32e63bfafe98f338d00a06f9ac4 [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"
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -040018#include "src/sksl/SkSLDSLParser.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/SkSLIRGenerator.h"
Brian Osman00185012021-02-04 16:07:11 -050020#include "src/sksl/SkSLOperators.h"
John Stiles270cec22021-02-17 12:59:36 -050021#include "src/sksl/SkSLProgramSettings.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040022#include "src/sksl/SkSLRehydrator.h"
John Stiles3738ef52021-04-13 10:41:57 -040023#include "src/sksl/codegen/SkSLGLSLCodeGenerator.h"
John Stiles3738ef52021-04-13 10:41:57 -040024#include "src/sksl/codegen/SkSLMetalCodeGenerator.h"
25#include "src/sksl/codegen/SkSLSPIRVCodeGenerator.h"
26#include "src/sksl/codegen/SkSLSPIRVtoHLSL.h"
Ethan Nicholas55a63af2021-05-18 10:12:58 -040027#include "src/sksl/dsl/priv/DSLWriter.h"
28#include "src/sksl/dsl/priv/DSL_priv.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050029#include "src/sksl/ir/SkSLExpression.h"
30#include "src/sksl/ir/SkSLExpressionStatement.h"
31#include "src/sksl/ir/SkSLFunctionCall.h"
32#include "src/sksl/ir/SkSLIntLiteral.h"
33#include "src/sksl/ir/SkSLModifiersDeclaration.h"
34#include "src/sksl/ir/SkSLNop.h"
35#include "src/sksl/ir/SkSLSymbolTable.h"
36#include "src/sksl/ir/SkSLTernaryExpression.h"
37#include "src/sksl/ir/SkSLUnresolvedFunction.h"
38#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stilese6150002020-10-05 12:03:53 -040039#include "src/utils/SkBitSet.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070040
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040041#include <fstream>
42
Ethan Nicholasa11035b2019-11-26 16:27:47 -050043#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
44#include "include/gpu/GrContextOptions.h"
45#include "src/gpu/GrShaderCaps.h"
46#endif
47
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040048#ifdef SK_ENABLE_SPIRV_VALIDATION
49#include "spirv-tools/libspirv.hpp"
50#endif
51
Brian Osman3d87e9f2020-10-08 11:50:22 -040052#if defined(SKSL_STANDALONE)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040053
Brian Osman3d87e9f2020-10-08 11:50:22 -040054// In standalone mode, we load the textual sksl source files. GN generates or copies these files
55// to the skslc executable directory. The "data" in this mode is just the filename.
56#define MODULE_DATA(name) MakeModulePath("sksl_" #name ".sksl")
57
58#else
59
60// At runtime, we load the dehydrated sksl data files. The data is a (pointer, size) pair.
Ethan Nicholasc18bb512020-07-28 14:46:53 -040061#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
62#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
63#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
Brian Osmanb06301e2020-11-06 11:45:36 -050064#include "src/sksl/generated/sksl_public.dehydrated.sksl"
John Stilesf7f36ae2021-06-08 14:06:22 -040065#include "src/sksl/generated/sksl_rt_blend.dehydrated.sksl"
Brian Osmancbb60bd2021-04-12 09:49:20 -040066#include "src/sksl/generated/sksl_rt_colorfilter.dehydrated.sksl"
67#include "src/sksl/generated/sksl_rt_shader.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040068#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
69
Brian Osman3d87e9f2020-10-08 11:50:22 -040070#define MODULE_DATA(name) MakeModuleData(SKSL_INCLUDE_sksl_##name,\
71 SKSL_INCLUDE_sksl_##name##_LENGTH)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040072
73#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040074
ethannicholasb3058bd2016-07-01 08:22:01 -070075namespace SkSL {
76
John Stiles7247b482021-03-08 10:40:35 -050077// These flags allow tools like Viewer or Nanobench to override the compiler's ProgramSettings.
John Stiles2ee4d7a2021-03-30 10:30:47 -040078Compiler::OverrideFlag Compiler::sOptimizer = OverrideFlag::kDefault;
79Compiler::OverrideFlag Compiler::sInliner = OverrideFlag::kDefault;
John Stiles8ef4d6c2021-03-05 16:01:45 -050080
John Stiles47c0a742021-02-09 09:30:35 -050081using RefKind = VariableReference::RefKind;
82
Brian Osman88cda172020-10-09 12:05:16 -040083class AutoSource {
84public:
Ethan Nicholasb449fff2021-08-04 15:06:37 -040085 AutoSource(Compiler* compiler, const char* source)
John Stilesa289ac22021-05-06 07:35:35 -040086 : fCompiler(compiler) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040087 SkASSERT(!fCompiler->errorReporter().source());
88 fCompiler->errorReporter().setSource(source);
Brian Osman88cda172020-10-09 12:05:16 -040089 }
90
John Stilesa289ac22021-05-06 07:35:35 -040091 ~AutoSource() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040092 fCompiler->errorReporter().setSource(nullptr);
John Stilesa289ac22021-05-06 07:35:35 -040093 }
Brian Osman88cda172020-10-09 12:05:16 -040094
95 Compiler* fCompiler;
Brian Osman88cda172020-10-09 12:05:16 -040096};
97
John Stilesa935c3f2021-02-25 10:35:49 -050098class AutoProgramConfig {
99public:
100 AutoProgramConfig(std::shared_ptr<Context>& context, ProgramConfig* config)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400101 : fContext(context.get())
102 , fOldConfig(fContext->fConfig) {
John Stilesa935c3f2021-02-25 10:35:49 -0500103 fContext->fConfig = config;
104 }
105
106 ~AutoProgramConfig() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400107 fContext->fConfig = fOldConfig;
John Stilesa935c3f2021-02-25 10:35:49 -0500108 }
109
110 Context* fContext;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400111 ProgramConfig* fOldConfig;
John Stilesa935c3f2021-02-25 10:35:49 -0500112};
113
John Stiles10d39d92021-05-04 16:13:14 -0400114class AutoModifiersPool {
115public:
116 AutoModifiersPool(std::shared_ptr<Context>& context, ModifiersPool* modifiersPool)
117 : fContext(context.get()) {
118 SkASSERT(!fContext->fModifiersPool);
119 fContext->fModifiersPool = modifiersPool;
120 }
121
122 ~AutoModifiersPool() {
123 fContext->fModifiersPool = nullptr;
124 }
125
126 Context* fContext;
127};
128
John Stilesd6a5f4492021-02-11 15:46:11 -0500129Compiler::Compiler(const ShaderCapsClass* caps)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400130 : fErrorReporter(this)
131 , fContext(std::make_shared<Context>(fErrorReporter, *caps))
John Stilesa47b3512021-05-04 16:15:00 -0400132 , fInliner(fContext.get()) {
John Stilesc1a98b82021-02-24 13:35:02 -0500133 SkASSERT(caps);
John Stilesb624b722021-08-13 12:16:13 -0400134 fRootModule.fSymbols = this->makeRootSymbolTable();
135 fPrivateModule.fSymbols = this->makePrivateSymbolTable(fRootModule.fSymbols);
John Stilesc1a98b82021-02-24 13:35:02 -0500136 fIRGenerator = std::make_unique<IRGenerator>(fContext.get());
John Stilesb624b722021-08-13 12:16:13 -0400137}
138
139Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700140
John Stiles54e7c052021-01-11 14:22:36 -0500141#define TYPE(t) fContext->fTypes.f ## t .get()
ethannicholasb3058bd2016-07-01 08:22:01 -0700142
John Stilesb624b722021-08-13 12:16:13 -0400143std::shared_ptr<SymbolTable> Compiler::makeRootSymbolTable() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400144 auto rootSymbolTable = std::make_shared<SymbolTable>(&this->errorReporter(), /*builtin=*/true);
John Stilesb624b722021-08-13 12:16:13 -0400145
Brian Osmanb06301e2020-11-06 11:45:36 -0500146 const SkSL::Symbol* rootTypes[] = {
147 TYPE(Void),
Brian Salomonbf7b6202016-11-11 16:08:03 -0500148
Brian Osmanb06301e2020-11-06 11:45:36 -0500149 TYPE( Float), TYPE( Float2), TYPE( Float3), TYPE( Float4),
150 TYPE( Half), TYPE( Half2), TYPE( Half3), TYPE( Half4),
151 TYPE( Int), TYPE( Int2), TYPE( Int3), TYPE( Int4),
Brian Osmanb06301e2020-11-06 11:45:36 -0500152 TYPE( Bool), TYPE( Bool2), TYPE( Bool3), TYPE( Bool4),
Brian Salomon2a51de82016-11-16 12:06:01 -0500153
Brian Osmanc0f2b642020-12-22 13:35:55 -0500154 TYPE(Float2x2), TYPE(Float3x3), TYPE(Float4x4),
Brian Osmanc63f4312020-12-23 11:44:14 -0500155 TYPE( Half2x2), TYPE( Half3x3), TYPE(Half4x4),
Greg Daniel64773e62016-11-22 09:44:03 -0500156
Brian Osmanc63f4312020-12-23 11:44:14 -0500157 TYPE(SquareMat), TYPE(SquareHMat),
ethannicholasb3058bd2016-07-01 08:22:01 -0700158
Brian Osman20fad322020-12-23 12:42:33 -0500159 TYPE(GenType), TYPE(GenHType), TYPE(GenIType), TYPE(GenBType),
160 TYPE(Vec), TYPE(HVec), TYPE(IVec), TYPE(BVec),
Brian Osmanb06301e2020-11-06 11:45:36 -0500161
Brian Osman14d00962021-04-02 17:04:35 -0400162 TYPE(ColorFilter),
163 TYPE(Shader),
John Stilesbb2ef922021-07-26 08:32:07 -0400164 TYPE(Blender),
Brian Osmanb06301e2020-11-06 11:45:36 -0500165 };
166
John Stilesb624b722021-08-13 12:16:13 -0400167 for (const SkSL::Symbol* type : rootTypes) {
168 rootSymbolTable->addWithoutOwnership(type);
169 }
170
171 return rootSymbolTable;
172}
173
174std::shared_ptr<SymbolTable> Compiler::makePrivateSymbolTable(std::shared_ptr<SymbolTable> parent) {
175 auto privateSymbolTable = std::make_shared<SymbolTable>(parent, /*builtin=*/true);
176
Brian Osmanb06301e2020-11-06 11:45:36 -0500177 const SkSL::Symbol* privateTypes[] = {
Brian Osman20fad322020-12-23 12:42:33 -0500178 TYPE( UInt), TYPE( UInt2), TYPE( UInt3), TYPE( UInt4),
179 TYPE( Short), TYPE( Short2), TYPE( Short3), TYPE( Short4),
180 TYPE(UShort), TYPE(UShort2), TYPE(UShort3), TYPE(UShort4),
Brian Osman20fad322020-12-23 12:42:33 -0500181
182 TYPE(GenUType), TYPE(UVec),
John Stilesb624b722021-08-13 12:16:13 -0400183 TYPE(SVec), TYPE(USVec),
Brian Osman20fad322020-12-23 12:42:33 -0500184
Brian Osmanc0f2b642020-12-22 13:35:55 -0500185 TYPE(Float2x3), TYPE(Float2x4),
186 TYPE(Float3x2), TYPE(Float3x4),
187 TYPE(Float4x2), TYPE(Float4x3),
188
Brian Osmanc63f4312020-12-23 11:44:14 -0500189 TYPE(Half2x3), TYPE(Half2x4),
190 TYPE(Half3x2), TYPE(Half3x4),
191 TYPE(Half4x2), TYPE(Half4x3),
192
Brian Osmanc0f2b642020-12-22 13:35:55 -0500193 TYPE(Mat), TYPE(HMat),
194
Brian Osmanb06301e2020-11-06 11:45:36 -0500195 TYPE(Sampler1D), TYPE(Sampler2D), TYPE(Sampler3D),
196 TYPE(SamplerExternalOES),
Brian Osmanb06301e2020-11-06 11:45:36 -0500197 TYPE(Sampler2DRect),
Brian Osmanb06301e2020-11-06 11:45:36 -0500198
199 TYPE(ISampler2D),
Brian Osmanb06301e2020-11-06 11:45:36 -0500200 TYPE(SubpassInput), TYPE(SubpassInputMS),
201
Brian Osmanb06301e2020-11-06 11:45:36 -0500202 TYPE(Sampler),
203 TYPE(Texture2D),
204 };
205
Brian Osmanb06301e2020-11-06 11:45:36 -0500206 for (const SkSL::Symbol* type : privateTypes) {
John Stilesb624b722021-08-13 12:16:13 -0400207 privateSymbolTable->addWithoutOwnership(type);
Brian Osmanb06301e2020-11-06 11:45:36 -0500208 }
209
Brian Osman3887a012020-09-30 13:22:27 -0400210 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
211 // treat it as builtin (ie, no need to clone it into the Program).
John Stilesb624b722021-08-13 12:16:13 -0400212 privateSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
213 fCoreModifiers.add(Modifiers{}),
214 "sk_Caps",
215 fContext->fTypes.fSkCaps.get(),
216 /*builtin=*/false,
217 Variable::Storage::kGlobal));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500218
John Stilesb624b722021-08-13 12:16:13 -0400219 return privateSymbolTable;
ethannicholasb3058bd2016-07-01 08:22:01 -0700220}
221
John Stilesb624b722021-08-13 12:16:13 -0400222#undef TYPE
ethannicholasb3058bd2016-07-01 08:22:01 -0700223
Brian Osman56269982020-11-20 12:38:07 -0500224const ParsedModule& Compiler::loadGPUModule() {
225 if (!fGPUModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500226 fGPUModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(gpu), fPrivateModule);
Brian Osman56269982020-11-20 12:38:07 -0500227 }
228 return fGPUModule;
229}
230
231const ParsedModule& Compiler::loadFragmentModule() {
232 if (!fFragmentModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500233 fFragmentModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(frag),
Brian Osman56269982020-11-20 12:38:07 -0500234 this->loadGPUModule());
235 }
236 return fFragmentModule;
237}
238
239const ParsedModule& Compiler::loadVertexModule() {
240 if (!fVertexModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500241 fVertexModule = this->parseModule(ProgramKind::kVertex, MODULE_DATA(vert),
Brian Osman56269982020-11-20 12:38:07 -0500242 this->loadGPUModule());
243 }
244 return fVertexModule;
245}
246
Brian Osman88cda172020-10-09 12:05:16 -0400247const ParsedModule& Compiler::loadGeometryModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400248 if (!fGeometryModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500249 fGeometryModule = this->parseModule(ProgramKind::kGeometry, MODULE_DATA(geom),
Brian Osman56269982020-11-20 12:38:07 -0500250 this->loadGPUModule());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400251 }
Brian Osman88cda172020-10-09 12:05:16 -0400252 return fGeometryModule;
Ethan Nicholasc18bb512020-07-28 14:46:53 -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 Stiles2d8b8352021-06-16 11:33:13 -0400300const ParsedModule& Compiler::loadRuntimeBlenderModule() {
301 if (!fRuntimeBlenderModule.fSymbols) {
302 fRuntimeBlenderModule = this->parseModule(
303 ProgramKind::kRuntimeBlender, MODULE_DATA(rt_blend), this->loadPublicModule());
304 add_glsl_type_aliases(fRuntimeBlenderModule.fSymbols.get(), fContext->fTypes);
John Stilesf7f36ae2021-06-08 14:06:22 -0400305 }
John Stiles2d8b8352021-06-16 11:33:13 -0400306 return fRuntimeBlenderModule;
John Stilesf7f36ae2021-06-08 14:06:22 -0400307}
308
John Stilesdbd4e6f2021-02-16 13:29:15 -0500309const ParsedModule& Compiler::moduleForProgramKind(ProgramKind kind) {
Brian Osman88cda172020-10-09 12:05:16 -0400310 switch (kind) {
Brian Osmancbb60bd2021-04-12 09:49:20 -0400311 case ProgramKind::kVertex: return this->loadVertexModule(); break;
312 case ProgramKind::kFragment: return this->loadFragmentModule(); break;
313 case ProgramKind::kGeometry: return this->loadGeometryModule(); break;
Brian Osmancbb60bd2021-04-12 09:49:20 -0400314 case ProgramKind::kRuntimeColorFilter: return this->loadRuntimeColorFilterModule(); break;
315 case ProgramKind::kRuntimeShader: return this->loadRuntimeShaderModule(); break;
John Stiles2d8b8352021-06-16 11:33:13 -0400316 case ProgramKind::kRuntimeBlender: return this->loadRuntimeBlenderModule(); break;
Brian Osmancbb60bd2021-04-12 09:49:20 -0400317 case ProgramKind::kGeneric: return this->loadPublicModule(); break;
Brian Osman88cda172020-10-09 12:05:16 -0400318 }
319 SkUNREACHABLE;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400320}
321
John Stilesdbd4e6f2021-02-16 13:29:15 -0500322LoadedModule Compiler::loadModule(ProgramKind kind,
Brian Osman3d87e9f2020-10-08 11:50:22 -0400323 ModuleData data,
John Stilesa935c3f2021-02-25 10:35:49 -0500324 std::shared_ptr<SymbolTable> base,
325 bool dehydrate) {
326 if (dehydrate) {
327 // NOTE: This is a workaround. When dehydrating includes, skslc doesn't know which module
328 // it's preparing, nor what the correct base module is. We can't use 'Root', because many
329 // GPU intrinsics reference private types, like samplers or textures. Today, 'Private' does
330 // contain the union of all known types, so this is safe. If we ever have types that only
331 // exist in 'Public' (for example), this logic needs to be smarter (by choosing the correct
332 // base for the module we're compiling).
John Stilesb624b722021-08-13 12:16:13 -0400333 base = fPrivateModule.fSymbols;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400334 }
John Stilesa935c3f2021-02-25 10:35:49 -0500335 SkASSERT(base);
336
John Stilesa47b3512021-05-04 16:15:00 -0400337 // Put the core-module modifier pool into the context.
338 AutoModifiersPool autoPool(fContext, &fCoreModifiers);
John Stiles10d39d92021-05-04 16:13:14 -0400339
John Stilesa935c3f2021-02-25 10:35:49 -0500340 // Built-in modules always use default program settings.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400341 Program::Settings settings;
342 settings.fReplaceSettings = !dehydrate;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400343
344#if defined(SKSL_STANDALONE)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400345 SkASSERT(this->errorCount() == 0);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400346 SkASSERT(data.fPath);
347 std::ifstream in(data.fPath);
John Stilesd51c9792021-03-18 11:40:14 -0400348 String text{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400349 if (in.rdstate()) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400350 printf("error reading %s\n", data.fPath);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400351 abort();
352 }
John Stilesb624b722021-08-13 12:16:13 -0400353 const String* source = fRootModule.fSymbols->takeOwnershipOfString(std::move(text));
John Stilesd1204642021-02-17 16:30:02 -0500354
Brian Osman88cda172020-10-09 12:05:16 -0400355 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400356 std::vector<std::unique_ptr<ProgramElement>> elements;
357 std::vector<const ProgramElement*> sharedElements;
358 dsl::StartModule(this, kind, settings, baseModule);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400359 dsl::SetErrorReporter(&this->errorReporter());
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400360 AutoSource as(this, source->c_str());
John Stilesd1204642021-02-17 16:30:02 -0500361 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/true,
Ethan Nicholas6823b502021-06-15 11:42:07 -0400362 *source);
Brian Osman133724c2020-10-28 14:14:39 -0400363 SkASSERT(ir.fSharedElements.empty());
Brian Osman0006ad02020-11-18 15:38:39 -0500364 LoadedModule module = { kind, std::move(ir.fSymbolTable), std::move(ir.fElements) };
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400365 if (this->errorCount()) {
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400366 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400367 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400368 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400369 dsl::End();
Brian Osman3d87e9f2020-10-08 11:50:22 -0400370#else
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400371 ProgramConfig config;
372 config.fKind = kind;
373 config.fSettings = settings;
374 AutoProgramConfig autoConfig(fContext, &config);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400375 SkASSERT(data.fData && (data.fSize != 0));
John Stiles10d39d92021-05-04 16:13:14 -0400376 Rehydrator rehydrator(fContext.get(), base, data.fData, data.fSize);
Brian Osman0006ad02020-11-18 15:38:39 -0500377 LoadedModule module = { kind, rehydrator.symbolTable(), rehydrator.elements() };
Brian Osman3d87e9f2020-10-08 11:50:22 -0400378#endif
379
380 return module;
381}
382
John Stilesdbd4e6f2021-02-16 13:29:15 -0500383ParsedModule Compiler::parseModule(ProgramKind kind, ModuleData data, const ParsedModule& base) {
John Stilesa935c3f2021-02-25 10:35:49 -0500384 LoadedModule module = this->loadModule(kind, data, base.fSymbols, /*dehydrate=*/false);
Brian Osman0006ad02020-11-18 15:38:39 -0500385 this->optimize(module);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400386
387 // For modules that just declare (but don't define) intrinsic functions, there will be no new
388 // program elements. In that case, we can share our parent's intrinsic map:
Brian Osman0006ad02020-11-18 15:38:39 -0500389 if (module.fElements.empty()) {
John Stiles10d39d92021-05-04 16:13:14 -0400390 return ParsedModule{module.fSymbols, base.fIntrinsics};
Brian Osman3d87e9f2020-10-08 11:50:22 -0400391 }
392
393 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
394
395 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
396 // global objects to the declaring ProgramElement.
Brian Osman0006ad02020-11-18 15:38:39 -0500397 for (std::unique_ptr<ProgramElement>& element : module.fElements) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400398 switch (element->kind()) {
399 case ProgramElement::Kind::kFunction: {
400 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400401 SkASSERT(f.declaration().isBuiltin());
402 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400403 break;
404 }
John Stiles569249b2020-11-03 12:18:22 -0500405 case ProgramElement::Kind::kFunctionPrototype: {
406 // These are already in the symbol table.
407 break;
408 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400409 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400410 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
411 const Variable& var = global.declaration()->as<VarDeclaration>().var();
412 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400413 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400414 break;
415 }
416 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400417 const Variable& var = element->as<InterfaceBlock>().variable();
418 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400419 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400420 break;
421 }
422 default:
423 printf("Unsupported element: %s\n", element->description().c_str());
424 SkASSERT(false);
425 break;
426 }
427 }
428
John Stiles10d39d92021-05-04 16:13:14 -0400429 return ParsedModule{module.fSymbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400430}
431
Brian Osman32d53552020-09-23 13:55:20 -0400432std::unique_ptr<Program> Compiler::convertProgram(
John Stilesdbd4e6f2021-02-16 13:29:15 -0500433 ProgramKind kind,
Brian Osman32d53552020-09-23 13:55:20 -0400434 String text,
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400435 Program::Settings settings) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400436 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::convertProgram");
Leon Scrogginsb66214e2021-02-11 17:14:18 -0500437
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400438 SkASSERT(!settings.fExternalFunctions || (kind == ProgramKind::kGeneric));
Ethan Nicholas91164d12019-05-15 15:29:54 -0400439
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400440#if !SKSL_DSL_PARSER
Brian Osman0006ad02020-11-18 15:38:39 -0500441 // Loading and optimizing our base module might reset the inliner, so do that first,
442 // *then* configure the inliner with the settings for this program.
443 const ParsedModule& baseModule = this->moduleForProgramKind(kind);
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400444#endif
Brian Osman0006ad02020-11-18 15:38:39 -0500445
John Stiles2ee4d7a2021-03-30 10:30:47 -0400446 // Honor our optimization-override flags.
447 switch (sOptimizer) {
448 case OverrideFlag::kDefault:
449 break;
450 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400451 settings.fOptimize = false;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400452 break;
453 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400454 settings.fOptimize = true;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400455 break;
456 }
457
458 switch (sInliner) {
459 case OverrideFlag::kDefault:
460 break;
461 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400462 settings.fInlineThreshold = 0;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400463 break;
464 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400465 if (settings.fInlineThreshold == 0) {
466 settings.fInlineThreshold = kDefaultInlineThreshold;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400467 }
468 break;
469 }
John Stiles7247b482021-03-08 10:40:35 -0500470
471 // Disable optimization settings that depend on a parent setting which has been disabled.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400472 settings.fInlineThreshold *= (int)settings.fOptimize;
473 settings.fRemoveDeadFunctions &= settings.fOptimize;
474 settings.fRemoveDeadVariables &= settings.fOptimize;
John Stiles7247b482021-03-08 10:40:35 -0500475
John Stilesaddccaf2021-08-02 19:03:30 -0400476 // Runtime effects always allow narrowing conversions.
477 if (ProgramConfig::IsRuntimeEffect(kind)) {
478 settings.fAllowNarrowingConversions = true;
479 }
480
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400481 this->resetErrors();
John Stiles10d39d92021-05-04 16:13:14 -0400482 fInliner.reset();
Brian Osman88cda172020-10-09 12:05:16 -0400483
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400484#if SKSL_DSL_PARSER
485 settings.fDSLMangling = false;
486 return DSLParser(this, settings, kind, text).program();
487#else
John Stiles10d39d92021-05-04 16:13:14 -0400488 auto textPtr = std::make_unique<String>(std::move(text));
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400489 AutoSource as(this, textPtr->c_str());
Brian Osman88cda172020-10-09 12:05:16 -0400490
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400491 dsl::Start(this, kind, settings);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400492 dsl::SetErrorReporter(&fErrorReporter);
John Stilesd1204642021-02-17 16:30:02 -0500493 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/false,
Ethan Nicholas6823b502021-06-15 11:42:07 -0400494 *textPtr);
Ethan Nicholas4f3e6a22021-06-15 09:17:05 -0400495 // Ideally, we would just use dsl::ReleaseProgram and not have to do any manual mucking about
496 // with the memory pool, but we've got some impedance mismatches to solve first
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400497 Pool* memoryPool = dsl::DSLWriter::MemoryPool().get();
John Stiles270cec22021-02-17 12:59:36 -0500498 auto program = std::make_unique<Program>(std::move(textPtr),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400499 std::move(dsl::DSLWriter::GetProgramConfig()),
John Stiles5c7bb322020-10-22 11:09:15 -0400500 fContext,
501 std::move(ir.fElements),
Brian Osman133724c2020-10-28 14:14:39 -0400502 std::move(ir.fSharedElements),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400503 std::move(dsl::DSLWriter::GetModifiersPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400504 std::move(ir.fSymbolTable),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400505 std::move(dsl::DSLWriter::MemoryPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400506 ir.fInputs);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400507 this->errorReporter().reportPendingErrors(PositionInfo());
John Stiles5c7bb322020-10-22 11:09:15 -0400508 bool success = false;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400509 if (this->errorCount()) {
John Stiles5c7bb322020-10-22 11:09:15 -0400510 // Do not return programs that failed to compile.
John Stiles7247b482021-03-08 10:40:35 -0500511 } else if (!this->optimize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400512 // Do not return programs that failed to optimize.
513 } else {
514 // We have a successful program!
515 success = true;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500516 }
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400517 dsl::End();
518 if (memoryPool) {
519 memoryPool->detachFromThread();
Brian Osman28f702c2021-02-02 11:52:07 -0500520 }
John Stiles5c7bb322020-10-22 11:09:15 -0400521 return success ? std::move(program) : nullptr;
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400522#endif // SKSL_DSL_PARSER
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500523}
524
John Stilesbb1505f2021-02-12 09:17:53 -0500525void Compiler::verifyStaticTests(const Program& program) {
526 class StaticTestVerifier : public ProgramVisitor {
527 public:
528 StaticTestVerifier(ErrorReporter* r) : fReporter(r) {}
529
530 using ProgramVisitor::visitProgramElement;
531
532 bool visitStatement(const Statement& stmt) override {
533 switch (stmt.kind()) {
534 case Statement::Kind::kIf:
535 if (stmt.as<IfStatement>().isStatic()) {
536 fReporter->error(stmt.fOffset, "static if has non-static test");
537 }
538 break;
539
540 case Statement::Kind::kSwitch:
541 if (stmt.as<SwitchStatement>().isStatic()) {
542 fReporter->error(stmt.fOffset, "static switch has non-static test");
543 }
544 break;
545
546 default:
547 break;
548 }
549 return INHERITED::visitStatement(stmt);
550 }
551
John Stiles59e34562021-02-12 16:56:39 -0500552 bool visitExpression(const Expression&) override {
553 // We aren't looking for anything inside an Expression, so skip them entirely.
554 return false;
555 }
556
John Stilesbb1505f2021-02-12 09:17:53 -0500557 private:
558 using INHERITED = ProgramVisitor;
559 ErrorReporter* fReporter;
560 };
561
562 // If invalid static tests are permitted, we don't need to check anything.
John Stilesd1204642021-02-17 16:30:02 -0500563 if (fContext->fConfig->fSettings.fPermitInvalidStaticTests) {
John Stilesbb1505f2021-02-12 09:17:53 -0500564 return;
565 }
566
567 // Check all of the program's owned elements. (Built-in elements are assumed to be valid.)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400568 StaticTestVerifier visitor{&this->errorReporter()};
John Stilesbb1505f2021-02-12 09:17:53 -0500569 for (const std::unique_ptr<ProgramElement>& element : program.ownedElements()) {
570 if (element->is<FunctionDefinition>()) {
571 visitor.visitProgramElement(*element);
572 }
573 }
574}
575
Brian Osman0006ad02020-11-18 15:38:39 -0500576bool Compiler::optimize(LoadedModule& module) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400577 SkASSERT(!this->errorCount());
Brian Osman0006ad02020-11-18 15:38:39 -0500578
John Stiles270cec22021-02-17 12:59:36 -0500579 // Create a temporary program configuration with default settings.
580 ProgramConfig config;
581 config.fKind = module.fKind;
John Stilesa935c3f2021-02-25 10:35:49 -0500582 AutoProgramConfig autoConfig(fContext, &config);
John Stiles270cec22021-02-17 12:59:36 -0500583
John Stilesd1204642021-02-17 16:30:02 -0500584 // Reset the Inliner.
John Stiles10d39d92021-05-04 16:13:14 -0400585 fInliner.reset();
John Stiles270cec22021-02-17 12:59:36 -0500586
587 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
Brian Osman0006ad02020-11-18 15:38:39 -0500588
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400589 while (this->errorCount() == 0) {
Brian Osman0006ad02020-11-18 15:38:39 -0500590 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stilesf3a28db2021-03-10 23:00:47 -0500591 if (!fInliner.analyze(module.fElements, module.fSymbols, usage.get())) {
Brian Osman0006ad02020-11-18 15:38:39 -0500592 break;
593 }
594 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400595 return this->errorCount() == 0;
Brian Osman0006ad02020-11-18 15:38:39 -0500596}
597
John Stiles0bfeae62021-03-11 09:09:42 -0500598bool Compiler::removeDeadFunctions(Program& program, ProgramUsage* usage) {
599 bool madeChanges = false;
600
601 if (program.fConfig->fSettings.fRemoveDeadFunctions) {
602 auto isDeadFunction = [&](const ProgramElement* element) {
603 if (!element->is<FunctionDefinition>()) {
604 return false;
605 }
606 const FunctionDefinition& fn = element->as<FunctionDefinition>();
John Stilese8da4d22021-03-24 09:19:45 -0400607 if (fn.declaration().isMain() || usage->get(fn.declaration()) > 0) {
John Stiles0bfeae62021-03-11 09:09:42 -0500608 return false;
609 }
610 usage->remove(*element);
611 madeChanges = true;
612 return true;
613 };
614
615 program.fElements.erase(std::remove_if(program.fElements.begin(),
616 program.fElements.end(),
617 [&](const std::unique_ptr<ProgramElement>& element) {
618 return isDeadFunction(element.get());
619 }),
620 program.fElements.end());
621 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
622 program.fSharedElements.end(),
623 isDeadFunction),
624 program.fSharedElements.end());
625 }
626 return madeChanges;
627}
628
629bool Compiler::removeDeadGlobalVariables(Program& program, ProgramUsage* usage) {
630 bool madeChanges = false;
631
632 if (program.fConfig->fSettings.fRemoveDeadVariables) {
633 auto isDeadVariable = [&](const ProgramElement* element) {
634 if (!element->is<GlobalVarDeclaration>()) {
635 return false;
636 }
637 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
638 const VarDeclaration& varDecl = global.declaration()->as<VarDeclaration>();
639 if (!usage->isDead(varDecl.var())) {
640 return false;
641 }
642 madeChanges = true;
643 return true;
644 };
645
646 program.fElements.erase(std::remove_if(program.fElements.begin(),
647 program.fElements.end(),
648 [&](const std::unique_ptr<ProgramElement>& element) {
649 return isDeadVariable(element.get());
650 }),
651 program.fElements.end());
652 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
653 program.fSharedElements.end(),
654 isDeadVariable),
655 program.fSharedElements.end());
656 }
657 return madeChanges;
658}
659
John Stiles26541872021-03-16 12:19:54 -0400660bool Compiler::removeDeadLocalVariables(Program& program, ProgramUsage* usage) {
661 class DeadLocalVariableEliminator : public ProgramWriter {
662 public:
663 DeadLocalVariableEliminator(const Context& context, ProgramUsage* usage)
664 : fContext(context)
665 , fUsage(usage) {}
666
667 using ProgramWriter::visitProgramElement;
668
669 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
670 // We don't need to look inside expressions at all.
671 return false;
672 }
673
674 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
675 if (stmt->is<VarDeclaration>()) {
676 VarDeclaration& varDecl = stmt->as<VarDeclaration>();
677 const Variable* var = &varDecl.var();
678 ProgramUsage::VariableCounts* counts = fUsage->fVariableCounts.find(var);
679 SkASSERT(counts);
680 SkASSERT(counts->fDeclared);
681 if (CanEliminate(var, *counts)) {
682 if (var->initialValue()) {
683 // The variable has an initial-value expression, which might have side
684 // effects. ExpressionStatement::Make will preserve side effects, but
685 // replaces pure expressions with Nop.
686 fUsage->remove(stmt.get());
687 stmt = ExpressionStatement::Make(fContext, std::move(varDecl.value()));
688 fUsage->add(stmt.get());
689 } else {
690 // The variable has no initial-value and can be cleanly eliminated.
691 fUsage->remove(stmt.get());
692 stmt = std::make_unique<Nop>();
693 }
694 fMadeChanges = true;
695 }
696 return false;
697 }
698 return INHERITED::visitStatementPtr(stmt);
699 }
700
701 static bool CanEliminate(const Variable* var, const ProgramUsage::VariableCounts& counts) {
702 if (!counts.fDeclared || counts.fRead || var->storage() != VariableStorage::kLocal) {
703 return false;
704 }
705 if (var->initialValue()) {
706 SkASSERT(counts.fWrite >= 1);
707 return counts.fWrite == 1;
708 } else {
709 return counts.fWrite == 0;
710 }
711 }
712
713 bool fMadeChanges = false;
714 const Context& fContext;
715 ProgramUsage* fUsage;
716
717 using INHERITED = ProgramWriter;
718 };
719
720 DeadLocalVariableEliminator visitor{*fContext, usage};
721
722 if (program.fConfig->fSettings.fRemoveDeadVariables) {
723 for (auto& [var, counts] : usage->fVariableCounts) {
724 if (DeadLocalVariableEliminator::CanEliminate(var, counts)) {
725 // This program contains at least one dead local variable.
726 // Scan the program for any dead local variables and eliminate them all.
727 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
728 if (pe->is<FunctionDefinition>()) {
729 visitor.visitProgramElement(*pe);
730 }
731 }
732 break;
733 }
734 }
735 }
736
737 return visitor.fMadeChanges;
738}
739
John Stiles25be58e2021-05-20 14:38:40 -0400740void Compiler::removeUnreachableCode(Program& program, ProgramUsage* usage) {
741 class UnreachableCodeEliminator : public ProgramWriter {
742 public:
743 UnreachableCodeEliminator(const Context& context, ProgramUsage* usage)
744 : fContext(context)
745 , fUsage(usage) {
746 fFoundFunctionExit.push(false);
747 fFoundLoopExit.push(false);
748 }
749
750 using ProgramWriter::visitProgramElement;
751
752 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
753 // We don't need to look inside expressions at all.
754 return false;
755 }
756
757 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
758 if (fFoundFunctionExit.top() || fFoundLoopExit.top()) {
759 // If we already found an exit in this section, anything beyond it is dead code.
760 if (!stmt->is<Nop>()) {
761 // Eliminate the dead statement by substituting a Nop.
762 fUsage->remove(stmt.get());
763 stmt = std::make_unique<Nop>();
764 }
765 return false;
766 }
767
768 switch (stmt->kind()) {
769 case Statement::Kind::kReturn:
770 case Statement::Kind::kDiscard:
771 // We found a function exit on this path.
772 fFoundFunctionExit.top() = true;
773 break;
774
775 case Statement::Kind::kBreak:
776 case Statement::Kind::kContinue:
777 // We found a loop exit on this path. Note that we skip over switch statements
778 // completely when eliminating code, so any `break` statement would be breaking
779 // out of a loop, not out of a switch.
780 fFoundLoopExit.top() = true;
781 break;
782
783 case Statement::Kind::kExpression:
784 case Statement::Kind::kInlineMarker:
785 case Statement::Kind::kNop:
786 case Statement::Kind::kVarDeclaration:
787 // These statements don't affect control flow.
788 break;
789
790 case Statement::Kind::kBlock:
791 // Blocks are on the straight-line path and don't affect control flow.
792 return INHERITED::visitStatementPtr(stmt);
793
794 case Statement::Kind::kDo: {
795 // Function-exits are allowed to propagate outside of a do-loop, because it
796 // always executes its body at least once.
797 fFoundLoopExit.push(false);
798 bool result = INHERITED::visitStatementPtr(stmt);
799 fFoundLoopExit.pop();
800 return result;
801 }
802 case Statement::Kind::kFor: {
803 // Function-exits are not allowed to propagate out, because a for-loop or while-
804 // loop could potentially run zero times.
805 fFoundFunctionExit.push(false);
806 fFoundLoopExit.push(false);
807 bool result = INHERITED::visitStatementPtr(stmt);
808 fFoundLoopExit.pop();
809 fFoundFunctionExit.pop();
810 return result;
811 }
812 case Statement::Kind::kIf: {
813 // This statement is conditional and encloses two inner sections of code.
814 // If both sides contain a function-exit or loop-exit, that exit is allowed to
815 // propagate out.
816 IfStatement& ifStmt = stmt->as<IfStatement>();
817
818 fFoundFunctionExit.push(false);
819 fFoundLoopExit.push(false);
820 bool result = (ifStmt.ifTrue() && this->visitStatementPtr(ifStmt.ifTrue()));
821 bool foundFunctionExitOnTrue = fFoundFunctionExit.top();
822 bool foundLoopExitOnTrue = fFoundLoopExit.top();
823 fFoundFunctionExit.pop();
824 fFoundLoopExit.pop();
825
826 fFoundFunctionExit.push(false);
827 fFoundLoopExit.push(false);
828 result |= (ifStmt.ifFalse() && this->visitStatementPtr(ifStmt.ifFalse()));
829 bool foundFunctionExitOnFalse = fFoundFunctionExit.top();
830 bool foundLoopExitOnFalse = fFoundLoopExit.top();
831 fFoundFunctionExit.pop();
832 fFoundLoopExit.pop();
833
834 fFoundFunctionExit.top() |= foundFunctionExitOnTrue && foundFunctionExitOnFalse;
835 fFoundLoopExit.top() |= foundLoopExitOnTrue && foundLoopExitOnFalse;
836 return result;
837 }
838 case Statement::Kind::kSwitch:
839 case Statement::Kind::kSwitchCase:
840 // We skip past switch statements entirely when scanning for dead code. Their
841 // control flow is quite complex and we already do a good job of flattening out
842 // switches on constant values.
843 break;
844 }
845
846 return false;
847 }
848
849 const Context& fContext;
850 ProgramUsage* fUsage;
851 std::stack<bool> fFoundFunctionExit;
852 std::stack<bool> fFoundLoopExit;
853
854 using INHERITED = ProgramWriter;
855 };
856
857 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
858 if (pe->is<FunctionDefinition>()) {
859 UnreachableCodeEliminator visitor{*fContext, usage};
860 visitor.visitProgramElement(*pe);
861 }
862 }
863}
864
Ethan Nicholas00543112018-07-31 09:44:36 -0400865bool Compiler::optimize(Program& program) {
John Stiles7247b482021-03-08 10:40:35 -0500866 // The optimizer only needs to run when it is enabled.
867 if (!program.fConfig->fSettings.fOptimize) {
868 return true;
869 }
870
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400871 SkASSERT(!this->errorCount());
Brian Osman010ce6a2020-10-19 16:34:10 -0400872 ProgramUsage* usage = program.fUsage.get();
John Stiles7954d6c2020-09-01 10:53:02 -0400873
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400874 if (this->errorCount() == 0) {
John Stiles87fc6572021-04-01 14:56:34 +0000875 // Run the inliner only once; it is expensive! Multiple passes can occasionally shake out
876 // more wins, but it's diminishing returns.
877 fInliner.analyze(program.ownedElements(), program.fSymbols, usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400878
John Stilesb6664582021-03-19 09:46:00 -0400879 while (this->removeDeadFunctions(program, usage)) {
880 // Removing dead functions may cause more functions to become unreferenced. Try again.
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400881 }
John Stilesb6664582021-03-19 09:46:00 -0400882 while (this->removeDeadLocalVariables(program, usage)) {
883 // Removing dead variables may cause more variables to become unreferenced. Try again.
884 }
John Stiles25be58e2021-05-20 14:38:40 -0400885 // Unreachable code can confuse some drivers, so it's worth removing. (skia:12012)
886 this->removeUnreachableCode(program, usage);
887
Brian Osman8c264792021-07-01 16:41:27 -0400888 this->removeDeadGlobalVariables(program, usage);
Ethan Nicholas00543112018-07-31 09:44:36 -0400889 }
John Stilesbb1505f2021-02-12 09:17:53 -0500890
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400891 if (this->errorCount() == 0) {
John Stilesbb1505f2021-02-12 09:17:53 -0500892 this->verifyStaticTests(program);
893 }
894
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400895 return this->errorCount() == 0;
Ethan Nicholas00543112018-07-31 09:44:36 -0400896}
897
Brian Osmanfb32ddf2019-06-18 10:14:20 -0400898#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
899
Ethan Nicholas00543112018-07-31 09:44:36 -0400900bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400901 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toSPIRV");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400902 AutoSource as(this, program.fSource->c_str());
Brian Salomond8d85b92021-07-07 09:41:17 -0400903 ProgramSettings settings;
904 settings.fDSLUseMemoryPool = false;
905 dsl::Start(this, program.fConfig->fKind, settings);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400906 dsl::SetErrorReporter(&fErrorReporter);
Brian Salomond8d85b92021-07-07 09:41:17 -0400907 dsl::DSLWriter::IRGenerator().fSymbolTable = program.fSymbols;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400908#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400909 StringStream buffer;
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400910 SPIRVCodeGenerator cg(fContext.get(), &program, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400911 bool result = cg.generateCode();
John Stiles270cec22021-02-17 12:59:36 -0500912 if (result && program.fConfig->fSettings.fValidateSPIRV) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400913 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400914 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400915 SkASSERT(0 == data.size() % 4);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500916 String errors;
917 auto dumpmsg = [&errors](spv_message_level_t, const char*, const spv_position_t&,
918 const char* m) {
919 errors.appendf("SPIR-V validation error: %s\n", m);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400920 };
921 tools.SetMessageConsumer(dumpmsg);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500922
923 // Verify that the SPIR-V we produced is valid. At runtime, we will abort() with a message
924 // explaining the error. In standalone mode (skslc), we will send the message, plus the
925 // entire disassembled SPIR-V (for easier context & debugging) as *our* error message.
926 result = tools.Validate((const uint32_t*) data.c_str(), data.size() / 4);
927
928 if (!result) {
929#if defined(SKSL_STANDALONE)
930 // Convert the string-stream to a SPIR-V disassembly.
931 std::string disassembly;
932 if (tools.Disassemble((const uint32_t*)data.data(), data.size() / 4, &disassembly)) {
933 errors.append(disassembly);
934 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400935 this->errorReporter().error(-1, errors);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500936#else
937 SkDEBUGFAILF("%s", errors.c_str());
938#endif
939 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400940 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400941 }
942#else
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400943 SPIRVCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500944 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400945#endif
Brian Salomond8d85b92021-07-07 09:41:17 -0400946 dsl::End();
Ethan Nicholasce33f102016-12-09 17:22:59 -0500947 return result;
948}
949
Ethan Nicholas00543112018-07-31 09:44:36 -0400950bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400951 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500952 bool result = this->toSPIRV(program, buffer);
953 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400954 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500955 }
956 return result;
957}
958
Ethan Nicholas00543112018-07-31 09:44:36 -0400959bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400960 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toGLSL");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400961 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400962 GLSLCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500963 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500964 return result;
965}
966
Ethan Nicholas00543112018-07-31 09:44:36 -0400967bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400968 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500969 bool result = this->toGLSL(program, buffer);
970 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400971 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500972 }
973 return result;
974}
975
Brian Osmanc0243912020-02-19 15:35:26 -0500976bool Compiler::toHLSL(Program& program, String* out) {
977 String spirv;
978 if (!this->toSPIRV(program, &spirv)) {
979 return false;
980 }
981
982 return SPIRVtoHLSL(spirv, out);
983}
984
Ethan Nicholas00543112018-07-31 09:44:36 -0400985bool Compiler::toMetal(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400986 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toMetal");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400987 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400988 MetalCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -0400989 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -0400990 return result;
991}
992
Ethan Nicholas00543112018-07-31 09:44:36 -0400993bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -0400994 StringStream buffer;
995 bool result = this->toMetal(program, buffer);
996 if (result) {
997 *out = buffer.str();
998 }
999 return result;
1000}
1001
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001002#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04001003
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -04001004void Compiler::handleError(const char* msg, PositionInfo pos) {
Ethan Nicholasb449fff2021-08-04 15:06:37 -04001005 if (strstr(msg, POISON_TAG)) {
Ethan Nicholas549c6b82021-06-25 12:31:44 -04001006 // don't report errors on poison values
1007 return;
1008 }
Ethan Nicholasa40ddcd2021-08-06 09:17:18 -04001009 fErrorText += "error: " + (pos.line() >= 1 ? to_string(pos.line()) + ": " : "") + msg + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001010}
1011
Ethan Nicholas95046142021-01-07 10:57:27 -05001012String Compiler::errorText(bool showCount) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -04001013 this->errorReporter().reportPendingErrors(PositionInfo());
Ethan Nicholas95046142021-01-07 10:57:27 -05001014 if (showCount) {
1015 this->writeErrorCount();
1016 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001017 String result = fErrorText;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -04001018 this->resetErrors();
ethannicholasb3058bd2016-07-01 08:22:01 -07001019 return result;
1020}
1021
1022void Compiler::writeErrorCount() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -04001023 int count = this->errorCount();
1024 if (count) {
1025 fErrorText += to_string(count) + " error";
1026 if (count > 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001027 fErrorText += "s";
1028 }
1029 fErrorText += "\n";
1030 }
1031}
1032
John Stilesa6841be2020-08-06 14:11:56 -04001033} // namespace SkSL