blob: de8b735bd0fc942ed4126b0544e2d8e9cafa6cbc [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/SkSLByteCodeGenerator.h"
11#include "src/sksl/SkSLCFGGenerator.h"
12#include "src/sksl/SkSLCPPCodeGenerator.h"
13#include "src/sksl/SkSLGLSLCodeGenerator.h"
14#include "src/sksl/SkSLHCodeGenerator.h"
15#include "src/sksl/SkSLIRGenerator.h"
16#include "src/sksl/SkSLMetalCodeGenerator.h"
17#include "src/sksl/SkSLPipelineStageCodeGenerator.h"
18#include "src/sksl/SkSLSPIRVCodeGenerator.h"
19#include "src/sksl/ir/SkSLEnum.h"
20#include "src/sksl/ir/SkSLExpression.h"
21#include "src/sksl/ir/SkSLExpressionStatement.h"
22#include "src/sksl/ir/SkSLFunctionCall.h"
23#include "src/sksl/ir/SkSLIntLiteral.h"
24#include "src/sksl/ir/SkSLModifiersDeclaration.h"
25#include "src/sksl/ir/SkSLNop.h"
26#include "src/sksl/ir/SkSLSymbolTable.h"
27#include "src/sksl/ir/SkSLTernaryExpression.h"
28#include "src/sksl/ir/SkSLUnresolvedFunction.h"
29#include "src/sksl/ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070030
Ethan Nicholasa11035b2019-11-26 16:27:47 -050031#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
32#include "include/gpu/GrContextOptions.h"
33#include "src/gpu/GrShaderCaps.h"
34#endif
35
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040036#ifdef SK_ENABLE_SPIRV_VALIDATION
37#include "spirv-tools/libspirv.hpp"
38#endif
39
ethannicholasb3058bd2016-07-01 08:22:01 -070040// include the built-in shader symbols as static strings
41
Ethan Nicholas79707652017-11-16 11:20:11 -050042#define STRINGIFY(x) #x
43
Ethan Nicholas8da1e652019-05-24 11:01:59 -040044static const char* SKSL_GPU_INCLUDE =
45#include "sksl_gpu.inc"
46;
47
Brian Salomonf8c187c2019-12-19 14:41:57 -050048static const char* SKSL_BLEND_INCLUDE =
49#include "sksl_blend.inc"
50;
51
Ethan Nicholas8da1e652019-05-24 11:01:59 -040052static const char* SKSL_INTERP_INCLUDE =
53#include "sksl_interp.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070054;
55
ethannicholas5961bc92016-10-12 06:39:56 -070056static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050057#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070058;
59
ethannicholas5961bc92016-10-12 06:39:56 -070060static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050061#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070062;
63
Ethan Nicholas52cad152017-02-16 16:37:32 -050064static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050065#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050066;
67
Ethan Nicholas762466e2017-06-29 10:03:38 -040068static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050069#include "sksl_enums.inc"
70#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040071;
72
Ethan Nicholas8da1e652019-05-24 11:01:59 -040073static const char* SKSL_PIPELINE_INCLUDE =
74#include "sksl_pipeline.inc"
Ethan Nicholas0d997662019-04-08 09:46:01 -040075;
76
ethannicholasb3058bd2016-07-01 08:22:01 -070077namespace SkSL {
78
Ethan Nicholasdb80f692019-11-22 14:06:12 -050079static void grab_intrinsics(std::vector<std::unique_ptr<ProgramElement>>* src,
Ethan Nicholasb962eff2020-01-23 16:49:41 -050080 std::map<String, std::pair<std::unique_ptr<ProgramElement>, bool>>* target) {
81 for (auto iter = src->begin(); iter != src->end(); ) {
82 std::unique_ptr<ProgramElement>& element = *iter;
Ethan Nicholasdb80f692019-11-22 14:06:12 -050083 switch (element->fKind) {
84 case ProgramElement::kFunction_Kind: {
85 FunctionDefinition& f = (FunctionDefinition&) *element;
Ethan Nicholasb962eff2020-01-23 16:49:41 -050086 SkASSERT(f.fDeclaration.fBuiltin);
87 String key = f.fDeclaration.declaration();
88 SkASSERT(target->find(key) == target->end());
89 (*target)[key] = std::make_pair(std::move(element), false);
90 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050091 break;
92 }
93 case ProgramElement::kEnum_Kind: {
94 Enum& e = (Enum&) *element;
95 StringFragment name = e.fTypeName;
96 SkASSERT(target->find(name) == target->end());
97 (*target)[name] = std::make_pair(std::move(element), false);
Ethan Nicholasb962eff2020-01-23 16:49:41 -050098 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050099 break;
100 }
101 default:
102 printf("unsupported include file element\n");
103 SkASSERT(false);
104 }
105 }
106}
107
108
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400109Compiler::Compiler(Flags flags)
110: fFlags(flags)
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400111, fContext(new Context())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400112, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -0400113 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
114 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400115 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700116 fTypes = types;
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400117 #define ADD_TYPE(t) types->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
118 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700119 ADD_TYPE(Void);
120 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400121 ADD_TYPE(Float2);
122 ADD_TYPE(Float3);
123 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400124 ADD_TYPE(Half);
125 ADD_TYPE(Half2);
126 ADD_TYPE(Half3);
127 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700128 ADD_TYPE(Double);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400129 ADD_TYPE(Double2);
130 ADD_TYPE(Double3);
131 ADD_TYPE(Double4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700132 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400133 ADD_TYPE(Int2);
134 ADD_TYPE(Int3);
135 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700136 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400137 ADD_TYPE(UInt2);
138 ADD_TYPE(UInt3);
139 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400140 ADD_TYPE(Short);
141 ADD_TYPE(Short2);
142 ADD_TYPE(Short3);
143 ADD_TYPE(Short4);
144 ADD_TYPE(UShort);
145 ADD_TYPE(UShort2);
146 ADD_TYPE(UShort3);
147 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400148 ADD_TYPE(Byte);
149 ADD_TYPE(Byte2);
150 ADD_TYPE(Byte3);
151 ADD_TYPE(Byte4);
152 ADD_TYPE(UByte);
153 ADD_TYPE(UByte2);
154 ADD_TYPE(UByte3);
155 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700156 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400157 ADD_TYPE(Bool2);
158 ADD_TYPE(Bool3);
159 ADD_TYPE(Bool4);
160 ADD_TYPE(Float2x2);
161 ADD_TYPE(Float2x3);
162 ADD_TYPE(Float2x4);
163 ADD_TYPE(Float3x2);
164 ADD_TYPE(Float3x3);
165 ADD_TYPE(Float3x4);
166 ADD_TYPE(Float4x2);
167 ADD_TYPE(Float4x3);
168 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400169 ADD_TYPE(Half2x2);
170 ADD_TYPE(Half2x3);
171 ADD_TYPE(Half2x4);
172 ADD_TYPE(Half3x2);
173 ADD_TYPE(Half3x3);
174 ADD_TYPE(Half3x4);
175 ADD_TYPE(Half4x2);
176 ADD_TYPE(Half4x3);
177 ADD_TYPE(Half4x4);
178 ADD_TYPE(Double2x2);
179 ADD_TYPE(Double2x3);
180 ADD_TYPE(Double2x4);
181 ADD_TYPE(Double3x2);
182 ADD_TYPE(Double3x3);
183 ADD_TYPE(Double3x4);
184 ADD_TYPE(Double4x2);
185 ADD_TYPE(Double4x3);
186 ADD_TYPE(Double4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700187 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400188 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700189 ADD_TYPE(GenDType);
190 ADD_TYPE(GenIType);
191 ADD_TYPE(GenUType);
192 ADD_TYPE(GenBType);
193 ADD_TYPE(Mat);
194 ADD_TYPE(Vec);
195 ADD_TYPE(GVec);
196 ADD_TYPE(GVec2);
197 ADD_TYPE(GVec3);
198 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400199 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700200 ADD_TYPE(DVec);
201 ADD_TYPE(IVec);
202 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400203 ADD_TYPE(SVec);
204 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400205 ADD_TYPE(ByteVec);
206 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700207 ADD_TYPE(BVec);
208
209 ADD_TYPE(Sampler1D);
210 ADD_TYPE(Sampler2D);
211 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700212 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700213 ADD_TYPE(SamplerCube);
214 ADD_TYPE(Sampler2DRect);
215 ADD_TYPE(Sampler1DArray);
216 ADD_TYPE(Sampler2DArray);
217 ADD_TYPE(SamplerCubeArray);
218 ADD_TYPE(SamplerBuffer);
219 ADD_TYPE(Sampler2DMS);
220 ADD_TYPE(Sampler2DMSArray);
221
Brian Salomonbf7b6202016-11-11 16:08:03 -0500222 ADD_TYPE(ISampler2D);
223
Brian Salomon2a51de82016-11-16 12:06:01 -0500224 ADD_TYPE(Image2D);
225 ADD_TYPE(IImage2D);
226
Greg Daniel64773e62016-11-22 09:44:03 -0500227 ADD_TYPE(SubpassInput);
228 ADD_TYPE(SubpassInputMS);
229
ethannicholasb3058bd2016-07-01 08:22:01 -0700230 ADD_TYPE(GSampler1D);
231 ADD_TYPE(GSampler2D);
232 ADD_TYPE(GSampler3D);
233 ADD_TYPE(GSamplerCube);
234 ADD_TYPE(GSampler2DRect);
235 ADD_TYPE(GSampler1DArray);
236 ADD_TYPE(GSampler2DArray);
237 ADD_TYPE(GSamplerCubeArray);
238 ADD_TYPE(GSamplerBuffer);
239 ADD_TYPE(GSampler2DMS);
240 ADD_TYPE(GSampler2DMSArray);
241
242 ADD_TYPE(Sampler1DShadow);
243 ADD_TYPE(Sampler2DShadow);
244 ADD_TYPE(SamplerCubeShadow);
245 ADD_TYPE(Sampler2DRectShadow);
246 ADD_TYPE(Sampler1DArrayShadow);
247 ADD_TYPE(Sampler2DArrayShadow);
248 ADD_TYPE(SamplerCubeArrayShadow);
249 ADD_TYPE(GSampler2DArrayShadow);
250 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400251 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400252 ADD_TYPE(Sampler);
253 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700254
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700255 StringFragment skCapsName("sk_Caps");
256 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400257 *fContext->fSkCaps_Type, Variable::kGlobal_Storage);
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500258 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
259
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700260 StringFragment skArgsName("sk_Args");
261 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400262 *fContext->fSkArgs_Type, Variable::kGlobal_Storage);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400263 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
264
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500265 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
266 std::vector<std::unique_ptr<ProgramElement>> gpuIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400267 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, strlen(SKSL_GPU_INCLUDE),
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500268 symbols, &gpuIntrinsics, &fGpuSymbolTable);
Brian Salomonf8c187c2019-12-19 14:41:57 -0500269 this->processIncludeFile(Program::kFragment_Kind, SKSL_BLEND_INCLUDE,
270 strlen(SKSL_BLEND_INCLUDE), std::move(fGpuSymbolTable), &gpuIntrinsics,
271 &fGpuSymbolTable);
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500272 grab_intrinsics(&gpuIntrinsics, &fGPUIntrinsics);
273 // need to hang on to the source so that FunctionDefinition.fSource pointers in this file
274 // remain valid
275 fGpuIncludeSource = std::move(fIRGenerator->fFile);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400276 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, strlen(SKSL_VERT_INCLUDE),
277 fGpuSymbolTable, &fVertexInclude, &fVertexSymbolTable);
278 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, strlen(SKSL_FRAG_INCLUDE),
279 fGpuSymbolTable, &fFragmentInclude, &fFragmentSymbolTable);
280 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, strlen(SKSL_GEOM_INCLUDE),
281 fGpuSymbolTable, &fGeometryInclude, &fGeometrySymbolTable);
282 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
283 strlen(SKSL_PIPELINE_INCLUDE), fGpuSymbolTable, &fPipelineInclude,
284 &fPipelineSymbolTable);
285 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
286 strlen(SKSL_INTERP_INCLUDE), symbols, &fInterpreterInclude,
287 &fInterpreterSymbolTable);
Ethan Nicholasb962eff2020-01-23 16:49:41 -0500288 grab_intrinsics(&fInterpreterInclude, &fInterpreterIntrinsics);
289 // need to hang on to the source so that FunctionDefinition.fSource pointers in this file
290 // remain valid
291 fInterpreterIncludeSource = std::move(fIRGenerator->fFile);
ethannicholasb3058bd2016-07-01 08:22:01 -0700292}
293
294Compiler::~Compiler() {
295 delete fIRGenerator;
296}
297
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400298void Compiler::processIncludeFile(Program::Kind kind, const char* src, size_t length,
299 std::shared_ptr<SymbolTable> base,
300 std::vector<std::unique_ptr<ProgramElement>>* outElements,
301 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500302#ifdef SK_DEBUG
303 String source(src, length);
304 fSource = &source;
305#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400306 fIRGenerator->fSymbolTable = std::move(base);
307 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500308#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
309 GrContextOptions opts;
310 GrShaderCaps caps(opts);
311 settings.fCaps = &caps;
312#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400313 fIRGenerator->start(&settings, nullptr);
314 fIRGenerator->convertProgram(kind, src, length, *fTypes, outElements);
315 if (this->fErrorCount) {
316 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
317 }
318 SkASSERT(!fErrorCount);
319 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
320 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500321#ifdef SK_DEBUG
322 fSource = nullptr;
323#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400324}
325
ethannicholas22f939e2016-10-13 13:25:34 -0700326// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500327void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
328 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700329 switch (lvalue->fKind) {
330 case Expression::kVariableReference_Kind: {
331 const Variable& var = ((VariableReference*) lvalue)->fVariable;
332 if (var.fStorage == Variable::kLocal_Storage) {
333 (*definitions)[&var] = expr;
334 }
335 break;
336 }
337 case Expression::kSwizzle_Kind:
338 // We consider the variable written to as long as at least some of its components have
339 // been written to. This will lead to some false negatives (we won't catch it if you
340 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400341 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
342 // 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 -0700343 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400344 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400345 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700346 definitions);
347 break;
348 case Expression::kIndex_Kind:
349 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400350 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400351 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700352 definitions);
353 break;
354 case Expression::kFieldAccess_Kind:
355 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400356 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400357 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700358 definitions);
359 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500360 case Expression::kTernary_Kind:
361 // To simplify analysis, we just pretend that we write to both sides of the ternary.
362 // This allows for false positives (meaning we fail to detect that a variable might not
363 // have been assigned), but is preferable to false negatives.
364 this->addDefinition(((TernaryExpression*) lvalue)->fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400365 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500366 definitions);
367 this->addDefinition(((TernaryExpression*) lvalue)->fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400368 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500369 definitions);
370 break;
Ethan Nicholas91164d12019-05-15 15:29:54 -0400371 case Expression::kExternalValue_Kind:
372 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700373 default:
374 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400375 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700376 }
377}
378
379// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400380void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500381 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700382 switch (node.fKind) {
383 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400384 SkASSERT(node.expression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400385 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500386 switch (expr->fKind) {
387 case Expression::kBinary_Kind: {
388 BinaryExpression* b = (BinaryExpression*) expr;
389 if (b->fOperator == Token::EQ) {
390 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700391 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500392 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400393 b->fLeft.get(),
394 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
395 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500396
397 }
398 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700399 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400400 case Expression::kFunctionCall_Kind: {
401 const FunctionCall& c = (const FunctionCall&) *expr;
402 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
403 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
404 this->addDefinition(
405 c.fArguments[i].get(),
406 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
407 definitions);
408 }
409 }
410 break;
411 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500412 case Expression::kPrefix_Kind: {
413 const PrefixExpression* p = (PrefixExpression*) expr;
414 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
415 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400416 p->fOperand.get(),
417 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
418 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500419 }
420 break;
421 }
422 case Expression::kPostfix_Kind: {
423 const PostfixExpression* p = (PostfixExpression*) expr;
424 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
425 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400426 p->fOperand.get(),
427 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
428 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500429 }
430 break;
431 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400432 case Expression::kVariableReference_Kind: {
433 const VariableReference* v = (VariableReference*) expr;
434 if (v->fRefKind != VariableReference::kRead_RefKind) {
435 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400436 v,
437 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
438 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400439 }
440 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500441 default:
442 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700443 }
444 break;
445 }
446 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400447 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000448 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
449 VarDeclaration& vd = (VarDeclaration&) *stmt;
450 if (vd.fValue) {
451 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700452 }
453 }
454 break;
455 }
456 }
457}
458
459void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
460 BasicBlock& block = cfg->fBlocks[blockId];
461
462 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500463 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700464 for (const BasicBlock::Node& n : block.fNodes) {
465 this->addDefinitions(n, &after);
466 }
467
468 // propagate definitions to exits
469 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400470 if (exitId == blockId) {
471 continue;
472 }
ethannicholas22f939e2016-10-13 13:25:34 -0700473 BasicBlock& exit = cfg->fBlocks[exitId];
474 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500475 std::unique_ptr<Expression>* e1 = pair.second;
476 auto found = exit.fBefore.find(pair.first);
477 if (found == exit.fBefore.end()) {
478 // exit has no definition for it, just copy it
479 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700480 exit.fBefore[pair.first] = e1;
481 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500482 // exit has a (possibly different) value already defined
483 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700484 if (e1 != e2) {
485 // definition has changed, merge and add exit block to worklist
486 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500487 if (e1 && e2) {
488 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400489 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500490 } else {
491 exit.fBefore[pair.first] = nullptr;
492 }
ethannicholas22f939e2016-10-13 13:25:34 -0700493 }
494 }
495 }
496 }
497}
498
499// returns a map which maps all local variables in the function to null, indicating that their value
500// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500501static DefinitionMap compute_start_state(const CFG& cfg) {
502 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400503 for (const auto& block : cfg.fBlocks) {
504 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700505 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400506 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400507 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700508 if (s->fKind == Statement::kVarDeclarations_Kind) {
509 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000510 for (const auto& decl : vd->fDeclaration->fVars) {
511 if (decl->fKind == Statement::kVarDeclaration_Kind) {
512 result[((VarDeclaration&) *decl).fVar] = nullptr;
513 }
Mike Klein6ad99092016-10-26 10:35:22 -0400514 }
ethannicholas22f939e2016-10-13 13:25:34 -0700515 }
516 }
517 }
518 }
519 return result;
520}
521
Ethan Nicholascb670962017-04-20 19:31:52 -0400522/**
523 * Returns true if assigning to this lvalue has no effect.
524 */
525static bool is_dead(const Expression& lvalue) {
526 switch (lvalue.fKind) {
527 case Expression::kVariableReference_Kind:
528 return ((VariableReference&) lvalue).fVariable.dead();
529 case Expression::kSwizzle_Kind:
530 return is_dead(*((Swizzle&) lvalue).fBase);
531 case Expression::kFieldAccess_Kind:
532 return is_dead(*((FieldAccess&) lvalue).fBase);
533 case Expression::kIndex_Kind: {
534 const IndexExpression& idx = (IndexExpression&) lvalue;
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500535 return is_dead(*idx.fBase) &&
536 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400537 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500538 case Expression::kTernary_Kind: {
539 const TernaryExpression& t = (TernaryExpression&) lvalue;
540 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
541 }
Ethan Nicholas91164d12019-05-15 15:29:54 -0400542 case Expression::kExternalValue_Kind:
543 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400544 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500545#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400546 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500547#endif
548 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400549 }
550}
ethannicholas22f939e2016-10-13 13:25:34 -0700551
Ethan Nicholascb670962017-04-20 19:31:52 -0400552/**
553 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
554 * to a dead target and lack of side effects on the left hand side.
555 */
556static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700557 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400558 return false;
559 }
560 return is_dead(*b.fLeft);
561}
562
563void Compiler::computeDataFlow(CFG* cfg) {
564 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700565 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400566 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700567 workList.insert(i);
568 }
569 while (workList.size()) {
570 BlockId next = *workList.begin();
571 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400572 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700573 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400574}
575
576/**
577 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
578 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
579 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
580 * need to be regenerated).
581 */
582bool try_replace_expression(BasicBlock* b,
583 std::vector<BasicBlock::Node>::iterator* iter,
584 std::unique_ptr<Expression>* newExpression) {
585 std::unique_ptr<Expression>* target = (*iter)->expression();
586 if (!b->tryRemoveExpression(iter)) {
587 *target = std::move(*newExpression);
588 return false;
589 }
590 *target = std::move(*newExpression);
591 return b->tryInsertExpression(iter, target);
592}
593
594/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400595 * Returns true if the expression is a constant numeric literal with the specified value, or a
596 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400597 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400598bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400599 switch (expr.fKind) {
600 case Expression::kIntLiteral_Kind:
601 return ((IntLiteral&) expr).fValue == value;
602 case Expression::kFloatLiteral_Kind:
603 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400604 case Expression::kConstructor_Kind: {
605 Constructor& c = (Constructor&) expr;
Ethan Nicholasd188c182019-06-10 15:55:38 -0400606 bool isFloat = c.fType.columns() > 1 ? c.fType.componentType().isFloat()
607 : c.fType.isFloat();
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400608 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
609 for (int i = 0; i < c.fType.columns(); ++i) {
Ethan Nicholasd188c182019-06-10 15:55:38 -0400610 if (isFloat) {
611 if (c.getFVecComponent(i) != value) {
612 return false;
613 }
614 } else if (c.getIVecComponent(i) != value) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400615 return false;
616 }
617 }
618 return true;
619 }
620 return false;
621 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400622 default:
623 return false;
624 }
625}
626
627/**
628 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
629 * and CFG structures).
630 */
631void delete_left(BasicBlock* b,
632 std::vector<BasicBlock::Node>::iterator* iter,
633 bool* outUpdated,
634 bool* outNeedsRescan) {
635 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400636 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400637 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400638 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400639 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400640 bool result;
641 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400642 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400643 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400644 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400645 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400646 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400647 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400648 *outNeedsRescan = true;
649 return;
650 }
651 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400652 *outNeedsRescan = true;
653 return;
654 }
655 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400656 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
657 (*iter)->expression() != &bin.fRight) {
658 *outNeedsRescan = true;
659 return;
660 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400661 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400662 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400663}
664
665/**
666 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
667 * CFG structures).
668 */
669void delete_right(BasicBlock* b,
670 std::vector<BasicBlock::Node>::iterator* iter,
671 bool* outUpdated,
672 bool* outNeedsRescan) {
673 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400674 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400675 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400676 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400677 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400678 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
679 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400680 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400681 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400682 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400683 *target = std::move(bin.fLeft);
684 if (*iter == b->fNodes.begin()) {
685 *outNeedsRescan = true;
686 return;
687 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400688 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400689 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
690 (*iter)->expression() != &bin.fLeft)) {
691 *outNeedsRescan = true;
692 return;
693 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400694 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400695 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400696}
697
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400698/**
699 * Constructs the specified type using a single argument.
700 */
701static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
702 std::vector<std::unique_ptr<Expression>> args;
703 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700704 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400705 return result;
706}
707
708/**
709 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
710 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
711 */
712static void vectorize(BasicBlock* b,
713 std::vector<BasicBlock::Node>::iterator* iter,
714 const Type& type,
715 std::unique_ptr<Expression>* otherExpression,
716 bool* outUpdated,
717 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400718 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
719 SkASSERT(type.kind() == Type::kVector_Kind);
720 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400721 *outUpdated = true;
722 std::unique_ptr<Expression>* target = (*iter)->expression();
723 if (!b->tryRemoveExpression(iter)) {
724 *target = construct(type, std::move(*otherExpression));
725 *outNeedsRescan = true;
726 } else {
727 *target = construct(type, std::move(*otherExpression));
728 if (!b->tryInsertExpression(iter, target)) {
729 *outNeedsRescan = true;
730 }
731 }
732}
733
734/**
735 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
736 * left to yield vec<n>(x).
737 */
738static void vectorize_left(BasicBlock* b,
739 std::vector<BasicBlock::Node>::iterator* iter,
740 bool* outUpdated,
741 bool* outNeedsRescan) {
742 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
743 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
744}
745
746/**
747 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
748 * right to yield vec<n>(y).
749 */
750static void vectorize_right(BasicBlock* b,
751 std::vector<BasicBlock::Node>::iterator* iter,
752 bool* outUpdated,
753 bool* outNeedsRescan) {
754 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
755 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
756}
757
758// Mark that an expression which we were writing to is no longer being written to
759void clear_write(const Expression& expr) {
760 switch (expr.fKind) {
761 case Expression::kVariableReference_Kind: {
762 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
763 break;
764 }
765 case Expression::kFieldAccess_Kind:
766 clear_write(*((FieldAccess&) expr).fBase);
767 break;
768 case Expression::kSwizzle_Kind:
769 clear_write(*((Swizzle&) expr).fBase);
770 break;
771 case Expression::kIndex_Kind:
772 clear_write(*((IndexExpression&) expr).fBase);
773 break;
774 default:
775 ABORT("shouldn't be writing to this kind of expression\n");
776 break;
777 }
778}
779
Ethan Nicholascb670962017-04-20 19:31:52 -0400780void Compiler::simplifyExpression(DefinitionMap& definitions,
781 BasicBlock& b,
782 std::vector<BasicBlock::Node>::iterator* iter,
783 std::unordered_set<const Variable*>* undefinedVariables,
784 bool* outUpdated,
785 bool* outNeedsRescan) {
786 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400787 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400788 if ((*iter)->fConstantPropagation) {
789 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
790 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400791 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400792 if (!try_replace_expression(&b, iter, &optimized)) {
793 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400794 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400795 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400796 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400797 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400798 }
799 }
800 switch (expr->fKind) {
801 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400802 const VariableReference& ref = (VariableReference&) *expr;
803 const Variable& var = ref.fVariable;
804 if (ref.refKind() != VariableReference::kWrite_RefKind &&
805 ref.refKind() != VariableReference::kPointer_RefKind &&
806 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400807 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
808 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000809 this->error(expr->fOffset,
810 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400811 }
812 break;
813 }
814 case Expression::kTernary_Kind: {
815 TernaryExpression* t = (TernaryExpression*) expr;
816 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
817 // ternary has a constant test, replace it with either the true or
818 // false branch
819 if (((BoolLiteral&) *t->fTest).fValue) {
820 (*iter)->setExpression(std::move(t->fIfTrue));
821 } else {
822 (*iter)->setExpression(std::move(t->fIfFalse));
823 }
824 *outUpdated = true;
825 *outNeedsRescan = true;
826 }
827 break;
828 }
829 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400830 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400831 if (dead_assignment(*bin)) {
832 delete_left(&b, iter, outUpdated, outNeedsRescan);
833 break;
834 }
835 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400836 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
837 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
838 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
839 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
840 break;
841 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400842 switch (bin->fOperator) {
843 case Token::STAR:
844 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400845 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
846 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400847 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400848 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
849 } else {
850 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400851 // 1 * float4(x) -> float4(x)
852 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400853 delete_left(&b, iter, outUpdated, outNeedsRescan);
854 }
855 }
856 else if (is_constant(*bin->fLeft, 0)) {
857 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500858 bin->fRight->fType.kind() == Type::kVector_Kind &&
859 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400860 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400861 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
862 } else {
863 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400864 // float4(0) * x -> float4(0)
865 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500866 if (!bin->fRight->hasSideEffects()) {
867 delete_right(&b, iter, outUpdated, outNeedsRescan);
868 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400869 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400870 }
871 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400872 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
873 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400874 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400875 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
876 } else {
877 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400878 // float4(x) * 1 -> float4(x)
879 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400880 delete_right(&b, iter, outUpdated, outNeedsRescan);
881 }
882 }
883 else if (is_constant(*bin->fRight, 0)) {
884 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500885 bin->fRight->fType.kind() == Type::kScalar_Kind &&
886 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400887 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400888 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
889 } else {
890 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400891 // x * float4(0) -> float4(0)
892 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500893 if (!bin->fLeft->hasSideEffects()) {
894 delete_left(&b, iter, outUpdated, outNeedsRescan);
895 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400896 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400897 }
898 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400899 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400900 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400901 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
902 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400903 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400904 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
905 } else {
906 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400907 // 0 + float4(x) -> float4(x)
908 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400909 delete_left(&b, iter, outUpdated, outNeedsRescan);
910 }
911 } else if (is_constant(*bin->fRight, 0)) {
912 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
913 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400914 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400915 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
916 } else {
917 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400918 // float4(x) + 0 -> float4(x)
919 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400920 delete_right(&b, iter, outUpdated, outNeedsRescan);
921 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400922 }
923 break;
924 case Token::MINUS:
925 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400926 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
927 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400928 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400929 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
930 } else {
931 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400932 // float4(x) - 0 -> float4(x)
933 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400934 delete_right(&b, iter, outUpdated, outNeedsRescan);
935 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400936 }
937 break;
938 case Token::SLASH:
939 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400940 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
941 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400942 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400943 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
944 } else {
945 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400946 // float4(x) / 1 -> float4(x)
947 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400948 delete_right(&b, iter, outUpdated, outNeedsRescan);
949 }
950 } else if (is_constant(*bin->fLeft, 0)) {
951 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500952 bin->fRight->fType.kind() == Type::kVector_Kind &&
953 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400954 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400955 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
956 } else {
957 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400958 // float4(0) / x -> float4(0)
959 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500960 if (!bin->fRight->hasSideEffects()) {
961 delete_right(&b, iter, outUpdated, outNeedsRescan);
962 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400963 }
964 }
965 break;
966 case Token::PLUSEQ:
967 if (is_constant(*bin->fRight, 0)) {
968 clear_write(*bin->fLeft);
969 delete_right(&b, iter, outUpdated, outNeedsRescan);
970 }
971 break;
972 case Token::MINUSEQ:
973 if (is_constant(*bin->fRight, 0)) {
974 clear_write(*bin->fLeft);
975 delete_right(&b, iter, outUpdated, outNeedsRescan);
976 }
977 break;
978 case Token::STAREQ:
979 if (is_constant(*bin->fRight, 1)) {
980 clear_write(*bin->fLeft);
981 delete_right(&b, iter, outUpdated, outNeedsRescan);
982 }
983 break;
984 case Token::SLASHEQ:
985 if (is_constant(*bin->fRight, 1)) {
986 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400987 delete_right(&b, iter, outUpdated, outNeedsRescan);
988 }
989 break;
990 default:
991 break;
992 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -0400993 break;
994 }
995 case Expression::kSwizzle_Kind: {
996 Swizzle& s = (Swizzle&) *expr;
997 // detect identity swizzles like foo.rgba
998 if ((int) s.fComponents.size() == s.fBase->fType.columns()) {
999 bool identity = true;
1000 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
1001 if (s.fComponents[i] != i) {
1002 identity = false;
1003 break;
1004 }
1005 }
1006 if (identity) {
1007 *outUpdated = true;
1008 if (!try_replace_expression(&b, iter, &s.fBase)) {
1009 *outNeedsRescan = true;
1010 return;
1011 }
1012 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1013 break;
1014 }
1015 }
1016 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
1017 if (s.fBase->fKind == Expression::kSwizzle_Kind) {
1018 Swizzle& base = (Swizzle&) *s.fBase;
1019 std::vector<int> final;
1020 for (int c : s.fComponents) {
1021 if (c == SKSL_SWIZZLE_0 || c == SKSL_SWIZZLE_1) {
1022 final.push_back(c);
1023 } else {
1024 final.push_back(base.fComponents[c]);
1025 }
1026 }
1027 *outUpdated = true;
1028 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1029 std::move(final)));
1030 if (!try_replace_expression(&b, iter, &replacement)) {
1031 *outNeedsRescan = true;
1032 return;
1033 }
1034 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1035 break;
1036 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001037 }
1038 default:
1039 break;
1040 }
1041}
1042
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001043// returns true if this statement could potentially execute a break at the current level (we ignore
1044// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
Ethan Nicholas5005a222018-08-24 13:06:27 -04001045static bool contains_conditional_break(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001046 switch (s.fKind) {
1047 case Statement::kBlock_Kind:
1048 for (const auto& sub : ((Block&) s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001049 if (contains_conditional_break(*sub, inConditional)) {
1050 return true;
1051 }
1052 }
1053 return false;
1054 case Statement::kBreak_Kind:
1055 return inConditional;
1056 case Statement::kIf_Kind: {
1057 const IfStatement& i = (IfStatement&) s;
1058 return contains_conditional_break(*i.fIfTrue, true) ||
1059 (i.fIfFalse && contains_conditional_break(*i.fIfFalse, true));
1060 }
1061 default:
1062 return false;
1063 }
1064}
1065
1066// returns true if this statement definitely executes a break at the current level (we ignore
1067// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
1068static bool contains_unconditional_break(Statement& s) {
1069 switch (s.fKind) {
1070 case Statement::kBlock_Kind:
1071 for (const auto& sub : ((Block&) s).fStatements) {
1072 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001073 return true;
1074 }
1075 }
1076 return false;
1077 case Statement::kBreak_Kind:
1078 return true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001079 default:
1080 return false;
1081 }
1082}
1083
1084// Returns a block containing all of the statements that will be run if the given case matches
1085// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1086// broken by this call and must then be discarded).
1087// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1088// when break statements appear inside conditionals.
1089static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
1090 bool capturing = false;
1091 std::vector<std::unique_ptr<Statement>*> statementPtrs;
1092 for (const auto& current : s->fCases) {
1093 if (current.get() == c) {
1094 capturing = true;
1095 }
1096 if (capturing) {
1097 for (auto& stmt : current->fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001098 if (contains_conditional_break(*stmt, s->fKind == Statement::kIf_Kind)) {
1099 return nullptr;
1100 }
1101 if (contains_unconditional_break(*stmt)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001102 capturing = false;
1103 break;
1104 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001105 statementPtrs.push_back(&stmt);
1106 }
1107 if (!capturing) {
1108 break;
1109 }
1110 }
1111 }
1112 std::vector<std::unique_ptr<Statement>> statements;
1113 for (const auto& s : statementPtrs) {
1114 statements.push_back(std::move(*s));
1115 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001116 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001117}
1118
Ethan Nicholascb670962017-04-20 19:31:52 -04001119void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001120 BasicBlock& b,
1121 std::vector<BasicBlock::Node>::iterator* iter,
1122 std::unordered_set<const Variable*>* undefinedVariables,
1123 bool* outUpdated,
1124 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001125 Statement* stmt = (*iter)->statement()->get();
1126 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001127 case Statement::kVarDeclaration_Kind: {
1128 const auto& varDecl = (VarDeclaration&) *stmt;
1129 if (varDecl.fVar->dead() &&
1130 (!varDecl.fValue ||
1131 !varDecl.fValue->hasSideEffects())) {
1132 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001133 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001134 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1135 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001136 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001137 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001138 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001139 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001140 }
1141 break;
1142 }
1143 case Statement::kIf_Kind: {
1144 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001145 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1146 // constant if, collapse down to a single branch
1147 if (((BoolLiteral&) *i.fTest).fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001148 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001149 (*iter)->setStatement(std::move(i.fIfTrue));
1150 } else {
1151 if (i.fIfFalse) {
1152 (*iter)->setStatement(std::move(i.fIfFalse));
1153 } else {
1154 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1155 }
1156 }
1157 *outUpdated = true;
1158 *outNeedsRescan = true;
1159 break;
1160 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001161 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1162 // else block doesn't do anything, remove it
1163 i.fIfFalse.reset();
1164 *outUpdated = true;
1165 *outNeedsRescan = true;
1166 }
1167 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1168 // if block doesn't do anything, no else block
1169 if (i.fTest->hasSideEffects()) {
1170 // test has side effects, keep it
1171 (*iter)->setStatement(std::unique_ptr<Statement>(
1172 new ExpressionStatement(std::move(i.fTest))));
1173 } else {
1174 // no if, no else, no test side effects, kill the whole if
1175 // statement
1176 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1177 }
1178 *outUpdated = true;
1179 *outNeedsRescan = true;
1180 }
1181 break;
1182 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001183 case Statement::kSwitch_Kind: {
1184 SwitchStatement& s = (SwitchStatement&) *stmt;
1185 if (s.fValue->isConstant()) {
1186 // switch is constant, replace it with the case that matches
1187 bool found = false;
1188 SwitchCase* defaultCase = nullptr;
1189 for (const auto& c : s.fCases) {
1190 if (!c->fValue) {
1191 defaultCase = c.get();
1192 continue;
1193 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001194 SkASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001195 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001196 if (found) {
1197 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1198 if (newBlock) {
1199 (*iter)->setStatement(std::move(newBlock));
1200 break;
1201 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001202 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001203 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001204 "static switch contains non-static conditional break");
1205 s.fIsStatic = false;
1206 }
1207 return; // can't simplify
1208 }
1209 }
1210 }
1211 if (!found) {
1212 // no matching case. use default if it exists, or kill the whole thing
1213 if (defaultCase) {
1214 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1215 if (newBlock) {
1216 (*iter)->setStatement(std::move(newBlock));
1217 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001218 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001219 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001220 "static switch contains non-static conditional break");
1221 s.fIsStatic = false;
1222 }
1223 return; // can't simplify
1224 }
1225 } else {
1226 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1227 }
1228 }
1229 *outUpdated = true;
1230 *outNeedsRescan = true;
1231 }
1232 break;
1233 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001234 case Statement::kExpression_Kind: {
1235 ExpressionStatement& e = (ExpressionStatement&) *stmt;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001236 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001237 if (!e.fExpression->hasSideEffects()) {
1238 // Expression statement with no side effects, kill it
1239 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1240 *outNeedsRescan = true;
1241 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001242 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001243 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1244 *outUpdated = true;
1245 }
1246 break;
1247 }
1248 default:
1249 break;
1250 }
1251}
1252
1253void Compiler::scanCFG(FunctionDefinition& f) {
1254 CFG cfg = CFGGenerator().getCFG(f);
1255 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001256
1257 // check for unreachable code
1258 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001259 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001260 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001261 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001262 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1263 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001264 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001265 break;
1266 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001267 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001268 break;
1269 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001270 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001271 }
1272 }
1273 if (fErrorCount) {
1274 return;
1275 }
1276
Ethan Nicholascb670962017-04-20 19:31:52 -04001277 // check for dead code & undefined variables, perform constant propagation
1278 std::unordered_set<const Variable*> undefinedVariables;
1279 bool updated;
1280 bool needsRescan = false;
1281 do {
1282 if (needsRescan) {
1283 cfg = CFGGenerator().getCFG(f);
1284 this->computeDataFlow(&cfg);
1285 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001286 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001287
1288 updated = false;
1289 for (BasicBlock& b : cfg.fBlocks) {
1290 DefinitionMap definitions = b.fBefore;
1291
1292 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1293 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1294 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1295 &needsRescan);
1296 } else {
1297 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1298 &needsRescan);
1299 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001300 if (needsRescan) {
1301 break;
1302 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001303 this->addDefinitions(*iter, &definitions);
1304 }
1305 }
1306 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001307 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001308
Ethan Nicholas91a10532017-06-22 11:24:38 -04001309 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001310 for (BasicBlock& b : cfg.fBlocks) {
1311 DefinitionMap definitions = b.fBefore;
1312
Ethan Nicholas91a10532017-06-22 11:24:38 -04001313 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001314 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1315 const Statement& s = **iter->statement();
1316 switch (s.fKind) {
1317 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001318 if (((const IfStatement&) s).fIsStatic &&
1319 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001320 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001321 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001322 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001323 break;
1324 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001325 if (((const SwitchStatement&) s).fIsStatic &&
1326 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001327 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001328 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001329 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001330 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001331 case Statement::kVarDeclarations_Kind: {
1332 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1333 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1334 if ((*varIter)->fKind == Statement::kNop_Kind) {
1335 varIter = decls.fVars.erase(varIter);
1336 } else {
1337 ++varIter;
1338 }
1339 }
1340 if (!decls.fVars.size()) {
1341 iter = b.fNodes.erase(iter);
1342 } else {
1343 ++iter;
1344 }
1345 break;
1346 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001347 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001348 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001349 break;
1350 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001351 } else {
1352 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001353 }
1354 }
1355 }
1356
ethannicholas22f939e2016-10-13 13:25:34 -07001357 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001358 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001359 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001360 this->error(f.fOffset, String("function '" + String(f.fDeclaration.fName) +
1361 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001362 }
1363 }
1364}
1365
Ethan Nicholas91164d12019-05-15 15:29:54 -04001366void Compiler::registerExternalValue(ExternalValue* value) {
1367 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1368}
1369
1370Symbol* Compiler::takeOwnership(std::unique_ptr<Symbol> symbol) {
1371 return fIRGenerator->fRootSymbolTable->takeOwnership(std::move(symbol));
1372}
1373
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001374std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001375 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001376 fErrorText = "";
1377 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001378 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001379 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001380 switch (kind) {
1381 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001382 inherited = &fVertexInclude;
1383 fIRGenerator->fSymbolTable = fVertexSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001384 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001385 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001386 break;
1387 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001388 inherited = &fFragmentInclude;
1389 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001390 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001391 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001392 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001393 case Program::kGeometry_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001394 inherited = &fGeometryInclude;
1395 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001396 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001397 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001398 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001399 case Program::kFragmentProcessor_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001400 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001401 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001402 fIRGenerator->start(&settings, nullptr);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001403 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Robert Phillipsfe8da172018-01-24 14:52:02 +00001404 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001405 &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001406 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001407 break;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001408 case Program::kPipelineStage_Kind:
1409 inherited = &fPipelineInclude;
1410 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001411 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001412 fIRGenerator->start(&settings, inherited);
1413 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001414 case Program::kGeneric_Kind:
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001415 inherited = &fInterpreterInclude;
1416 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001417 fIRGenerator->fIntrinsics = &fInterpreterIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001418 fIRGenerator->start(&settings, inherited);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001419 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001420 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001421 for (auto& element : elements) {
1422 if (element->fKind == ProgramElement::kEnum_Kind) {
1423 ((Enum&) *element).fBuiltin = true;
1424 }
1425 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001426 std::unique_ptr<String> textPtr(new String(std::move(text)));
1427 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001428 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001429 auto result = std::unique_ptr<Program>(new Program(kind,
1430 std::move(textPtr),
1431 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001432 fContext,
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001433 inherited,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001434 std::move(elements),
1435 fIRGenerator->fSymbolTable,
1436 fIRGenerator->fInputs));
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001437 if (fErrorCount) {
1438 return nullptr;
1439 }
1440 return result;
1441}
1442
Ethan Nicholas00543112018-07-31 09:44:36 -04001443bool Compiler::optimize(Program& program) {
1444 SkASSERT(!fErrorCount);
1445 if (!program.fIsOptimized) {
1446 program.fIsOptimized = true;
1447 fIRGenerator->fKind = program.fKind;
1448 fIRGenerator->fSettings = &program.fSettings;
1449 for (auto& element : program) {
1450 if (element.fKind == ProgramElement::kFunction_Kind) {
1451 this->scanCFG((FunctionDefinition&) element);
1452 }
1453 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001454 if (program.fKind != Program::kFragmentProcessor_Kind) {
1455 for (auto iter = program.fElements.begin(); iter != program.fElements.end();) {
1456 if ((*iter)->fKind == ProgramElement::kVar_Kind) {
1457 VarDeclarations& vars = (VarDeclarations&) **iter;
1458 for (auto varIter = vars.fVars.begin(); varIter != vars.fVars.end();) {
1459 const Variable& var = *((VarDeclaration&) **varIter).fVar;
1460 if (var.dead()) {
1461 varIter = vars.fVars.erase(varIter);
1462 } else {
1463 ++varIter;
1464 }
1465 }
1466 if (vars.fVars.size() == 0) {
1467 iter = program.fElements.erase(iter);
1468 continue;
1469 }
1470 }
1471 ++iter;
1472 }
1473 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001474 }
1475 return fErrorCount == 0;
1476}
1477
1478std::unique_ptr<Program> Compiler::specialize(
1479 Program& program,
1480 const std::unordered_map<SkSL::String, SkSL::Program::Settings::Value>& inputs) {
1481 std::vector<std::unique_ptr<ProgramElement>> elements;
1482 for (const auto& e : program) {
1483 elements.push_back(e.clone());
1484 }
1485 Program::Settings settings;
1486 settings.fCaps = program.fSettings.fCaps;
1487 for (auto iter = inputs.begin(); iter != inputs.end(); ++iter) {
1488 settings.fArgs.insert(*iter);
1489 }
Brian Osman808f0212020-01-21 15:36:47 -05001490 std::unique_ptr<String> sourceCopy(new String(*program.fSource));
Ethan Nicholas00543112018-07-31 09:44:36 -04001491 std::unique_ptr<Program> result(new Program(program.fKind,
Brian Osman808f0212020-01-21 15:36:47 -05001492 std::move(sourceCopy),
Ethan Nicholas00543112018-07-31 09:44:36 -04001493 settings,
1494 program.fContext,
1495 program.fInheritedElements,
1496 std::move(elements),
1497 program.fSymbols,
1498 program.fInputs));
1499 return result;
1500}
1501
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001502#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1503
Ethan Nicholas00543112018-07-31 09:44:36 -04001504bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1505 if (!this->optimize(program)) {
1506 return false;
1507 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001508#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001509 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001510 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001511 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001512 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001513 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001514 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001515 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001516 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001517 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001518 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1519 SkDebugf("SPIR-V validation error: %s\n", m);
1520 };
1521 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001522 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001523 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001524 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001525 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001526 }
1527#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001528 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001529 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001530 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001531 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001532#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001533 return result;
1534}
1535
Ethan Nicholas00543112018-07-31 09:44:36 -04001536bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001537 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001538 bool result = this->toSPIRV(program, buffer);
1539 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001540 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001541 }
1542 return result;
1543}
1544
Ethan Nicholas00543112018-07-31 09:44:36 -04001545bool Compiler::toGLSL(Program& program, OutputStream& out) {
1546 if (!this->optimize(program)) {
1547 return false;
1548 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001549 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001550 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001551 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001552 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001553 return result;
1554}
1555
Ethan Nicholas00543112018-07-31 09:44:36 -04001556bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001557 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001558 bool result = this->toGLSL(program, buffer);
1559 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001560 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001561 }
1562 return result;
1563}
1564
Ethan Nicholas00543112018-07-31 09:44:36 -04001565bool Compiler::toMetal(Program& program, OutputStream& out) {
1566 if (!this->optimize(program)) {
1567 return false;
1568 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001569 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001570 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001571 return result;
1572}
1573
Ethan Nicholas00543112018-07-31 09:44:36 -04001574bool Compiler::toMetal(Program& program, String* out) {
1575 if (!this->optimize(program)) {
1576 return false;
1577 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001578 StringStream buffer;
1579 bool result = this->toMetal(program, buffer);
1580 if (result) {
1581 *out = buffer.str();
1582 }
1583 return result;
1584}
1585
Ethan Nicholas00543112018-07-31 09:44:36 -04001586bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1587 if (!this->optimize(program)) {
1588 return false;
1589 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001590 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001591 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001592 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001593 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001594 return result;
1595}
1596
Ethan Nicholas00543112018-07-31 09:44:36 -04001597bool Compiler::toH(Program& program, String name, OutputStream& out) {
1598 if (!this->optimize(program)) {
1599 return false;
1600 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001601 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001602 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001603 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001604 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001605 return result;
1606}
1607
Brian Osman2e29ab52019-09-20 12:19:11 -04001608#endif
1609
1610#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osman107c6662019-12-30 15:02:30 -05001611bool Compiler::toPipelineStage(const Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001612 SkASSERT(program.fIsOptimized);
1613 fSource = program.fSource.get();
1614 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001615 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001616 bool result = cg.generateCode();
1617 fSource = nullptr;
1618 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001619 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001620 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001621 return result;
1622}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001623#endif
1624
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001625std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Brian Osman489cf882019-07-09 10:48:28 -04001626#if defined(SK_ENABLE_SKSL_INTERPRETER)
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001627 if (!this->optimize(program)) {
1628 return nullptr;
1629 }
Brian Osman808f0212020-01-21 15:36:47 -05001630 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001631 std::unique_ptr<ByteCode> result(new ByteCode());
Ethan Nicholasb962eff2020-01-23 16:49:41 -05001632 ByteCodeGenerator cg(&program, this, result.get());
1633 if (cg.generateCode()) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001634 return result;
1635 }
Brian Osman489cf882019-07-09 10:48:28 -04001636#else
1637 ABORT("ByteCode interpreter not enabled");
1638#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001639 return nullptr;
1640}
1641
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001642const char* Compiler::OperatorName(Token::Kind kind) {
1643 switch (kind) {
1644 case Token::PLUS: return "+";
1645 case Token::MINUS: return "-";
1646 case Token::STAR: return "*";
1647 case Token::SLASH: return "/";
1648 case Token::PERCENT: return "%";
1649 case Token::SHL: return "<<";
1650 case Token::SHR: return ">>";
1651 case Token::LOGICALNOT: return "!";
1652 case Token::LOGICALAND: return "&&";
1653 case Token::LOGICALOR: return "||";
1654 case Token::LOGICALXOR: return "^^";
1655 case Token::BITWISENOT: return "~";
1656 case Token::BITWISEAND: return "&";
1657 case Token::BITWISEOR: return "|";
1658 case Token::BITWISEXOR: return "^";
1659 case Token::EQ: return "=";
1660 case Token::EQEQ: return "==";
1661 case Token::NEQ: return "!=";
1662 case Token::LT: return "<";
1663 case Token::GT: return ">";
1664 case Token::LTEQ: return "<=";
1665 case Token::GTEQ: return ">=";
1666 case Token::PLUSEQ: return "+=";
1667 case Token::MINUSEQ: return "-=";
1668 case Token::STAREQ: return "*=";
1669 case Token::SLASHEQ: return "/=";
1670 case Token::PERCENTEQ: return "%=";
1671 case Token::SHLEQ: return "<<=";
1672 case Token::SHREQ: return ">>=";
1673 case Token::LOGICALANDEQ: return "&&=";
1674 case Token::LOGICALOREQ: return "||=";
1675 case Token::LOGICALXOREQ: return "^^=";
1676 case Token::BITWISEANDEQ: return "&=";
1677 case Token::BITWISEOREQ: return "|=";
1678 case Token::BITWISEXOREQ: return "^=";
1679 case Token::PLUSPLUS: return "++";
1680 case Token::MINUSMINUS: return "--";
1681 case Token::COMMA: return ",";
1682 default:
1683 ABORT("unsupported operator: %d\n", kind);
1684 }
1685}
1686
1687
1688bool Compiler::IsAssignment(Token::Kind op) {
1689 switch (op) {
1690 case Token::EQ: // fall through
1691 case Token::PLUSEQ: // fall through
1692 case Token::MINUSEQ: // fall through
1693 case Token::STAREQ: // fall through
1694 case Token::SLASHEQ: // fall through
1695 case Token::PERCENTEQ: // fall through
1696 case Token::SHLEQ: // fall through
1697 case Token::SHREQ: // fall through
1698 case Token::BITWISEOREQ: // fall through
1699 case Token::BITWISEXOREQ: // fall through
1700 case Token::BITWISEANDEQ: // fall through
1701 case Token::LOGICALOREQ: // fall through
1702 case Token::LOGICALXOREQ: // fall through
1703 case Token::LOGICALANDEQ:
1704 return true;
1705 default:
1706 return false;
1707 }
1708}
1709
1710Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001711 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001712 int line = 1;
1713 int column = 1;
1714 for (int i = 0; i < offset; i++) {
1715 if ((*fSource)[i] == '\n') {
1716 ++line;
1717 column = 1;
1718 }
1719 else {
1720 ++column;
1721 }
1722 }
1723 return Position(line, column);
1724}
1725
1726void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001727 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001728 Position pos = this->position(offset);
1729 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001730}
1731
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001732String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001733 this->writeErrorCount();
1734 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001735 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001736 return result;
1737}
1738
1739void Compiler::writeErrorCount() {
1740 if (fErrorCount) {
1741 fErrorText += to_string(fErrorCount) + " error";
1742 if (fErrorCount > 1) {
1743 fErrorText += "s";
1744 }
1745 fErrorText += "\n";
1746 }
1747}
1748
ethannicholasb3058bd2016-07-01 08:22:01 -07001749} // namespace