blob: de55721cbe1cf6f84d58a4af2c780b1dc2d53d1a [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
John Stilesb92641c2020-08-31 18:09:01 -040013#include "src/sksl/SkSLAnalysis.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050014#include "src/sksl/SkSLByteCodeGenerator.h"
15#include "src/sksl/SkSLCFGGenerator.h"
16#include "src/sksl/SkSLCPPCodeGenerator.h"
17#include "src/sksl/SkSLGLSLCodeGenerator.h"
18#include "src/sksl/SkSLHCodeGenerator.h"
19#include "src/sksl/SkSLIRGenerator.h"
20#include "src/sksl/SkSLMetalCodeGenerator.h"
21#include "src/sksl/SkSLPipelineStageCodeGenerator.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040022#include "src/sksl/SkSLRehydrator.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050023#include "src/sksl/SkSLSPIRVCodeGenerator.h"
Brian Osmanc0243912020-02-19 15:35:26 -050024#include "src/sksl/SkSLSPIRVtoHLSL.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/sksl/ir/SkSLEnum.h"
26#include "src/sksl/ir/SkSLExpression.h"
27#include "src/sksl/ir/SkSLExpressionStatement.h"
28#include "src/sksl/ir/SkSLFunctionCall.h"
29#include "src/sksl/ir/SkSLIntLiteral.h"
30#include "src/sksl/ir/SkSLModifiersDeclaration.h"
31#include "src/sksl/ir/SkSLNop.h"
32#include "src/sksl/ir/SkSLSymbolTable.h"
33#include "src/sksl/ir/SkSLTernaryExpression.h"
34#include "src/sksl/ir/SkSLUnresolvedFunction.h"
35#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stilese6150002020-10-05 12:03:53 -040036#include "src/utils/SkBitSet.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070037
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040038#include <fstream>
39
Ethan Nicholasa11035b2019-11-26 16:27:47 -050040#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
41#include "include/gpu/GrContextOptions.h"
42#include "src/gpu/GrShaderCaps.h"
43#endif
44
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040045#ifdef SK_ENABLE_SPIRV_VALIDATION
46#include "spirv-tools/libspirv.hpp"
47#endif
48
Brian Osman3d87e9f2020-10-08 11:50:22 -040049#if defined(SKSL_STANDALONE)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040050
Brian Osman3d87e9f2020-10-08 11:50:22 -040051// In standalone mode, we load the textual sksl source files. GN generates or copies these files
52// to the skslc executable directory. The "data" in this mode is just the filename.
53#define MODULE_DATA(name) MakeModulePath("sksl_" #name ".sksl")
54
55#else
56
57// At runtime, we load the dehydrated sksl data files. The data is a (pointer, size) pair.
Ethan Nicholasc18bb512020-07-28 14:46:53 -040058#include "src/sksl/generated/sksl_fp.dehydrated.sksl"
59#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
60#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
61#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
62#include "src/sksl/generated/sksl_interp.dehydrated.sksl"
63#include "src/sksl/generated/sksl_pipeline.dehydrated.sksl"
64#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
65
Brian Osman3d87e9f2020-10-08 11:50:22 -040066#define MODULE_DATA(name) MakeModuleData(SKSL_INCLUDE_sksl_##name,\
67 SKSL_INCLUDE_sksl_##name##_LENGTH)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040068
69#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040070
ethannicholasb3058bd2016-07-01 08:22:01 -070071namespace SkSL {
72
Brian Osman88cda172020-10-09 12:05:16 -040073class AutoSource {
74public:
75 AutoSource(Compiler* compiler, const String* source)
76 : fCompiler(compiler), fOldSource(fCompiler->fSource) {
77 fCompiler->fSource = source;
78 }
79
80 ~AutoSource() { fCompiler->fSource = fOldSource; }
81
82 Compiler* fCompiler;
83 const String* fOldSource;
84};
85
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040086Compiler::Compiler(Flags flags)
Brian Osman00a8b5b2020-10-02 09:06:04 -040087: fFlags(flags)
John Stiles810c8cf2020-08-26 19:46:27 -040088, fContext(std::make_shared<Context>())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040089, fErrorCount(0) {
John Stiles7c3515b2020-10-16 18:38:39 -040090 fRootSymbolTable = std::make_shared<SymbolTable>(this, /*builtin=*/true);
John Stiles4c412bc2020-10-13 11:19:41 -040091 fIRGenerator = std::make_unique<IRGenerator>(fContext.get(), &fInliner, *this);
Brian Osman88cda172020-10-09 12:05:16 -040092#define ADD_TYPE(t) fRootSymbolTable->addWithoutOwnership(fContext->f##t##_Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070093 ADD_TYPE(Void);
94 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040095 ADD_TYPE(Float2);
96 ADD_TYPE(Float3);
97 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040098 ADD_TYPE(Half);
99 ADD_TYPE(Half2);
100 ADD_TYPE(Half3);
101 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700102 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400103 ADD_TYPE(Int2);
104 ADD_TYPE(Int3);
105 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700106 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400107 ADD_TYPE(UInt2);
108 ADD_TYPE(UInt3);
109 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400110 ADD_TYPE(Short);
111 ADD_TYPE(Short2);
112 ADD_TYPE(Short3);
113 ADD_TYPE(Short4);
114 ADD_TYPE(UShort);
115 ADD_TYPE(UShort2);
116 ADD_TYPE(UShort3);
117 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400118 ADD_TYPE(Byte);
119 ADD_TYPE(Byte2);
120 ADD_TYPE(Byte3);
121 ADD_TYPE(Byte4);
122 ADD_TYPE(UByte);
123 ADD_TYPE(UByte2);
124 ADD_TYPE(UByte3);
125 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700126 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400127 ADD_TYPE(Bool2);
128 ADD_TYPE(Bool3);
129 ADD_TYPE(Bool4);
130 ADD_TYPE(Float2x2);
131 ADD_TYPE(Float2x3);
132 ADD_TYPE(Float2x4);
133 ADD_TYPE(Float3x2);
134 ADD_TYPE(Float3x3);
135 ADD_TYPE(Float3x4);
136 ADD_TYPE(Float4x2);
137 ADD_TYPE(Float4x3);
138 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400139 ADD_TYPE(Half2x2);
140 ADD_TYPE(Half2x3);
141 ADD_TYPE(Half2x4);
142 ADD_TYPE(Half3x2);
143 ADD_TYPE(Half3x3);
144 ADD_TYPE(Half3x4);
145 ADD_TYPE(Half4x2);
146 ADD_TYPE(Half4x3);
147 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700148 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400149 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700150 ADD_TYPE(GenIType);
151 ADD_TYPE(GenUType);
152 ADD_TYPE(GenBType);
153 ADD_TYPE(Mat);
154 ADD_TYPE(Vec);
155 ADD_TYPE(GVec);
156 ADD_TYPE(GVec2);
157 ADD_TYPE(GVec3);
158 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400159 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700160 ADD_TYPE(IVec);
161 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400162 ADD_TYPE(SVec);
163 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400164 ADD_TYPE(ByteVec);
165 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700166 ADD_TYPE(BVec);
167
168 ADD_TYPE(Sampler1D);
169 ADD_TYPE(Sampler2D);
170 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700171 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700172 ADD_TYPE(SamplerCube);
173 ADD_TYPE(Sampler2DRect);
174 ADD_TYPE(Sampler1DArray);
175 ADD_TYPE(Sampler2DArray);
176 ADD_TYPE(SamplerCubeArray);
177 ADD_TYPE(SamplerBuffer);
178 ADD_TYPE(Sampler2DMS);
179 ADD_TYPE(Sampler2DMSArray);
180
Brian Salomonbf7b6202016-11-11 16:08:03 -0500181 ADD_TYPE(ISampler2D);
182
Brian Salomon2a51de82016-11-16 12:06:01 -0500183 ADD_TYPE(Image2D);
184 ADD_TYPE(IImage2D);
185
Greg Daniel64773e62016-11-22 09:44:03 -0500186 ADD_TYPE(SubpassInput);
187 ADD_TYPE(SubpassInputMS);
188
ethannicholasb3058bd2016-07-01 08:22:01 -0700189 ADD_TYPE(GSampler1D);
190 ADD_TYPE(GSampler2D);
191 ADD_TYPE(GSampler3D);
192 ADD_TYPE(GSamplerCube);
193 ADD_TYPE(GSampler2DRect);
194 ADD_TYPE(GSampler1DArray);
195 ADD_TYPE(GSampler2DArray);
196 ADD_TYPE(GSamplerCubeArray);
197 ADD_TYPE(GSamplerBuffer);
198 ADD_TYPE(GSampler2DMS);
199 ADD_TYPE(GSampler2DMSArray);
200
201 ADD_TYPE(Sampler1DShadow);
202 ADD_TYPE(Sampler2DShadow);
203 ADD_TYPE(SamplerCubeShadow);
204 ADD_TYPE(Sampler2DRectShadow);
205 ADD_TYPE(Sampler1DArrayShadow);
206 ADD_TYPE(Sampler2DArrayShadow);
207 ADD_TYPE(SamplerCubeArrayShadow);
208 ADD_TYPE(GSampler2DArrayShadow);
209 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400210 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400211 ADD_TYPE(Sampler);
212 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700213
Brian Osman3887a012020-09-30 13:22:27 -0400214 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
215 // treat it as builtin (ie, no need to clone it into the Program).
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700216 StringFragment skCapsName("sk_Caps");
John Stilesb8cc6652020-10-08 09:12:07 -0400217 fRootSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400218 fIRGenerator->fModifiers->handle(Modifiers()),
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400219 skCapsName,
220 fContext->fSkCaps_Type.get(),
221 /*builtin=*/false,
222 Variable::Storage::kGlobal));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500223
Brian Osman3d87e9f2020-10-08 11:50:22 -0400224 fRootModule = {fRootSymbolTable, /*fIntrinsics=*/nullptr};
John Stilesbc0c29e2020-09-28 13:13:40 -0400225
Brian Osman3d87e9f2020-10-08 11:50:22 -0400226 fGPUModule = this->parseModule(Program::kFragment_Kind, MODULE_DATA(gpu), fRootModule);
227 fVertexModule = this->parseModule(Program::kVertex_Kind, MODULE_DATA(vert), fGPUModule);
228 fFragmentModule = this->parseModule(Program::kFragment_Kind, MODULE_DATA(frag), fGPUModule);
ethannicholasb3058bd2016-07-01 08:22:01 -0700229}
230
John Stiles656427a2020-08-27 15:26:26 -0400231Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700232
Brian Osman88cda172020-10-09 12:05:16 -0400233const ParsedModule& Compiler::loadGeometryModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400234 if (!fGeometryModule.fSymbols) {
235 fGeometryModule = this->parseModule(Program::kGeometry_Kind, MODULE_DATA(geom), fGPUModule);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400236 }
Brian Osman88cda172020-10-09 12:05:16 -0400237 return fGeometryModule;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400238}
239
Brian Osman88cda172020-10-09 12:05:16 -0400240const ParsedModule& Compiler::loadFPModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400241 if (!fFPModule.fSymbols) {
242 fFPModule =
243 this->parseModule(Program::kFragmentProcessor_Kind, MODULE_DATA(fp), fGPUModule);
Brian Osman8e2ef022020-09-30 13:26:43 -0400244 }
Brian Osman88cda172020-10-09 12:05:16 -0400245 return fFPModule;
Brian Osman8e2ef022020-09-30 13:26:43 -0400246}
247
Brian Osman88cda172020-10-09 12:05:16 -0400248const ParsedModule& Compiler::loadPipelineModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400249 if (!fPipelineModule.fSymbols) {
250 fPipelineModule =
251 this->parseModule(Program::kPipelineStage_Kind, MODULE_DATA(pipeline), fGPUModule);
Brian Osmanf1319c32020-10-13 09:34:23 -0400252
253 // Add some aliases to the pipeline module so that it's friendlier, and more like GLSL
254 fPipelineModule.fSymbols->addAlias("shader", fContext->fFragmentProcessor_Type.get());
255
256 fPipelineModule.fSymbols->addAlias("vec2", fContext->fFloat2_Type.get());
257 fPipelineModule.fSymbols->addAlias("vec3", fContext->fFloat3_Type.get());
258 fPipelineModule.fSymbols->addAlias("vec4", fContext->fFloat4_Type.get());
259
260 fPipelineModule.fSymbols->addAlias("bvec2", fContext->fBool2_Type.get());
261 fPipelineModule.fSymbols->addAlias("bvec3", fContext->fBool3_Type.get());
262 fPipelineModule.fSymbols->addAlias("bvec4", fContext->fBool4_Type.get());
263
264 fPipelineModule.fSymbols->addAlias("mat2", fContext->fFloat2x2_Type.get());
265 fPipelineModule.fSymbols->addAlias("mat3", fContext->fFloat3x3_Type.get());
266 fPipelineModule.fSymbols->addAlias("mat4", fContext->fFloat4x4_Type.get());
267
268 fPipelineModule.fSymbols->addAlias("mat2x2", fContext->fFloat2x2_Type.get());
269 fPipelineModule.fSymbols->addAlias("mat2x3", fContext->fFloat2x3_Type.get());
270 fPipelineModule.fSymbols->addAlias("mat2x4", fContext->fFloat2x4_Type.get());
271
272 fPipelineModule.fSymbols->addAlias("mat3x2", fContext->fFloat3x2_Type.get());
273 fPipelineModule.fSymbols->addAlias("mat3x3", fContext->fFloat3x3_Type.get());
274 fPipelineModule.fSymbols->addAlias("mat3x4", fContext->fFloat3x4_Type.get());
275
276 fPipelineModule.fSymbols->addAlias("mat4x2", fContext->fFloat4x2_Type.get());
277 fPipelineModule.fSymbols->addAlias("mat4x3", fContext->fFloat4x3_Type.get());
278 fPipelineModule.fSymbols->addAlias("mat4x4", fContext->fFloat4x4_Type.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400279 }
Brian Osman88cda172020-10-09 12:05:16 -0400280 return fPipelineModule;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400281}
282
Brian Osman88cda172020-10-09 12:05:16 -0400283const ParsedModule& Compiler::loadInterpreterModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400284 if (!fInterpreterModule.fSymbols) {
285 fInterpreterModule =
286 this->parseModule(Program::kGeneric_Kind, MODULE_DATA(interp), fRootModule);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400287 }
Brian Osman88cda172020-10-09 12:05:16 -0400288 return fInterpreterModule;
289}
290
291const ParsedModule& Compiler::moduleForProgramKind(Program::Kind kind) {
292 switch (kind) {
293 case Program::kVertex_Kind: return fVertexModule; break;
294 case Program::kFragment_Kind: return fFragmentModule; break;
295 case Program::kGeometry_Kind: return this->loadGeometryModule(); break;
296 case Program::kFragmentProcessor_Kind: return this->loadFPModule(); break;
297 case Program::kPipelineStage_Kind: return this->loadPipelineModule(); break;
298 case Program::kGeneric_Kind: return this->loadInterpreterModule(); break;
299 }
300 SkUNREACHABLE;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400301}
302
Brian Osman3d87e9f2020-10-08 11:50:22 -0400303LoadedModule Compiler::loadModule(Program::Kind kind,
304 ModuleData data,
305 std::shared_ptr<SymbolTable> base) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400306 if (!base) {
307 base = fRootSymbolTable;
308 }
309
310#if defined(SKSL_STANDALONE)
311 SkASSERT(data.fPath);
312 std::ifstream in(data.fPath);
Brian Osmane498b3c2020-09-23 14:42:11 -0400313 std::unique_ptr<String> text = std::make_unique<String>(std::istreambuf_iterator<char>(in),
314 std::istreambuf_iterator<char>());
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400315 if (in.rdstate()) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400316 printf("error reading %s\n", data.fPath);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400317 abort();
318 }
Brian Osmane498b3c2020-09-23 14:42:11 -0400319 const String* source = fRootSymbolTable->takeOwnershipOfString(std::move(text));
Brian Osman88cda172020-10-09 12:05:16 -0400320 AutoSource as(this, source);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400321 Program::Settings settings;
John Stiles881a10c2020-09-19 10:13:24 -0400322 SkASSERT(fIRGenerator->fCanInline);
323 fIRGenerator->fCanInline = false;
Brian Osman88cda172020-10-09 12:05:16 -0400324 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
325 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(
326 kind, &settings, baseModule, /*isBuiltinCode=*/true, source->c_str(), source->length(),
327 /*externalValues=*/nullptr);
328 LoadedModule module = { std::move(ir.fSymbolTable), std::move(ir.fElements) };
John Stiles881a10c2020-09-19 10:13:24 -0400329 fIRGenerator->fCanInline = true;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400330 if (this->fErrorCount) {
331 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400332 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400333 }
Brian Osman88cda172020-10-09 12:05:16 -0400334 fModifiers.push_back(std::move(ir.fModifiers));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400335#else
336 SkASSERT(data.fData && (data.fSize != 0));
337 Rehydrator rehydrator(fContext.get(), fIRGenerator->fModifiers.get(), base, this,
338 data.fData, data.fSize);
Brian Osman88cda172020-10-09 12:05:16 -0400339 LoadedModule module = { rehydrator.symbolTable(), rehydrator.elements() };
Brian Osman3d87e9f2020-10-08 11:50:22 -0400340 fModifiers.push_back(fIRGenerator->releaseModifiers());
341#endif
342
343 return module;
344}
345
346ParsedModule Compiler::parseModule(Program::Kind kind, ModuleData data, const ParsedModule& base) {
347 auto [symbols, elements] = this->loadModule(kind, data, base.fSymbols);
348
349 // For modules that just declare (but don't define) intrinsic functions, there will be no new
350 // program elements. In that case, we can share our parent's intrinsic map:
351 if (elements.empty()) {
352 return {symbols, base.fIntrinsics};
353 }
354
355 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
356
357 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
358 // global objects to the declaring ProgramElement.
359 for (std::unique_ptr<ProgramElement>& element : elements) {
360 switch (element->kind()) {
361 case ProgramElement::Kind::kFunction: {
362 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400363 SkASSERT(f.declaration().isBuiltin());
364 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400365 break;
366 }
367 case ProgramElement::Kind::kEnum: {
368 const Enum& e = element->as<Enum>();
369 SkASSERT(e.isBuiltin());
370 intrinsics->insertOrDie(e.typeName(), std::move(element));
371 break;
372 }
373 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400374 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
375 const Variable& var = global.declaration()->as<VarDeclaration>().var();
376 SkASSERT(var.isBuiltin());
377 intrinsics->insertOrDie(var.name(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400378 break;
379 }
380 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400381 const Variable& var = element->as<InterfaceBlock>().variable();
382 SkASSERT(var.isBuiltin());
383 intrinsics->insertOrDie(var.name(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400384 break;
385 }
386 default:
387 printf("Unsupported element: %s\n", element->description().c_str());
388 SkASSERT(false);
389 break;
390 }
391 }
392
393 return {symbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400394}
395
ethannicholas22f939e2016-10-13 13:25:34 -0700396// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500397void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
398 DefinitionMap* definitions) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400399 switch (lvalue->kind()) {
400 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -0400401 const Variable& var = *lvalue->as<VariableReference>().variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400402 if (var.storage() == Variable::Storage::kLocal) {
John Stiles796cdb72020-10-08 12:06:53 -0400403 definitions->set(&var, expr);
ethannicholas22f939e2016-10-13 13:25:34 -0700404 }
405 break;
406 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400407 case Expression::Kind::kSwizzle:
ethannicholas22f939e2016-10-13 13:25:34 -0700408 // We consider the variable written to as long as at least some of its components have
409 // been written to. This will lead to some false negatives (we won't catch it if you
410 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400411 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
412 // but since we pass foo as a whole it is flagged as an error) unless we perform a much
ethannicholas22f939e2016-10-13 13:25:34 -0700413 // more complicated whole-program analysis. This is probably good enough.
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400414 this->addDefinition(lvalue->as<Swizzle>().base().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400415 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700416 definitions);
417 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400418 case Expression::Kind::kIndex:
ethannicholas22f939e2016-10-13 13:25:34 -0700419 // see comments in Swizzle
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400420 this->addDefinition(lvalue->as<IndexExpression>().base().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400421 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700422 definitions);
423 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400424 case Expression::Kind::kFieldAccess:
ethannicholas22f939e2016-10-13 13:25:34 -0700425 // see comments in Swizzle
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400426 this->addDefinition(lvalue->as<FieldAccess>().base().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400427 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700428 definitions);
429 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400430 case Expression::Kind::kTernary:
Ethan Nicholasa583b812018-01-18 13:32:11 -0500431 // To simplify analysis, we just pretend that we write to both sides of the ternary.
432 // This allows for false positives (meaning we fail to detect that a variable might not
433 // have been assigned), but is preferable to false negatives.
Ethan Nicholasdd218162020-10-08 05:48:01 -0400434 this->addDefinition(lvalue->as<TernaryExpression>().ifTrue().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400435 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500436 definitions);
Ethan Nicholasdd218162020-10-08 05:48:01 -0400437 this->addDefinition(lvalue->as<TernaryExpression>().ifFalse().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400438 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500439 definitions);
440 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400441 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400442 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700443 default:
444 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400445 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700446 }
447}
448
449// add local variables defined by this node to the set
John Stiles796cdb72020-10-08 12:06:53 -0400450void Compiler::addDefinitions(const BasicBlock::Node& node, DefinitionMap* definitions) {
John Stiles70025e52020-09-28 16:08:58 -0400451 if (node.isExpression()) {
452 Expression* expr = node.expression()->get();
453 switch (expr->kind()) {
454 case Expression::Kind::kBinary: {
455 BinaryExpression* b = &expr->as<BinaryExpression>();
456 if (b->getOperator() == Token::Kind::TK_EQ) {
457 this->addDefinition(&b->left(), &b->rightPointer(), definitions);
458 } else if (Compiler::IsAssignment(b->getOperator())) {
459 this->addDefinition(
460 &b->left(),
461 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
462 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500463
ethannicholas22f939e2016-10-13 13:25:34 -0700464 }
John Stiles70025e52020-09-28 16:08:58 -0400465 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700466 }
John Stiles70025e52020-09-28 16:08:58 -0400467 case Expression::Kind::kFunctionCall: {
468 const FunctionCall& c = expr->as<FunctionCall>();
Brian Osman5bf3e202020-10-13 10:34:18 -0400469 const std::vector<const Variable*>& parameters = c.function().parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -0400470 for (size_t i = 0; i < parameters.size(); ++i) {
471 if (parameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles70025e52020-09-28 16:08:58 -0400472 this->addDefinition(
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400473 c.arguments()[i].get(),
John Stiles70025e52020-09-28 16:08:58 -0400474 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
475 definitions);
476 }
477 }
478 break;
479 }
480 case Expression::Kind::kPrefix: {
481 const PrefixExpression* p = &expr->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400482 if (p->getOperator() == Token::Kind::TK_MINUSMINUS ||
483 p->getOperator() == Token::Kind::TK_PLUSPLUS) {
John Stiles70025e52020-09-28 16:08:58 -0400484 this->addDefinition(
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400485 p->operand().get(),
John Stiles70025e52020-09-28 16:08:58 -0400486 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
487 definitions);
488 }
489 break;
490 }
491 case Expression::Kind::kPostfix: {
492 const PostfixExpression* p = &expr->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400493 if (p->getOperator() == Token::Kind::TK_MINUSMINUS ||
494 p->getOperator() == Token::Kind::TK_PLUSPLUS) {
John Stiles70025e52020-09-28 16:08:58 -0400495 this->addDefinition(
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400496 p->operand().get(),
John Stiles70025e52020-09-28 16:08:58 -0400497 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
498 definitions);
499 }
500 break;
501 }
502 case Expression::Kind::kVariableReference: {
503 const VariableReference* v = &expr->as<VariableReference>();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400504 if (v->refKind() != VariableReference::RefKind::kRead) {
John Stiles70025e52020-09-28 16:08:58 -0400505 this->addDefinition(
506 v,
507 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
508 definitions);
509 }
510 break;
511 }
512 default:
513 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700514 }
John Stiles70025e52020-09-28 16:08:58 -0400515 } else if (node.isStatement()) {
516 Statement* stmt = node.statement()->get();
517 if (stmt->is<VarDeclaration>()) {
518 VarDeclaration& vd = stmt->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400519 if (vd.value()) {
520 definitions->set(&vd.var(), &vd.value());
ethannicholas22f939e2016-10-13 13:25:34 -0700521 }
ethannicholas22f939e2016-10-13 13:25:34 -0700522 }
523 }
524}
525
John Stilese6150002020-10-05 12:03:53 -0400526void Compiler::scanCFG(CFG* cfg, BlockId blockId, SkBitSet* processedSet) {
ethannicholas22f939e2016-10-13 13:25:34 -0700527 BasicBlock& block = cfg->fBlocks[blockId];
528
529 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500530 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700531 for (const BasicBlock::Node& n : block.fNodes) {
532 this->addDefinitions(n, &after);
533 }
534
535 // propagate definitions to exits
536 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400537 if (exitId == blockId) {
538 continue;
539 }
ethannicholas22f939e2016-10-13 13:25:34 -0700540 BasicBlock& exit = cfg->fBlocks[exitId];
John Stiles796cdb72020-10-08 12:06:53 -0400541 after.foreach([&](const Variable* var, std::unique_ptr<Expression>** e1Ptr) {
542 std::unique_ptr<Expression>* e1 = *e1Ptr;
543 std::unique_ptr<Expression>** exitDef = exit.fBefore.find(var);
544 if (!exitDef) {
John Stilese6150002020-10-05 12:03:53 -0400545 // exit has no definition for it, just copy it and reprocess exit block
546 processedSet->reset(exitId);
John Stiles796cdb72020-10-08 12:06:53 -0400547 exit.fBefore[var] = e1;
ethannicholas22f939e2016-10-13 13:25:34 -0700548 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500549 // exit has a (possibly different) value already defined
John Stiles796cdb72020-10-08 12:06:53 -0400550 std::unique_ptr<Expression>* e2 = *exitDef;
ethannicholas22f939e2016-10-13 13:25:34 -0700551 if (e1 != e2) {
John Stilese6150002020-10-05 12:03:53 -0400552 // definition has changed, merge and reprocess the exit block
553 processedSet->reset(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500554 if (e1 && e2) {
John Stiles796cdb72020-10-08 12:06:53 -0400555 *exitDef = (std::unique_ptr<Expression>*)&fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500556 } else {
John Stiles796cdb72020-10-08 12:06:53 -0400557 *exitDef = nullptr;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500558 }
ethannicholas22f939e2016-10-13 13:25:34 -0700559 }
560 }
John Stiles796cdb72020-10-08 12:06:53 -0400561 });
ethannicholas22f939e2016-10-13 13:25:34 -0700562 }
563}
564
565// returns a map which maps all local variables in the function to null, indicating that their value
566// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500567static DefinitionMap compute_start_state(const CFG& cfg) {
568 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400569 for (const auto& block : cfg.fBlocks) {
570 for (const auto& node : block.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -0400571 if (node.isStatement()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400572 const Statement* s = node.statement()->get();
Brian Osmanc0213602020-10-06 14:43:32 -0400573 if (s->is<VarDeclaration>()) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400574 result[&s->as<VarDeclaration>().var()] = nullptr;
ethannicholas22f939e2016-10-13 13:25:34 -0700575 }
576 }
577 }
578 }
579 return result;
580}
581
Ethan Nicholascb670962017-04-20 19:31:52 -0400582/**
583 * Returns true if assigning to this lvalue has no effect.
584 */
585static bool is_dead(const Expression& lvalue) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400586 switch (lvalue.kind()) {
587 case Expression::Kind::kVariableReference:
Ethan Nicholas78686922020-10-08 06:46:27 -0400588 return lvalue.as<VariableReference>().variable()->dead();
Ethan Nicholase6592142020-09-08 10:22:09 -0400589 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400590 return is_dead(*lvalue.as<Swizzle>().base());
Ethan Nicholase6592142020-09-08 10:22:09 -0400591 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400592 return is_dead(*lvalue.as<FieldAccess>().base());
Ethan Nicholase6592142020-09-08 10:22:09 -0400593 case Expression::Kind::kIndex: {
John Stilesa5a97b42020-08-18 11:19:07 -0400594 const IndexExpression& idx = lvalue.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400595 return is_dead(*idx.base()) &&
596 !idx.index()->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400597 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400598 case Expression::Kind::kTernary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400599 const TernaryExpression& t = lvalue.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400600 return !t.test()->hasSideEffects() && is_dead(*t.ifTrue()) && is_dead(*t.ifFalse());
Ethan Nicholasa583b812018-01-18 13:32:11 -0500601 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400602 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400603 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400604 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500605#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400606 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500607#endif
608 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400609 }
610}
ethannicholas22f939e2016-10-13 13:25:34 -0700611
Ethan Nicholascb670962017-04-20 19:31:52 -0400612/**
613 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
614 * to a dead target and lack of side effects on the left hand side.
615 */
616static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400617 if (!Compiler::IsAssignment(b.getOperator())) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400618 return false;
619 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400620 return is_dead(b.left());
Ethan Nicholascb670962017-04-20 19:31:52 -0400621}
622
623void Compiler::computeDataFlow(CFG* cfg) {
624 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
John Stilese6150002020-10-05 12:03:53 -0400625
626 // We set bits in the "processed" set after a block has been scanned.
627 SkBitSet processedSet(cfg->fBlocks.size());
628 while (SkBitSet::OptionalIndex blockId = processedSet.findFirstUnset()) {
629 processedSet.set(*blockId);
630 this->scanCFG(cfg, *blockId, &processedSet);
ethannicholas22f939e2016-10-13 13:25:34 -0700631 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400632}
633
634/**
635 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
636 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
637 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
638 * need to be regenerated).
639 */
John Stilesafbf8992020-08-18 10:08:21 -0400640static bool try_replace_expression(BasicBlock* b,
641 std::vector<BasicBlock::Node>::iterator* iter,
642 std::unique_ptr<Expression>* newExpression) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400643 std::unique_ptr<Expression>* target = (*iter)->expression();
644 if (!b->tryRemoveExpression(iter)) {
645 *target = std::move(*newExpression);
646 return false;
647 }
648 *target = std::move(*newExpression);
649 return b->tryInsertExpression(iter, target);
650}
651
652/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400653 * Returns true if the expression is a constant numeric literal with the specified value, or a
654 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400655 */
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400656template <typename T = SKSL_FLOAT>
John Stiles9d944232020-08-19 09:56:49 -0400657static bool is_constant(const Expression& expr, T value) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400658 switch (expr.kind()) {
659 case Expression::Kind::kIntLiteral:
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400660 return expr.as<IntLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400661
Ethan Nicholase6592142020-09-08 10:22:09 -0400662 case Expression::Kind::kFloatLiteral:
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400663 return expr.as<FloatLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400664
Ethan Nicholase6592142020-09-08 10:22:09 -0400665 case Expression::Kind::kConstructor: {
John Stiles9d944232020-08-19 09:56:49 -0400666 const Constructor& constructor = expr.as<Constructor>();
667 if (constructor.isCompileTimeConstant()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400668 const Type& constructorType = constructor.type();
669 bool isFloat = constructorType.columns() > 1
670 ? constructorType.componentType().isFloat()
671 : constructorType.isFloat();
672 switch (constructorType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400673 case Type::TypeKind::kVector:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400674 for (int i = 0; i < constructorType.columns(); ++i) {
John Stiles9d944232020-08-19 09:56:49 -0400675 if (isFloat) {
676 if (constructor.getFVecComponent(i) != value) {
677 return false;
678 }
679 } else {
680 if (constructor.getIVecComponent(i) != value) {
681 return false;
682 }
683 }
Ethan Nicholasd188c182019-06-10 15:55:38 -0400684 }
John Stiles9d944232020-08-19 09:56:49 -0400685 return true;
686
Ethan Nicholase6592142020-09-08 10:22:09 -0400687 case Type::TypeKind::kScalar:
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400688 SkASSERT(constructor.arguments().size() == 1);
689 return is_constant<T>(*constructor.arguments()[0], value);
John Stiles9d944232020-08-19 09:56:49 -0400690
691 default:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400692 return false;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400693 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400694 }
695 return false;
696 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400697 default:
698 return false;
699 }
700}
701
702/**
703 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
704 * and CFG structures).
705 */
John Stilesafbf8992020-08-18 10:08:21 -0400706static void delete_left(BasicBlock* b,
707 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400708 Compiler::OptimizationContext* optimizationContext) {
709 optimizationContext->fUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400710 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400711 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400712 Expression& left = bin.left();
713 std::unique_ptr<Expression>& rightPointer = bin.rightPointer();
714 SkASSERT(!left.hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400715 bool result;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400716 if (bin.getOperator() == Token::Kind::TK_EQ) {
717 result = b->tryRemoveLValueBefore(iter, &left);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400718 } else {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400719 result = b->tryRemoveExpressionBefore(iter, &left);
Ethan Nicholascb670962017-04-20 19:31:52 -0400720 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400721 *target = std::move(rightPointer);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400722 if (!result) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400723 optimizationContext->fNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400724 return;
725 }
726 if (*iter == b->fNodes.begin()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400727 optimizationContext->fNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400728 return;
729 }
730 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400731 if (!(*iter)->isExpression() || (*iter)->expression() != &rightPointer) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400732 optimizationContext->fNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400733 return;
734 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400735 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400736 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400737}
738
739/**
740 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
741 * CFG structures).
742 */
John Stilesafbf8992020-08-18 10:08:21 -0400743static void delete_right(BasicBlock* b,
744 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400745 Compiler::OptimizationContext* optimizationContext) {
746 optimizationContext->fUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400747 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400748 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400749 std::unique_ptr<Expression>& leftPointer = bin.leftPointer();
750 Expression& right = bin.right();
751 SkASSERT(!right.hasSideEffects());
752 if (!b->tryRemoveExpressionBefore(iter, &right)) {
753 *target = std::move(leftPointer);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400754 optimizationContext->fNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400755 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400756 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400757 *target = std::move(leftPointer);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400758 if (*iter == b->fNodes.begin()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400759 optimizationContext->fNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400760 return;
761 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400762 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400763 if ((!(*iter)->isExpression() || (*iter)->expression() != &leftPointer)) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400764 optimizationContext->fNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400765 return;
766 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400767 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400768 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400769}
770
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400771/**
772 * Constructs the specified type using a single argument.
773 */
Ethan Nicholas30d30222020-09-11 12:27:26 -0400774static std::unique_ptr<Expression> construct(const Type* type, std::unique_ptr<Expression> v) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400775 ExpressionArray args;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400776 args.push_back(std::move(v));
Ethan Nicholase6592142020-09-08 10:22:09 -0400777 std::unique_ptr<Expression> result = std::make_unique<Constructor>(-1, type, std::move(args));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400778 return result;
779}
780
781/**
782 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
783 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
784 */
785static void vectorize(BasicBlock* b,
786 std::vector<BasicBlock::Node>::iterator* iter,
787 const Type& type,
788 std::unique_ptr<Expression>* otherExpression,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400789 Compiler::OptimizationContext* optimizationContext) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400790 SkASSERT((*(*iter)->expression())->kind() == Expression::Kind::kBinary);
791 SkASSERT(type.typeKind() == Type::TypeKind::kVector);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400792 SkASSERT((*otherExpression)->type().typeKind() == Type::TypeKind::kScalar);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400793 optimizationContext->fUpdated = true;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400794 std::unique_ptr<Expression>* target = (*iter)->expression();
795 if (!b->tryRemoveExpression(iter)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400796 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400797 optimizationContext->fNeedsRescan = true;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400798 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400799 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400800 if (!b->tryInsertExpression(iter, target)) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400801 optimizationContext->fNeedsRescan = true;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400802 }
803 }
804}
805
806/**
807 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
808 * left to yield vec<n>(x).
809 */
810static void vectorize_left(BasicBlock* b,
811 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400812 Compiler::OptimizationContext* optimizationContext) {
John Stilesa5a97b42020-08-18 11:19:07 -0400813 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400814 vectorize(b, iter, bin.right().type(), &bin.leftPointer(), optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400815}
816
817/**
818 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
819 * right to yield vec<n>(y).
820 */
821static void vectorize_right(BasicBlock* b,
822 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400823 Compiler::OptimizationContext* optimizationContext) {
John Stilesa5a97b42020-08-18 11:19:07 -0400824 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400825 vectorize(b, iter, bin.left().type(), &bin.rightPointer(), optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400826}
827
828// Mark that an expression which we were writing to is no longer being written to
John Stilesa5a97b42020-08-18 11:19:07 -0400829static void clear_write(Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400830 switch (expr.kind()) {
831 case Expression::Kind::kVariableReference: {
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400832 expr.as<VariableReference>().setRefKind(VariableReference::RefKind::kRead);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400833 break;
834 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400835 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400836 clear_write(*expr.as<FieldAccess>().base());
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400837 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400838 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400839 clear_write(*expr.as<Swizzle>().base());
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400840 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400841 case Expression::Kind::kIndex:
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400842 clear_write(*expr.as<IndexExpression>().base());
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400843 break;
844 default:
845 ABORT("shouldn't be writing to this kind of expression\n");
846 break;
847 }
848}
849
Ethan Nicholascb670962017-04-20 19:31:52 -0400850void Compiler::simplifyExpression(DefinitionMap& definitions,
851 BasicBlock& b,
852 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400853 OptimizationContext* optimizationContext) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400854 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400855 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400856 if ((*iter)->fConstantPropagation) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400857 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator,
858 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400859 if (optimized) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400860 optimizationContext->fUpdated = true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400861 optimized = fIRGenerator->coerce(std::move(optimized), expr->type());
Ethan Nicholas1d881522020-09-11 09:32:54 -0400862 SkASSERT(optimized);
Ethan Nicholascb670962017-04-20 19:31:52 -0400863 if (!try_replace_expression(&b, iter, &optimized)) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400864 optimizationContext->fNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400865 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400866 }
John Stiles70025e52020-09-28 16:08:58 -0400867 SkASSERT((*iter)->isExpression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400868 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400869 }
870 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400871 switch (expr->kind()) {
872 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400873 const VariableReference& ref = expr->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400874 const Variable* var = ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400875 if (ref.refKind() != VariableReference::RefKind::kWrite &&
876 ref.refKind() != VariableReference::RefKind::kPointer &&
877 var->storage() == Variable::Storage::kLocal && !definitions[var] &&
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400878 optimizationContext->fSilences.find(var) == optimizationContext->fSilences.end()) {
879 optimizationContext->fSilences.insert(var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000880 this->error(expr->fOffset,
Ethan Nicholase2c49992020-10-05 11:49:11 -0400881 "'" + var->name() + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400882 }
883 break;
884 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400885 case Expression::Kind::kTernary: {
John Stiles403a3632020-08-20 12:11:48 -0400886 TernaryExpression* t = &expr->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400887 if (t->test()->is<BoolLiteral>()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400888 // ternary has a constant test, replace it with either the true or
889 // false branch
Ethan Nicholasdd218162020-10-08 05:48:01 -0400890 if (t->test()->as<BoolLiteral>().value()) {
891 (*iter)->setExpression(std::move(t->ifTrue()));
Ethan Nicholascb670962017-04-20 19:31:52 -0400892 } else {
Ethan Nicholasdd218162020-10-08 05:48:01 -0400893 (*iter)->setExpression(std::move(t->ifFalse()));
Ethan Nicholascb670962017-04-20 19:31:52 -0400894 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400895 optimizationContext->fUpdated = true;
896 optimizationContext->fNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400897 }
898 break;
899 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400900 case Expression::Kind::kBinary: {
John Stiles403a3632020-08-20 12:11:48 -0400901 BinaryExpression* bin = &expr->as<BinaryExpression>();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400902 if (dead_assignment(*bin)) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400903 delete_left(&b, iter, optimizationContext);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400904 break;
905 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400906 Expression& left = bin->left();
907 Expression& right = bin->right();
908 const Type& leftType = left.type();
909 const Type& rightType = right.type();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400910 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholas30d30222020-09-11 12:27:26 -0400911 if (((leftType.typeKind() != Type::TypeKind::kScalar) &&
912 (leftType.typeKind() != Type::TypeKind::kVector)) ||
913 ((rightType.typeKind() != Type::TypeKind::kScalar) &&
914 (rightType.typeKind() != Type::TypeKind::kVector))) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400915 break;
916 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400917 switch (bin->getOperator()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400918 case Token::Kind::TK_STAR:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400919 if (is_constant(left, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400920 if (leftType.typeKind() == Type::TypeKind::kVector &&
921 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400922 // float4(1) * x -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400923 vectorize_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400924 } else {
925 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400926 // 1 * float4(x) -> float4(x)
927 // float4(1) * float4(x) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400928 delete_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400929 }
930 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400931 else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400932 if (leftType.typeKind() == Type::TypeKind::kScalar &&
933 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400934 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400935 // 0 * float4(x) -> float4(0)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400936 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400937 } else {
938 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400939 // float4(0) * x -> float4(0)
940 // float4(0) * float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400941 if (!right.hasSideEffects()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400942 delete_right(&b, iter, optimizationContext);
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500943 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400944 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400945 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400946 else if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400947 if (leftType.typeKind() == Type::TypeKind::kScalar &&
948 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400949 // x * float4(1) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400950 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400951 } else {
952 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400953 // float4(x) * 1 -> float4(x)
954 // float4(x) * float4(1) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400955 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400956 }
957 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400958 else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400959 if (leftType.typeKind() == Type::TypeKind::kVector &&
960 rightType.typeKind() == Type::TypeKind::kScalar &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400961 !left.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400962 // float4(x) * 0 -> float4(0)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400963 vectorize_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400964 } else {
965 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400966 // x * float4(0) -> float4(0)
967 // float4(x) * float4(0) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400968 if (!left.hasSideEffects()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400969 delete_left(&b, iter, optimizationContext);
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500970 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400971 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400972 }
973 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400974 case Token::Kind::TK_PLUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400975 if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400976 if (leftType.typeKind() == Type::TypeKind::kVector &&
977 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400978 // float4(0) + x -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400979 vectorize_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400980 } else {
981 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400982 // 0 + float4(x) -> float4(x)
983 // float4(0) + float4(x) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400984 delete_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400985 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400986 } else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400987 if (leftType.typeKind() == Type::TypeKind::kScalar &&
988 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400989 // x + float4(0) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400990 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400991 } else {
992 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400993 // float4(x) + 0 -> float4(x)
994 // float4(x) + float4(0) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400995 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400996 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400997 }
998 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400999 case Token::Kind::TK_MINUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001000 if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001001 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1002 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001003 // x - float4(0) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001004 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001005 } else {
1006 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001007 // float4(x) - 0 -> float4(x)
1008 // float4(x) - float4(0) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001009 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001010 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001011 }
1012 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001013 case Token::Kind::TK_SLASH:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001014 if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001015 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1016 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001017 // x / float4(1) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001018 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001019 } else {
1020 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001021 // float4(x) / 1 -> float4(x)
1022 // float4(x) / float4(1) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001023 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001024 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001025 } else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001026 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1027 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001028 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001029 // 0 / float4(x) -> float4(0)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001030 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001031 } else {
1032 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001033 // float4(0) / x -> float4(0)
1034 // float4(0) / float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001035 if (!right.hasSideEffects()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001036 delete_right(&b, iter, optimizationContext);
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001037 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001038 }
1039 }
1040 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001041 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001042 if (is_constant(right, 0)) {
1043 clear_write(left);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001044 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001045 }
1046 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001047 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001048 if (is_constant(right, 0)) {
1049 clear_write(left);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001050 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001051 }
1052 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001053 case Token::Kind::TK_STAREQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001054 if (is_constant(right, 1)) {
1055 clear_write(left);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001056 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001057 }
1058 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001059 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001060 if (is_constant(right, 1)) {
1061 clear_write(left);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001062 delete_right(&b, iter, optimizationContext);
Ethan Nicholascb670962017-04-20 19:31:52 -04001063 }
1064 break;
1065 default:
1066 break;
1067 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001068 break;
1069 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001070 case Expression::Kind::kSwizzle: {
John Stiles403a3632020-08-20 12:11:48 -04001071 Swizzle& s = expr->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001072 // detect identity swizzles like foo.rgba
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001073 if ((int) s.components().size() == s.base()->type().columns()) {
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001074 bool identity = true;
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001075 for (int i = 0; i < (int) s.components().size(); ++i) {
1076 if (s.components()[i] != i) {
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001077 identity = false;
1078 break;
1079 }
1080 }
1081 if (identity) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001082 optimizationContext->fUpdated = true;
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001083 if (!try_replace_expression(&b, iter, &s.base())) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001084 optimizationContext->fNeedsRescan = true;
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001085 return;
1086 }
John Stiles70025e52020-09-28 16:08:58 -04001087 SkASSERT((*iter)->isExpression());
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001088 break;
1089 }
1090 }
1091 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001092 if (s.base()->kind() == Expression::Kind::kSwizzle) {
1093 Swizzle& base = s.base()->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001094 std::vector<int> final;
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001095 for (int c : s.components()) {
1096 final.push_back(base.components()[c]);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001097 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001098 optimizationContext->fUpdated = true;
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001099 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.base()->clone(),
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001100 std::move(final)));
1101 if (!try_replace_expression(&b, iter, &replacement)) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001102 optimizationContext->fNeedsRescan = true;
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001103 return;
1104 }
John Stiles70025e52020-09-28 16:08:58 -04001105 SkASSERT((*iter)->isExpression());
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001106 }
John Stiles30212b72020-06-11 17:55:07 -04001107 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001108 }
1109 default:
1110 break;
1111 }
1112}
1113
John Stiles92219b42020-06-15 12:32:24 -04001114// Returns true if this statement could potentially execute a break at the current level. We ignore
1115// nested loops and switches, since any breaks inside of them will merely break the loop / switch.
John Stilesb92641c2020-08-31 18:09:01 -04001116static bool contains_conditional_break(Statement& stmt) {
1117 class ContainsConditionalBreak : public ProgramVisitor {
1118 public:
1119 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001120 switch (stmt.kind()) {
1121 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001122 return this->INHERITED::visitStatement(stmt);
1123
Ethan Nicholase6592142020-09-08 10:22:09 -04001124 case Statement::Kind::kBreak:
John Stilesb92641c2020-08-31 18:09:01 -04001125 return fInConditional > 0;
1126
Ethan Nicholase6592142020-09-08 10:22:09 -04001127 case Statement::Kind::kIf: {
John Stilesb92641c2020-08-31 18:09:01 -04001128 ++fInConditional;
1129 bool result = this->INHERITED::visitStatement(stmt);
1130 --fInConditional;
1131 return result;
1132 }
1133
1134 default:
1135 return false;
1136 }
1137 }
1138
1139 int fInConditional = 0;
1140 using INHERITED = ProgramVisitor;
1141 };
1142
1143 return ContainsConditionalBreak{}.visitStatement(stmt);
John Stiles92219b42020-06-15 12:32:24 -04001144}
1145
Ethan Nicholas5005a222018-08-24 13:06:27 -04001146// returns true if this statement definitely executes a break at the current level (we ignore
1147// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
John Stilesb92641c2020-08-31 18:09:01 -04001148static bool contains_unconditional_break(Statement& stmt) {
1149 class ContainsUnconditionalBreak : public ProgramVisitor {
1150 public:
1151 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001152 switch (stmt.kind()) {
1153 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001154 return this->INHERITED::visitStatement(stmt);
1155
Ethan Nicholase6592142020-09-08 10:22:09 -04001156 case Statement::Kind::kBreak:
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001157 return true;
John Stilesb92641c2020-08-31 18:09:01 -04001158
1159 default:
1160 return false;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001161 }
John Stilesb92641c2020-08-31 18:09:01 -04001162 }
John Stiles92219b42020-06-15 12:32:24 -04001163
John Stilesb92641c2020-08-31 18:09:01 -04001164 using INHERITED = ProgramVisitor;
1165 };
John Stiles92219b42020-06-15 12:32:24 -04001166
John Stilesb92641c2020-08-31 18:09:01 -04001167 return ContainsUnconditionalBreak{}.visitStatement(stmt);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001168}
1169
John Stiles8f2a0cf2020-10-13 12:48:21 -04001170static void move_all_but_break(std::unique_ptr<Statement>& stmt, StatementArray* target) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001171 switch (stmt->kind()) {
1172 case Statement::Kind::kBlock: {
John Stiles92219b42020-06-15 12:32:24 -04001173 // Recurse into the block.
1174 Block& block = static_cast<Block&>(*stmt);
1175
John Stiles8f2a0cf2020-10-13 12:48:21 -04001176 StatementArray blockStmts;
John Stilesf4bda742020-10-14 16:57:41 -04001177 blockStmts.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001178 for (std::unique_ptr<Statement>& stmt : block.children()) {
1179 move_all_but_break(stmt, &blockStmts);
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001180 }
John Stiles92219b42020-06-15 12:32:24 -04001181
1182 target->push_back(std::make_unique<Block>(block.fOffset, std::move(blockStmts),
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001183 block.symbolTable(), block.isScope()));
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001184 break;
John Stiles92219b42020-06-15 12:32:24 -04001185 }
1186
Ethan Nicholase6592142020-09-08 10:22:09 -04001187 case Statement::Kind::kBreak:
John Stiles92219b42020-06-15 12:32:24 -04001188 // Do not append a break to the target.
1189 break;
1190
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001191 default:
John Stiles92219b42020-06-15 12:32:24 -04001192 // Append normal statements to the target.
1193 target->push_back(std::move(stmt));
1194 break;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001195 }
1196}
1197
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001198// Returns a block containing all of the statements that will be run if the given case matches
1199// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1200// broken by this call and must then be discarded).
1201// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1202// when break statements appear inside conditionals.
John Stiles92219b42020-06-15 12:32:24 -04001203static std::unique_ptr<Statement> block_for_case(SwitchStatement* switchStatement,
1204 SwitchCase* caseToCapture) {
1205 // We have to be careful to not move any of the pointers until after we're sure we're going to
1206 // succeed, so before we make any changes at all, we check the switch-cases to decide on a plan
1207 // of action. First, find the switch-case we are interested in.
1208 auto iter = switchStatement->fCases.begin();
1209 for (; iter != switchStatement->fCases.end(); ++iter) {
1210 if (iter->get() == caseToCapture) {
1211 break;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001212 }
John Stiles92219b42020-06-15 12:32:24 -04001213 }
1214
1215 // Next, walk forward through the rest of the switch. If we find a conditional break, we're
1216 // stuck and can't simplify at all. If we find an unconditional break, we have a range of
1217 // statements that we can use for simplification.
1218 auto startIter = iter;
1219 Statement* unconditionalBreakStmt = nullptr;
1220 for (; iter != switchStatement->fCases.end(); ++iter) {
1221 for (std::unique_ptr<Statement>& stmt : (*iter)->fStatements) {
1222 if (contains_conditional_break(*stmt)) {
1223 // We can't reduce switch-cases to a block when they have conditional breaks.
1224 return nullptr;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001225 }
John Stiles92219b42020-06-15 12:32:24 -04001226
1227 if (contains_unconditional_break(*stmt)) {
1228 // We found an unconditional break. We can use this block, but we need to strip
1229 // out the break statement.
1230 unconditionalBreakStmt = stmt.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001231 break;
1232 }
1233 }
John Stiles92219b42020-06-15 12:32:24 -04001234
1235 if (unconditionalBreakStmt != nullptr) {
1236 break;
1237 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001238 }
John Stiles92219b42020-06-15 12:32:24 -04001239
1240 // We fell off the bottom of the switch or encountered a break. We know the range of statements
1241 // that we need to move over, and we know it's safe to do so.
John Stiles8f2a0cf2020-10-13 12:48:21 -04001242 StatementArray caseStmts;
John Stiles92219b42020-06-15 12:32:24 -04001243
1244 // We can move over most of the statements as-is.
1245 while (startIter != iter) {
1246 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1247 caseStmts.push_back(std::move(stmt));
1248 }
1249 ++startIter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001250 }
John Stiles92219b42020-06-15 12:32:24 -04001251
1252 // If we found an unconditional break at the end, we need to move what we can while avoiding
1253 // that break.
1254 if (unconditionalBreakStmt != nullptr) {
1255 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1256 if (stmt.get() == unconditionalBreakStmt) {
1257 move_all_but_break(stmt, &caseStmts);
1258 unconditionalBreakStmt = nullptr;
1259 break;
1260 }
1261
1262 caseStmts.push_back(std::move(stmt));
1263 }
1264 }
1265
1266 SkASSERT(unconditionalBreakStmt == nullptr); // Verify that we fixed the unconditional break.
1267
1268 // Return our newly-synthesized block.
1269 return std::make_unique<Block>(/*offset=*/-1, std::move(caseStmts), switchStatement->fSymbols);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001270}
1271
Ethan Nicholascb670962017-04-20 19:31:52 -04001272void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001273 BasicBlock& b,
1274 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001275 OptimizationContext* optimizationContext) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001276 Statement* stmt = (*iter)->statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -04001277 switch (stmt->kind()) {
1278 case Statement::Kind::kVarDeclaration: {
John Stilesa5a97b42020-08-18 11:19:07 -04001279 const auto& varDecl = stmt->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001280 if (varDecl.var().dead() &&
1281 (!varDecl.value() ||
1282 !varDecl.value()->hasSideEffects())) {
1283 if (varDecl.value()) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001284 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001285 if (!b.tryRemoveExpressionBefore(iter, varDecl.value().get())) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001286 optimizationContext->fNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001287 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001288 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001289 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001290 optimizationContext->fUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001291 }
1292 break;
1293 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001294 case Statement::Kind::kIf: {
John Stilesa5a97b42020-08-18 11:19:07 -04001295 IfStatement& i = stmt->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001296 if (i.test()->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001297 // constant if, collapse down to a single branch
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001298 if (i.test()->as<BoolLiteral>().value()) {
1299 SkASSERT(i.ifTrue());
1300 (*iter)->setStatement(std::move(i.ifTrue()));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001301 } else {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001302 if (i.ifFalse()) {
1303 (*iter)->setStatement(std::move(i.ifFalse()));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001304 } else {
1305 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1306 }
1307 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001308 optimizationContext->fUpdated = true;
1309 optimizationContext->fNeedsRescan = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001310 break;
1311 }
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001312 if (i.ifFalse() && i.ifFalse()->isEmpty()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001313 // else block doesn't do anything, remove it
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001314 i.ifFalse().reset();
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001315 optimizationContext->fUpdated = true;
1316 optimizationContext->fNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001317 }
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001318 if (!i.ifFalse() && i.ifTrue()->isEmpty()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001319 // if block doesn't do anything, no else block
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001320 if (i.test()->hasSideEffects()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001321 // test has side effects, keep it
1322 (*iter)->setStatement(std::unique_ptr<Statement>(
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001323 new ExpressionStatement(std::move(i.test()))));
Ethan Nicholascb670962017-04-20 19:31:52 -04001324 } else {
1325 // no if, no else, no test side effects, kill the whole if
1326 // statement
1327 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1328 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001329 optimizationContext->fUpdated = true;
1330 optimizationContext->fNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001331 }
1332 break;
1333 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001334 case Statement::Kind::kSwitch: {
John Stilesa5a97b42020-08-18 11:19:07 -04001335 SwitchStatement& s = stmt->as<SwitchStatement>();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001336 int64_t switchValue;
1337 if (fIRGenerator->getConstantInt(*s.fValue, &switchValue)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001338 // switch is constant, replace it with the case that matches
1339 bool found = false;
1340 SwitchCase* defaultCase = nullptr;
John Stiles9d944232020-08-19 09:56:49 -04001341 for (const std::unique_ptr<SwitchCase>& c : s.fCases) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001342 if (!c->fValue) {
1343 defaultCase = c.get();
1344 continue;
1345 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001346 int64_t caseValue;
1347 SkAssertResult(fIRGenerator->getConstantInt(*c->fValue, &caseValue));
1348 if (caseValue == switchValue) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001349 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1350 if (newBlock) {
1351 (*iter)->setStatement(std::move(newBlock));
John Stiles9d944232020-08-19 09:56:49 -04001352 found = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001353 break;
1354 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001355 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001356 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001357 "static switch contains non-static conditional break");
1358 s.fIsStatic = false;
1359 }
1360 return; // can't simplify
1361 }
1362 }
1363 }
1364 if (!found) {
1365 // no matching case. use default if it exists, or kill the whole thing
1366 if (defaultCase) {
1367 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1368 if (newBlock) {
1369 (*iter)->setStatement(std::move(newBlock));
1370 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001371 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001372 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001373 "static switch contains non-static conditional break");
1374 s.fIsStatic = false;
1375 }
1376 return; // can't simplify
1377 }
1378 } else {
1379 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1380 }
1381 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001382 optimizationContext->fUpdated = true;
1383 optimizationContext->fNeedsRescan = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001384 }
1385 break;
1386 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001387 case Statement::Kind::kExpression: {
John Stilesa5a97b42020-08-18 11:19:07 -04001388 ExpressionStatement& e = stmt->as<ExpressionStatement>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001389 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001390 if (!e.expression()->hasSideEffects()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001391 // Expression statement with no side effects, kill it
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001392 if (!b.tryRemoveExpressionBefore(iter, e.expression().get())) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001393 optimizationContext->fNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001394 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001395 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001396 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001397 optimizationContext->fUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001398 }
1399 break;
1400 }
1401 default:
1402 break;
1403 }
1404}
1405
John Stiles0cc193a2020-09-09 09:39:34 -04001406bool Compiler::scanCFG(FunctionDefinition& f) {
1407 bool madeChanges = false;
1408
Ethan Nicholascb670962017-04-20 19:31:52 -04001409 CFG cfg = CFGGenerator().getCFG(f);
1410 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001411
1412 // check for unreachable code
1413 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
John Stiles0cc193a2020-09-09 09:39:34 -04001414 const BasicBlock& block = cfg.fBlocks[i];
John Stiles61e75e32020-10-01 15:42:37 -04001415 if (i != cfg.fStart && !block.fIsReachable && block.fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001416 int offset;
John Stiles0cc193a2020-09-09 09:39:34 -04001417 const BasicBlock::Node& node = block.fNodes[0];
John Stiles70025e52020-09-28 16:08:58 -04001418 if (node.isStatement()) {
1419 offset = (*node.statement())->fOffset;
1420 } else {
1421 offset = (*node.expression())->fOffset;
1422 if ((*node.expression())->is<BoolLiteral>()) {
1423 // Function inlining can generate do { ... } while(false) loops which always
1424 // break, so the boolean condition is considered unreachable. Since not being
1425 // able to reach a literal is a non-issue in the first place, we don't report an
1426 // error in this case.
1427 continue;
1428 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001429 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001430 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001431 }
1432 }
1433 if (fErrorCount) {
John Stiles0cc193a2020-09-09 09:39:34 -04001434 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001435 }
1436
Ethan Nicholascb670962017-04-20 19:31:52 -04001437 // check for dead code & undefined variables, perform constant propagation
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001438 OptimizationContext optimizationContext;
Ethan Nicholascb670962017-04-20 19:31:52 -04001439 do {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001440 if (optimizationContext.fNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001441 cfg = CFGGenerator().getCFG(f);
1442 this->computeDataFlow(&cfg);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001443 optimizationContext.fNeedsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001444 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001445
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001446 optimizationContext.fUpdated = false;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001447 bool first = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001448 for (BasicBlock& b : cfg.fBlocks) {
John Stiles61e75e32020-10-01 15:42:37 -04001449 if (!first && !b.fIsReachable) {
Ethan Nicholas1de14812020-06-19 15:32:49 -04001450 // Block was reachable before optimization, but has since become unreachable. In
1451 // addition to being dead code, it's broken - since control flow can't reach it, no
1452 // prior variable definitions can reach it, and therefore variables might look to
Brian Osmanc0213602020-10-06 14:43:32 -04001453 // have not been properly assigned. Kill it by replacing all statements with Nops.
Ethan Nicholas1de14812020-06-19 15:32:49 -04001454 for (BasicBlock::Node& node : b.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -04001455 if (node.isStatement() && !(*node.statement())->is<Nop>()) {
John Stiles0cc193a2020-09-09 09:39:34 -04001456 node.setStatement(std::make_unique<Nop>());
1457 madeChanges = true;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001458 }
1459 }
1460 continue;
1461 }
1462 first = false;
Ethan Nicholascb670962017-04-20 19:31:52 -04001463 DefinitionMap definitions = b.fBefore;
1464
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001465 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() &&
1466 !optimizationContext.fNeedsRescan; ++iter) {
John Stiles70025e52020-09-28 16:08:58 -04001467 if (iter->isExpression()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001468 this->simplifyExpression(definitions, b, &iter, &optimizationContext);
Ethan Nicholascb670962017-04-20 19:31:52 -04001469 } else {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001470 this->simplifyStatement(definitions, b, &iter, &optimizationContext);
Ethan Nicholascb670962017-04-20 19:31:52 -04001471 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001472 if (optimizationContext.fNeedsRescan) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001473 break;
1474 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001475 this->addDefinitions(*iter, &definitions);
1476 }
Brian Osman01a3eb42020-09-14 11:32:49 -04001477
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001478 if (optimizationContext.fNeedsRescan) {
Brian Osman01a3eb42020-09-14 11:32:49 -04001479 break;
1480 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001481 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001482 madeChanges |= optimizationContext.fUpdated;
1483 } while (optimizationContext.fUpdated);
1484 SkASSERT(!optimizationContext.fNeedsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001485
Ethan Nicholas91a10532017-06-22 11:24:38 -04001486 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001487 for (BasicBlock& b : cfg.fBlocks) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001488 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() &&
1489 !optimizationContext.fNeedsRescan;) {
John Stiles70025e52020-09-28 16:08:58 -04001490 if (iter->isStatement()) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001491 const Statement& s = **iter->statement();
Ethan Nicholase6592142020-09-08 10:22:09 -04001492 switch (s.kind()) {
1493 case Statement::Kind::kIf:
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001494 if (s.as<IfStatement>().isStatic() &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001495 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001496 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001497 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001498 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001499 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001500 case Statement::Kind::kSwitch:
John Stilesa5a97b42020-08-18 11:19:07 -04001501 if (s.as<SwitchStatement>().fIsStatic &&
John Stiles0cc193a2020-09-09 09:39:34 -04001502 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001503 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001504 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001505 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001506 break;
1507 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001508 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001509 break;
1510 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001511 } else {
1512 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001513 }
1514 }
1515 }
1516
ethannicholas22f939e2016-10-13 13:25:34 -07001517 // check for missing return
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001518 if (f.declaration().returnType() != *fContext->fVoid_Type) {
John Stiles61e75e32020-10-01 15:42:37 -04001519 if (cfg.fBlocks[cfg.fExit].fIsReachable) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001520 this->error(f.fOffset, String("function '" + String(f.declaration().name()) +
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001521 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001522 }
1523 }
John Stiles0cc193a2020-09-09 09:39:34 -04001524
1525 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001526}
1527
Brian Osman32d53552020-09-23 13:55:20 -04001528std::unique_ptr<Program> Compiler::convertProgram(
1529 Program::Kind kind,
1530 String text,
1531 const Program::Settings& settings,
1532 const std::vector<std::unique_ptr<ExternalValue>>* externalValues) {
1533 SkASSERT(!externalValues || (kind == Program::kGeneric_Kind));
Ethan Nicholas91164d12019-05-15 15:29:54 -04001534
ethannicholasb3058bd2016-07-01 08:22:01 -07001535 fErrorText = "";
1536 fErrorCount = 0;
Brian Osman3d87e9f2020-10-08 11:50:22 -04001537 fInliner.reset(fContext.get(), fIRGenerator->fModifiers.get(), &settings);
Brian Osman88cda172020-10-09 12:05:16 -04001538
1539 // Not using AutoSource, because caller is likely to call errorText() if we fail to compile
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001540 std::unique_ptr<String> textPtr(new String(std::move(text)));
1541 fSource = textPtr.get();
Brian Osman88cda172020-10-09 12:05:16 -04001542
1543 const ParsedModule& baseModule = this->moduleForProgramKind(kind);
1544
John Stiles5c7bb322020-10-22 11:09:15 -04001545 // Enable node pooling while converting and optimizing the program for a performance boost.
1546 // The Program will take ownership of the pool.
1547 std::unique_ptr<Pool> pool = Pool::CreatePoolOnThread(2000);
Brian Osman88cda172020-10-09 12:05:16 -04001548 IRGenerator::IRBundle ir =
1549 fIRGenerator->convertProgram(kind, &settings, baseModule, /*isBuiltinCode=*/false,
1550 textPtr->c_str(), textPtr->size(), externalValues);
John Stiles5c7bb322020-10-22 11:09:15 -04001551 auto program = std::make_unique<Program>(kind,
1552 std::move(textPtr),
1553 settings,
1554 fContext,
1555 std::move(ir.fElements),
1556 std::move(ir.fModifiers),
1557 std::move(ir.fSymbolTable),
1558 std::move(pool),
1559 ir.fInputs);
1560 bool success = false;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001561 if (fErrorCount) {
John Stiles5c7bb322020-10-22 11:09:15 -04001562 // Do not return programs that failed to compile.
1563 } else if (settings.fOptimize && !this->optimize(*program)) {
1564 // Do not return programs that failed to optimize.
1565 } else {
1566 // We have a successful program!
1567 success = true;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001568 }
John Stiles5c7bb322020-10-22 11:09:15 -04001569
1570 program->fPool->detachFromThread();
1571 return success ? std::move(program) : nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001572}
1573
Ethan Nicholas00543112018-07-31 09:44:36 -04001574bool Compiler::optimize(Program& program) {
1575 SkASSERT(!fErrorCount);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001576 fIRGenerator->fKind = program.fKind;
1577 fIRGenerator->fSettings = &program.fSettings;
John Stiles7954d6c2020-09-01 10:53:02 -04001578
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001579 while (fErrorCount == 0) {
1580 bool madeChanges = false;
John Stiles7954d6c2020-09-01 10:53:02 -04001581
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001582 // Scan and optimize based on the control-flow graph for each function.
Brian Osman1179fcf2020-10-08 16:04:40 -04001583 for (const auto& element : program.elements()) {
1584 if (element->is<FunctionDefinition>()) {
1585 madeChanges |= this->scanCFG(element->as<FunctionDefinition>());
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001586 }
1587 }
1588
1589 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles881a10c2020-09-19 10:13:24 -04001590 madeChanges |= fInliner.analyze(program);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001591
1592 // Remove dead functions. We wait until after analysis so that we still report errors,
1593 // even in unused code.
1594 if (program.fSettings.fRemoveDeadFunctions) {
Brian Osman2e25ff42020-10-15 10:32:04 -04001595 Analysis::CallCountMap callCounts = Analysis::GetCallCounts(program);
1596
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001597 program.fElements.erase(
1598 std::remove_if(program.fElements.begin(),
1599 program.fElements.end(),
1600 [&](const std::unique_ptr<ProgramElement>& element) {
1601 if (!element->is<FunctionDefinition>()) {
1602 return false;
1603 }
1604 const auto& fn = element->as<FunctionDefinition>();
Brian Osman2e25ff42020-10-15 10:32:04 -04001605 bool dead = fn.declaration().name() != "main" &&
1606 callCounts[&fn.declaration()] == 0;
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001607 madeChanges |= dead;
1608 return dead;
1609 }),
1610 program.fElements.end());
1611 }
1612
1613 if (program.fKind != Program::kFragmentProcessor_Kind) {
Brian Osmanc0213602020-10-06 14:43:32 -04001614 // Remove declarations of dead global variables
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001615 program.fElements.erase(
1616 std::remove_if(program.fElements.begin(), program.fElements.end(),
1617 [&](const std::unique_ptr<ProgramElement>& element) {
Brian Osmanc0213602020-10-06 14:43:32 -04001618 if (!element->is<GlobalVarDeclaration>()) {
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001619 return false;
1620 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001621 const auto& global = element->as<GlobalVarDeclaration>();
1622 const auto& varDecl =
1623 global.declaration()->as<VarDeclaration>();
1624 bool dead = varDecl.var().dead();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001625 madeChanges |= dead;
1626 return dead;
1627 }),
1628 program.fElements.end());
1629 }
John Stiles73a6bff2020-09-09 13:40:37 -04001630
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001631 if (!madeChanges) {
1632 break;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001633 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001634 }
1635 return fErrorCount == 0;
1636}
1637
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001638#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1639
Ethan Nicholas00543112018-07-31 09:44:36 -04001640bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001641#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001642 StringStream buffer;
Brian Osman88cda172020-10-09 12:05:16 -04001643 AutoSource as(this, program.fSource.get());
Brian Osman8b43dad2020-10-09 13:31:42 -04001644 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001645 bool result = cg.generateCode();
1646 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001647 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001648 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001649 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001650 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1651 SkDebugf("SPIR-V validation error: %s\n", m);
1652 };
1653 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001654 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001655 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001656 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001657 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001658 }
1659#else
Brian Osman88cda172020-10-09 12:05:16 -04001660 AutoSource as(this, program.fSource.get());
Brian Osman8b43dad2020-10-09 13:31:42 -04001661 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001662 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001663#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001664 return result;
1665}
1666
Ethan Nicholas00543112018-07-31 09:44:36 -04001667bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001668 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001669 bool result = this->toSPIRV(program, buffer);
1670 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001671 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001672 }
1673 return result;
1674}
1675
Ethan Nicholas00543112018-07-31 09:44:36 -04001676bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -04001677 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001678 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001679 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001680 return result;
1681}
1682
Ethan Nicholas00543112018-07-31 09:44:36 -04001683bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001684 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001685 bool result = this->toGLSL(program, buffer);
1686 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001687 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001688 }
1689 return result;
1690}
1691
Brian Osmanc0243912020-02-19 15:35:26 -05001692bool Compiler::toHLSL(Program& program, String* out) {
1693 String spirv;
1694 if (!this->toSPIRV(program, &spirv)) {
1695 return false;
1696 }
1697
1698 return SPIRVtoHLSL(spirv, out);
1699}
1700
Ethan Nicholas00543112018-07-31 09:44:36 -04001701bool Compiler::toMetal(Program& program, OutputStream& out) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001702 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001703 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001704 return result;
1705}
1706
Ethan Nicholas00543112018-07-31 09:44:36 -04001707bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001708 StringStream buffer;
1709 bool result = this->toMetal(program, buffer);
1710 if (result) {
1711 *out = buffer.str();
1712 }
1713 return result;
1714}
1715
Greg Daniela28ea672020-09-25 11:12:56 -04001716#if defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04001717bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -04001718 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001719 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001720 bool result = cg.generateCode();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001721 return result;
1722}
1723
Ethan Nicholas00543112018-07-31 09:44:36 -04001724bool Compiler::toH(Program& program, String name, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -04001725 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001726 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001727 bool result = cg.generateCode();
Ethan Nicholas00543112018-07-31 09:44:36 -04001728 return result;
1729}
Greg Daniela28ea672020-09-25 11:12:56 -04001730#endif // defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04001731
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001732#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04001733
1734#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osmana4b91692020-08-10 14:26:16 -04001735bool Compiler::toPipelineStage(Program& program, PipelineStageArgs* outArgs) {
Brian Osman88cda172020-10-09 12:05:16 -04001736 AutoSource as(this, program.fSource.get());
Ethan Nicholas00543112018-07-31 09:44:36 -04001737 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001738 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001739 bool result = cg.generateCode();
Ethan Nicholas00543112018-07-31 09:44:36 -04001740 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001741 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001742 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001743 return result;
1744}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001745#endif
1746
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001747std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Mike Klein853d4ed2020-08-20 00:41:00 +00001748#if defined(SK_ENABLE_SKSL_INTERPRETER)
Brian Osman88cda172020-10-09 12:05:16 -04001749 AutoSource as(this, program.fSource.get());
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001750 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001751 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1752 bool success = cg.generateCode();
Brian Osmanb08cc022020-04-02 11:38:40 -04001753 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001754 return result;
1755 }
Mike Klein853d4ed2020-08-20 00:41:00 +00001756#else
1757 ABORT("ByteCode interpreter not enabled");
1758#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001759 return nullptr;
1760}
1761
Brian Osman401a0092020-09-10 14:47:24 -04001762const char* Compiler::OperatorName(Token::Kind op) {
1763 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001764 case Token::Kind::TK_PLUS: return "+";
1765 case Token::Kind::TK_MINUS: return "-";
1766 case Token::Kind::TK_STAR: return "*";
1767 case Token::Kind::TK_SLASH: return "/";
1768 case Token::Kind::TK_PERCENT: return "%";
1769 case Token::Kind::TK_SHL: return "<<";
1770 case Token::Kind::TK_SHR: return ">>";
1771 case Token::Kind::TK_LOGICALNOT: return "!";
1772 case Token::Kind::TK_LOGICALAND: return "&&";
1773 case Token::Kind::TK_LOGICALOR: return "||";
1774 case Token::Kind::TK_LOGICALXOR: return "^^";
1775 case Token::Kind::TK_BITWISENOT: return "~";
1776 case Token::Kind::TK_BITWISEAND: return "&";
1777 case Token::Kind::TK_BITWISEOR: return "|";
1778 case Token::Kind::TK_BITWISEXOR: return "^";
1779 case Token::Kind::TK_EQ: return "=";
1780 case Token::Kind::TK_EQEQ: return "==";
1781 case Token::Kind::TK_NEQ: return "!=";
1782 case Token::Kind::TK_LT: return "<";
1783 case Token::Kind::TK_GT: return ">";
1784 case Token::Kind::TK_LTEQ: return "<=";
1785 case Token::Kind::TK_GTEQ: return ">=";
1786 case Token::Kind::TK_PLUSEQ: return "+=";
1787 case Token::Kind::TK_MINUSEQ: return "-=";
1788 case Token::Kind::TK_STAREQ: return "*=";
1789 case Token::Kind::TK_SLASHEQ: return "/=";
1790 case Token::Kind::TK_PERCENTEQ: return "%=";
1791 case Token::Kind::TK_SHLEQ: return "<<=";
1792 case Token::Kind::TK_SHREQ: return ">>=";
1793 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1794 case Token::Kind::TK_LOGICALOREQ: return "||=";
1795 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1796 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1797 case Token::Kind::TK_BITWISEOREQ: return "|=";
1798 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1799 case Token::Kind::TK_PLUSPLUS: return "++";
1800 case Token::Kind::TK_MINUSMINUS: return "--";
1801 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001802 default:
Brian Osman401a0092020-09-10 14:47:24 -04001803 ABORT("unsupported operator: %d\n", (int) op);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001804 }
1805}
1806
1807
1808bool Compiler::IsAssignment(Token::Kind op) {
1809 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001810 case Token::Kind::TK_EQ: // fall through
1811 case Token::Kind::TK_PLUSEQ: // fall through
1812 case Token::Kind::TK_MINUSEQ: // fall through
1813 case Token::Kind::TK_STAREQ: // fall through
1814 case Token::Kind::TK_SLASHEQ: // fall through
1815 case Token::Kind::TK_PERCENTEQ: // fall through
1816 case Token::Kind::TK_SHLEQ: // fall through
1817 case Token::Kind::TK_SHREQ: // fall through
1818 case Token::Kind::TK_BITWISEOREQ: // fall through
1819 case Token::Kind::TK_BITWISEXOREQ: // fall through
1820 case Token::Kind::TK_BITWISEANDEQ: // fall through
1821 case Token::Kind::TK_LOGICALOREQ: // fall through
1822 case Token::Kind::TK_LOGICALXOREQ: // fall through
1823 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001824 return true;
1825 default:
1826 return false;
1827 }
1828}
1829
Brian Osman401a0092020-09-10 14:47:24 -04001830Token::Kind Compiler::RemoveAssignment(Token::Kind op) {
1831 switch (op) {
1832 case Token::Kind::TK_PLUSEQ: return Token::Kind::TK_PLUS;
1833 case Token::Kind::TK_MINUSEQ: return Token::Kind::TK_MINUS;
1834 case Token::Kind::TK_STAREQ: return Token::Kind::TK_STAR;
1835 case Token::Kind::TK_SLASHEQ: return Token::Kind::TK_SLASH;
1836 case Token::Kind::TK_PERCENTEQ: return Token::Kind::TK_PERCENT;
1837 case Token::Kind::TK_SHLEQ: return Token::Kind::TK_SHL;
1838 case Token::Kind::TK_SHREQ: return Token::Kind::TK_SHR;
1839 case Token::Kind::TK_BITWISEOREQ: return Token::Kind::TK_BITWISEOR;
1840 case Token::Kind::TK_BITWISEXOREQ: return Token::Kind::TK_BITWISEXOR;
1841 case Token::Kind::TK_BITWISEANDEQ: return Token::Kind::TK_BITWISEAND;
1842 case Token::Kind::TK_LOGICALOREQ: return Token::Kind::TK_LOGICALOR;
1843 case Token::Kind::TK_LOGICALXOREQ: return Token::Kind::TK_LOGICALXOR;
1844 case Token::Kind::TK_LOGICALANDEQ: return Token::Kind::TK_LOGICALAND;
1845 default: return op;
1846 }
1847}
1848
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001849Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001850 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001851 int line = 1;
1852 int column = 1;
1853 for (int i = 0; i < offset; i++) {
1854 if ((*fSource)[i] == '\n') {
1855 ++line;
1856 column = 1;
1857 }
1858 else {
1859 ++column;
1860 }
1861 }
1862 return Position(line, column);
1863}
1864
1865void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001866 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001867 Position pos = this->position(offset);
1868 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001869}
1870
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001871String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001872 this->writeErrorCount();
1873 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001874 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001875 return result;
1876}
1877
1878void Compiler::writeErrorCount() {
1879 if (fErrorCount) {
1880 fErrorText += to_string(fErrorCount) + " error";
1881 if (fErrorCount > 1) {
1882 fErrorText += "s";
1883 }
1884 fErrorText += "\n";
1885 }
1886}
1887
John Stilesa6841be2020-08-06 14:11:56 -04001888} // namespace SkSL