blob: 5d2571c77a357db6f8ad3f13b4a30a1137cba363 [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"
Brian Osmanc0243912020-02-19 15:35:26 -050019#include "src/sksl/SkSLSPIRVtoHLSL.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050020#include "src/sksl/ir/SkSLEnum.h"
21#include "src/sksl/ir/SkSLExpression.h"
22#include "src/sksl/ir/SkSLExpressionStatement.h"
23#include "src/sksl/ir/SkSLFunctionCall.h"
24#include "src/sksl/ir/SkSLIntLiteral.h"
25#include "src/sksl/ir/SkSLModifiersDeclaration.h"
26#include "src/sksl/ir/SkSLNop.h"
27#include "src/sksl/ir/SkSLSymbolTable.h"
28#include "src/sksl/ir/SkSLTernaryExpression.h"
29#include "src/sksl/ir/SkSLUnresolvedFunction.h"
30#include "src/sksl/ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070031
Ethan Nicholasa11035b2019-11-26 16:27:47 -050032#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
33#include "include/gpu/GrContextOptions.h"
34#include "src/gpu/GrShaderCaps.h"
35#endif
36
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040037#ifdef SK_ENABLE_SPIRV_VALIDATION
38#include "spirv-tools/libspirv.hpp"
39#endif
40
ethannicholasb3058bd2016-07-01 08:22:01 -070041// include the built-in shader symbols as static strings
42
Ethan Nicholas79707652017-11-16 11:20:11 -050043#define STRINGIFY(x) #x
44
Ethan Nicholas8da1e652019-05-24 11:01:59 -040045static const char* SKSL_GPU_INCLUDE =
46#include "sksl_gpu.inc"
47;
48
Brian Salomonf8c187c2019-12-19 14:41:57 -050049static const char* SKSL_BLEND_INCLUDE =
50#include "sksl_blend.inc"
51;
52
Ethan Nicholas8da1e652019-05-24 11:01:59 -040053static const char* SKSL_INTERP_INCLUDE =
54#include "sksl_interp.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070055;
56
ethannicholas5961bc92016-10-12 06:39:56 -070057static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050058#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070059;
60
ethannicholas5961bc92016-10-12 06:39:56 -070061static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050062#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070063;
64
Ethan Nicholas52cad152017-02-16 16:37:32 -050065static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050066#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050067;
68
Ethan Nicholas762466e2017-06-29 10:03:38 -040069static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050070#include "sksl_enums.inc"
71#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040072;
73
Ethan Nicholas8da1e652019-05-24 11:01:59 -040074static const char* SKSL_PIPELINE_INCLUDE =
75#include "sksl_pipeline.inc"
Ethan Nicholas0d997662019-04-08 09:46:01 -040076;
77
ethannicholasb3058bd2016-07-01 08:22:01 -070078namespace SkSL {
79
Ethan Nicholasdb80f692019-11-22 14:06:12 -050080static void grab_intrinsics(std::vector<std::unique_ptr<ProgramElement>>* src,
Brian Osman08f986d2020-05-13 17:06:46 -040081 std::map<String, std::pair<std::unique_ptr<ProgramElement>, bool>>* target) {
82 for (auto iter = src->begin(); iter != src->end(); ) {
83 std::unique_ptr<ProgramElement>& element = *iter;
Ethan Nicholasdb80f692019-11-22 14:06:12 -050084 switch (element->fKind) {
85 case ProgramElement::kFunction_Kind: {
86 FunctionDefinition& f = (FunctionDefinition&) *element;
Brian Osman08f986d2020-05-13 17:06:46 -040087 SkASSERT(f.fDeclaration.fBuiltin);
88 String key = f.fDeclaration.declaration();
89 SkASSERT(target->find(key) == target->end());
90 (*target)[key] = std::make_pair(std::move(element), false);
91 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050092 break;
93 }
94 case ProgramElement::kEnum_Kind: {
95 Enum& e = (Enum&) *element;
96 StringFragment name = e.fTypeName;
97 SkASSERT(target->find(name) == target->end());
98 (*target)[name] = std::make_pair(std::move(element), false);
Brian Osman08f986d2020-05-13 17:06:46 -040099 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500100 break;
101 }
102 default:
103 printf("unsupported include file element\n");
104 SkASSERT(false);
105 }
106 }
107}
108
109
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400110Compiler::Compiler(Flags flags)
111: fFlags(flags)
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400112, fContext(new Context())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400113, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -0400114 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
115 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400116 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700117 fTypes = types;
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400118 #define ADD_TYPE(t) types->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
119 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700120 ADD_TYPE(Void);
121 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400122 ADD_TYPE(Float2);
123 ADD_TYPE(Float3);
124 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400125 ADD_TYPE(Half);
126 ADD_TYPE(Half2);
127 ADD_TYPE(Half3);
128 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700129 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400130 ADD_TYPE(Int2);
131 ADD_TYPE(Int3);
132 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700133 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400134 ADD_TYPE(UInt2);
135 ADD_TYPE(UInt3);
136 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400137 ADD_TYPE(Short);
138 ADD_TYPE(Short2);
139 ADD_TYPE(Short3);
140 ADD_TYPE(Short4);
141 ADD_TYPE(UShort);
142 ADD_TYPE(UShort2);
143 ADD_TYPE(UShort3);
144 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400145 ADD_TYPE(Byte);
146 ADD_TYPE(Byte2);
147 ADD_TYPE(Byte3);
148 ADD_TYPE(Byte4);
149 ADD_TYPE(UByte);
150 ADD_TYPE(UByte2);
151 ADD_TYPE(UByte3);
152 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700153 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400154 ADD_TYPE(Bool2);
155 ADD_TYPE(Bool3);
156 ADD_TYPE(Bool4);
157 ADD_TYPE(Float2x2);
158 ADD_TYPE(Float2x3);
159 ADD_TYPE(Float2x4);
160 ADD_TYPE(Float3x2);
161 ADD_TYPE(Float3x3);
162 ADD_TYPE(Float3x4);
163 ADD_TYPE(Float4x2);
164 ADD_TYPE(Float4x3);
165 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400166 ADD_TYPE(Half2x2);
167 ADD_TYPE(Half2x3);
168 ADD_TYPE(Half2x4);
169 ADD_TYPE(Half3x2);
170 ADD_TYPE(Half3x3);
171 ADD_TYPE(Half3x4);
172 ADD_TYPE(Half4x2);
173 ADD_TYPE(Half4x3);
174 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700175 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400176 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700177 ADD_TYPE(GenIType);
178 ADD_TYPE(GenUType);
179 ADD_TYPE(GenBType);
180 ADD_TYPE(Mat);
181 ADD_TYPE(Vec);
182 ADD_TYPE(GVec);
183 ADD_TYPE(GVec2);
184 ADD_TYPE(GVec3);
185 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400186 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700187 ADD_TYPE(IVec);
188 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400189 ADD_TYPE(SVec);
190 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400191 ADD_TYPE(ByteVec);
192 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700193 ADD_TYPE(BVec);
194
195 ADD_TYPE(Sampler1D);
196 ADD_TYPE(Sampler2D);
197 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700198 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700199 ADD_TYPE(SamplerCube);
200 ADD_TYPE(Sampler2DRect);
201 ADD_TYPE(Sampler1DArray);
202 ADD_TYPE(Sampler2DArray);
203 ADD_TYPE(SamplerCubeArray);
204 ADD_TYPE(SamplerBuffer);
205 ADD_TYPE(Sampler2DMS);
206 ADD_TYPE(Sampler2DMSArray);
207
Brian Salomonbf7b6202016-11-11 16:08:03 -0500208 ADD_TYPE(ISampler2D);
209
Brian Salomon2a51de82016-11-16 12:06:01 -0500210 ADD_TYPE(Image2D);
211 ADD_TYPE(IImage2D);
212
Greg Daniel64773e62016-11-22 09:44:03 -0500213 ADD_TYPE(SubpassInput);
214 ADD_TYPE(SubpassInputMS);
215
ethannicholasb3058bd2016-07-01 08:22:01 -0700216 ADD_TYPE(GSampler1D);
217 ADD_TYPE(GSampler2D);
218 ADD_TYPE(GSampler3D);
219 ADD_TYPE(GSamplerCube);
220 ADD_TYPE(GSampler2DRect);
221 ADD_TYPE(GSampler1DArray);
222 ADD_TYPE(GSampler2DArray);
223 ADD_TYPE(GSamplerCubeArray);
224 ADD_TYPE(GSamplerBuffer);
225 ADD_TYPE(GSampler2DMS);
226 ADD_TYPE(GSampler2DMSArray);
227
228 ADD_TYPE(Sampler1DShadow);
229 ADD_TYPE(Sampler2DShadow);
230 ADD_TYPE(SamplerCubeShadow);
231 ADD_TYPE(Sampler2DRectShadow);
232 ADD_TYPE(Sampler1DArrayShadow);
233 ADD_TYPE(Sampler2DArrayShadow);
234 ADD_TYPE(SamplerCubeArrayShadow);
235 ADD_TYPE(GSampler2DArrayShadow);
236 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400237 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400238 ADD_TYPE(Sampler);
239 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700240
Brian Osman28590d52020-03-23 16:59:08 -0400241 StringFragment fpAliasName("shader");
242 fTypes->addWithoutOwnership(fpAliasName, fContext->fFragmentProcessor_Type.get());
243
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700244 StringFragment skCapsName("sk_Caps");
245 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400246 *fContext->fSkCaps_Type, Variable::kGlobal_Storage);
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500247 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
248
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700249 StringFragment skArgsName("sk_Args");
250 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400251 *fContext->fSkArgs_Type, Variable::kGlobal_Storage);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400252 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
253
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500254 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
255 std::vector<std::unique_ptr<ProgramElement>> gpuIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400256 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, strlen(SKSL_GPU_INCLUDE),
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500257 symbols, &gpuIntrinsics, &fGpuSymbolTable);
Brian Salomonf8c187c2019-12-19 14:41:57 -0500258 this->processIncludeFile(Program::kFragment_Kind, SKSL_BLEND_INCLUDE,
259 strlen(SKSL_BLEND_INCLUDE), std::move(fGpuSymbolTable), &gpuIntrinsics,
260 &fGpuSymbolTable);
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500261 grab_intrinsics(&gpuIntrinsics, &fGPUIntrinsics);
262 // need to hang on to the source so that FunctionDefinition.fSource pointers in this file
263 // remain valid
264 fGpuIncludeSource = std::move(fIRGenerator->fFile);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400265 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, strlen(SKSL_VERT_INCLUDE),
266 fGpuSymbolTable, &fVertexInclude, &fVertexSymbolTable);
267 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, strlen(SKSL_FRAG_INCLUDE),
268 fGpuSymbolTable, &fFragmentInclude, &fFragmentSymbolTable);
269 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, strlen(SKSL_GEOM_INCLUDE),
270 fGpuSymbolTable, &fGeometryInclude, &fGeometrySymbolTable);
271 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
272 strlen(SKSL_PIPELINE_INCLUDE), fGpuSymbolTable, &fPipelineInclude,
273 &fPipelineSymbolTable);
Brian Osmanb08cc022020-04-02 11:38:40 -0400274 std::vector<std::unique_ptr<ProgramElement>> interpIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400275 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
276 strlen(SKSL_INTERP_INCLUDE), symbols, &fInterpreterInclude,
277 &fInterpreterSymbolTable);
Brian Osmanb08cc022020-04-02 11:38:40 -0400278 grab_intrinsics(&interpIntrinsics, &fInterpreterIntrinsics);
ethannicholasb3058bd2016-07-01 08:22:01 -0700279}
280
281Compiler::~Compiler() {
282 delete fIRGenerator;
283}
284
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400285void Compiler::processIncludeFile(Program::Kind kind, const char* src, size_t length,
286 std::shared_ptr<SymbolTable> base,
287 std::vector<std::unique_ptr<ProgramElement>>* outElements,
288 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500289#ifdef SK_DEBUG
290 String source(src, length);
291 fSource = &source;
292#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400293 fIRGenerator->fSymbolTable = std::move(base);
294 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500295#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
296 GrContextOptions opts;
297 GrShaderCaps caps(opts);
298 settings.fCaps = &caps;
299#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400300 fIRGenerator->start(&settings, nullptr);
301 fIRGenerator->convertProgram(kind, src, length, *fTypes, outElements);
302 if (this->fErrorCount) {
303 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
304 }
305 SkASSERT(!fErrorCount);
306 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
307 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500308#ifdef SK_DEBUG
309 fSource = nullptr;
310#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400311}
312
ethannicholas22f939e2016-10-13 13:25:34 -0700313// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500314void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
315 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700316 switch (lvalue->fKind) {
317 case Expression::kVariableReference_Kind: {
318 const Variable& var = ((VariableReference*) lvalue)->fVariable;
319 if (var.fStorage == Variable::kLocal_Storage) {
320 (*definitions)[&var] = expr;
321 }
322 break;
323 }
324 case Expression::kSwizzle_Kind:
325 // We consider the variable written to as long as at least some of its components have
326 // been written to. This will lead to some false negatives (we won't catch it if you
327 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400328 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
329 // 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 -0700330 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400331 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400332 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700333 definitions);
334 break;
335 case Expression::kIndex_Kind:
336 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400337 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400338 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700339 definitions);
340 break;
341 case Expression::kFieldAccess_Kind:
342 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400343 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400344 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700345 definitions);
346 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500347 case Expression::kTernary_Kind:
348 // To simplify analysis, we just pretend that we write to both sides of the ternary.
349 // This allows for false positives (meaning we fail to detect that a variable might not
350 // have been assigned), but is preferable to false negatives.
351 this->addDefinition(((TernaryExpression*) lvalue)->fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400352 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500353 definitions);
354 this->addDefinition(((TernaryExpression*) lvalue)->fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400355 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500356 definitions);
357 break;
Ethan Nicholas91164d12019-05-15 15:29:54 -0400358 case Expression::kExternalValue_Kind:
359 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700360 default:
361 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400362 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700363 }
364}
365
366// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400367void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500368 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700369 switch (node.fKind) {
370 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400371 SkASSERT(node.expression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400372 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500373 switch (expr->fKind) {
374 case Expression::kBinary_Kind: {
375 BinaryExpression* b = (BinaryExpression*) expr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400376 if (b->fOperator == Token::Kind::TK_EQ) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500377 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700378 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500379 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400380 b->fLeft.get(),
381 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
382 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500383
384 }
385 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700386 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400387 case Expression::kFunctionCall_Kind: {
388 const FunctionCall& c = (const FunctionCall&) *expr;
389 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
390 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
391 this->addDefinition(
392 c.fArguments[i].get(),
393 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
394 definitions);
395 }
396 }
397 break;
398 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500399 case Expression::kPrefix_Kind: {
400 const PrefixExpression* p = (PrefixExpression*) expr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400401 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
402 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500403 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400404 p->fOperand.get(),
405 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
406 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500407 }
408 break;
409 }
410 case Expression::kPostfix_Kind: {
411 const PostfixExpression* p = (PostfixExpression*) expr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400412 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
413 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500414 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400415 p->fOperand.get(),
416 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
417 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500418 }
419 break;
420 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400421 case Expression::kVariableReference_Kind: {
422 const VariableReference* v = (VariableReference*) expr;
423 if (v->fRefKind != VariableReference::kRead_RefKind) {
424 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400425 v,
426 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
427 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400428 }
429 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500430 default:
431 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700432 }
433 break;
434 }
435 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400436 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000437 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
438 VarDeclaration& vd = (VarDeclaration&) *stmt;
439 if (vd.fValue) {
440 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700441 }
442 }
443 break;
444 }
445 }
446}
447
448void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
449 BasicBlock& block = cfg->fBlocks[blockId];
450
451 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500452 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700453 for (const BasicBlock::Node& n : block.fNodes) {
454 this->addDefinitions(n, &after);
455 }
456
457 // propagate definitions to exits
458 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400459 if (exitId == blockId) {
460 continue;
461 }
ethannicholas22f939e2016-10-13 13:25:34 -0700462 BasicBlock& exit = cfg->fBlocks[exitId];
463 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500464 std::unique_ptr<Expression>* e1 = pair.second;
465 auto found = exit.fBefore.find(pair.first);
466 if (found == exit.fBefore.end()) {
467 // exit has no definition for it, just copy it
468 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700469 exit.fBefore[pair.first] = e1;
470 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500471 // exit has a (possibly different) value already defined
472 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700473 if (e1 != e2) {
474 // definition has changed, merge and add exit block to worklist
475 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500476 if (e1 && e2) {
477 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400478 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500479 } else {
480 exit.fBefore[pair.first] = nullptr;
481 }
ethannicholas22f939e2016-10-13 13:25:34 -0700482 }
483 }
484 }
485 }
486}
487
488// returns a map which maps all local variables in the function to null, indicating that their value
489// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500490static DefinitionMap compute_start_state(const CFG& cfg) {
491 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400492 for (const auto& block : cfg.fBlocks) {
493 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700494 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400495 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400496 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700497 if (s->fKind == Statement::kVarDeclarations_Kind) {
498 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000499 for (const auto& decl : vd->fDeclaration->fVars) {
500 if (decl->fKind == Statement::kVarDeclaration_Kind) {
501 result[((VarDeclaration&) *decl).fVar] = nullptr;
502 }
Mike Klein6ad99092016-10-26 10:35:22 -0400503 }
ethannicholas22f939e2016-10-13 13:25:34 -0700504 }
505 }
506 }
507 }
508 return result;
509}
510
Ethan Nicholascb670962017-04-20 19:31:52 -0400511/**
512 * Returns true if assigning to this lvalue has no effect.
513 */
514static bool is_dead(const Expression& lvalue) {
515 switch (lvalue.fKind) {
516 case Expression::kVariableReference_Kind:
517 return ((VariableReference&) lvalue).fVariable.dead();
518 case Expression::kSwizzle_Kind:
519 return is_dead(*((Swizzle&) lvalue).fBase);
520 case Expression::kFieldAccess_Kind:
521 return is_dead(*((FieldAccess&) lvalue).fBase);
522 case Expression::kIndex_Kind: {
523 const IndexExpression& idx = (IndexExpression&) lvalue;
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500524 return is_dead(*idx.fBase) &&
525 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400526 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500527 case Expression::kTernary_Kind: {
528 const TernaryExpression& t = (TernaryExpression&) lvalue;
529 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
530 }
Ethan Nicholas91164d12019-05-15 15:29:54 -0400531 case Expression::kExternalValue_Kind:
532 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400533 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500534#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400535 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500536#endif
537 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400538 }
539}
ethannicholas22f939e2016-10-13 13:25:34 -0700540
Ethan Nicholascb670962017-04-20 19:31:52 -0400541/**
542 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
543 * to a dead target and lack of side effects on the left hand side.
544 */
545static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700546 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400547 return false;
548 }
549 return is_dead(*b.fLeft);
550}
551
552void Compiler::computeDataFlow(CFG* cfg) {
553 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700554 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400555 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700556 workList.insert(i);
557 }
558 while (workList.size()) {
559 BlockId next = *workList.begin();
560 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400561 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700562 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400563}
564
565/**
566 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
567 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
568 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
569 * need to be regenerated).
570 */
571bool try_replace_expression(BasicBlock* b,
572 std::vector<BasicBlock::Node>::iterator* iter,
573 std::unique_ptr<Expression>* newExpression) {
574 std::unique_ptr<Expression>* target = (*iter)->expression();
575 if (!b->tryRemoveExpression(iter)) {
576 *target = std::move(*newExpression);
577 return false;
578 }
579 *target = std::move(*newExpression);
580 return b->tryInsertExpression(iter, target);
581}
582
583/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400584 * Returns true if the expression is a constant numeric literal with the specified value, or a
585 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400586 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400587bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400588 switch (expr.fKind) {
589 case Expression::kIntLiteral_Kind:
590 return ((IntLiteral&) expr).fValue == value;
591 case Expression::kFloatLiteral_Kind:
592 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400593 case Expression::kConstructor_Kind: {
594 Constructor& c = (Constructor&) expr;
Ethan Nicholasd188c182019-06-10 15:55:38 -0400595 bool isFloat = c.fType.columns() > 1 ? c.fType.componentType().isFloat()
596 : c.fType.isFloat();
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400597 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
598 for (int i = 0; i < c.fType.columns(); ++i) {
Ethan Nicholasd188c182019-06-10 15:55:38 -0400599 if (isFloat) {
600 if (c.getFVecComponent(i) != value) {
601 return false;
602 }
603 } else if (c.getIVecComponent(i) != value) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400604 return false;
605 }
606 }
607 return true;
608 }
609 return false;
610 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400611 default:
612 return false;
613 }
614}
615
616/**
617 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
618 * and CFG structures).
619 */
620void delete_left(BasicBlock* b,
621 std::vector<BasicBlock::Node>::iterator* iter,
622 bool* outUpdated,
623 bool* outNeedsRescan) {
624 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400625 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400626 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400627 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400628 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400629 bool result;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400630 if (bin.fOperator == Token::Kind::TK_EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400631 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400632 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400633 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400634 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400635 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400636 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400637 *outNeedsRescan = true;
638 return;
639 }
640 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400641 *outNeedsRescan = true;
642 return;
643 }
644 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400645 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
646 (*iter)->expression() != &bin.fRight) {
647 *outNeedsRescan = true;
648 return;
649 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400650 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400651 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400652}
653
654/**
655 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
656 * CFG structures).
657 */
658void delete_right(BasicBlock* b,
659 std::vector<BasicBlock::Node>::iterator* iter,
660 bool* outUpdated,
661 bool* outNeedsRescan) {
662 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400663 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400664 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400665 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400666 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400667 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
668 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400669 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400670 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400671 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400672 *target = std::move(bin.fLeft);
673 if (*iter == b->fNodes.begin()) {
674 *outNeedsRescan = true;
675 return;
676 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400677 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400678 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
679 (*iter)->expression() != &bin.fLeft)) {
680 *outNeedsRescan = true;
681 return;
682 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400683 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400684 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400685}
686
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400687/**
688 * Constructs the specified type using a single argument.
689 */
690static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
691 std::vector<std::unique_ptr<Expression>> args;
692 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700693 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400694 return result;
695}
696
697/**
698 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
699 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
700 */
701static void vectorize(BasicBlock* b,
702 std::vector<BasicBlock::Node>::iterator* iter,
703 const Type& type,
704 std::unique_ptr<Expression>* otherExpression,
705 bool* outUpdated,
706 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400707 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
708 SkASSERT(type.kind() == Type::kVector_Kind);
709 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400710 *outUpdated = true;
711 std::unique_ptr<Expression>* target = (*iter)->expression();
712 if (!b->tryRemoveExpression(iter)) {
713 *target = construct(type, std::move(*otherExpression));
714 *outNeedsRescan = true;
715 } else {
716 *target = construct(type, std::move(*otherExpression));
717 if (!b->tryInsertExpression(iter, target)) {
718 *outNeedsRescan = true;
719 }
720 }
721}
722
723/**
724 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
725 * left to yield vec<n>(x).
726 */
727static void vectorize_left(BasicBlock* b,
728 std::vector<BasicBlock::Node>::iterator* iter,
729 bool* outUpdated,
730 bool* outNeedsRescan) {
731 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
732 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
733}
734
735/**
736 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
737 * right to yield vec<n>(y).
738 */
739static void vectorize_right(BasicBlock* b,
740 std::vector<BasicBlock::Node>::iterator* iter,
741 bool* outUpdated,
742 bool* outNeedsRescan) {
743 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
744 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
745}
746
747// Mark that an expression which we were writing to is no longer being written to
748void clear_write(const Expression& expr) {
749 switch (expr.fKind) {
750 case Expression::kVariableReference_Kind: {
751 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
752 break;
753 }
754 case Expression::kFieldAccess_Kind:
755 clear_write(*((FieldAccess&) expr).fBase);
756 break;
757 case Expression::kSwizzle_Kind:
758 clear_write(*((Swizzle&) expr).fBase);
759 break;
760 case Expression::kIndex_Kind:
761 clear_write(*((IndexExpression&) expr).fBase);
762 break;
763 default:
764 ABORT("shouldn't be writing to this kind of expression\n");
765 break;
766 }
767}
768
Ethan Nicholascb670962017-04-20 19:31:52 -0400769void Compiler::simplifyExpression(DefinitionMap& definitions,
770 BasicBlock& b,
771 std::vector<BasicBlock::Node>::iterator* iter,
772 std::unordered_set<const Variable*>* undefinedVariables,
773 bool* outUpdated,
774 bool* outNeedsRescan) {
775 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400776 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400777 if ((*iter)->fConstantPropagation) {
778 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
779 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400780 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400781 if (!try_replace_expression(&b, iter, &optimized)) {
782 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400783 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400784 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400785 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400786 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400787 }
788 }
789 switch (expr->fKind) {
790 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400791 const VariableReference& ref = (VariableReference&) *expr;
792 const Variable& var = ref.fVariable;
793 if (ref.refKind() != VariableReference::kWrite_RefKind &&
794 ref.refKind() != VariableReference::kPointer_RefKind &&
795 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400796 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
797 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000798 this->error(expr->fOffset,
799 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400800 }
801 break;
802 }
803 case Expression::kTernary_Kind: {
804 TernaryExpression* t = (TernaryExpression*) expr;
805 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
806 // ternary has a constant test, replace it with either the true or
807 // false branch
808 if (((BoolLiteral&) *t->fTest).fValue) {
809 (*iter)->setExpression(std::move(t->fIfTrue));
810 } else {
811 (*iter)->setExpression(std::move(t->fIfFalse));
812 }
813 *outUpdated = true;
814 *outNeedsRescan = true;
815 }
816 break;
817 }
818 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400819 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400820 if (dead_assignment(*bin)) {
821 delete_left(&b, iter, outUpdated, outNeedsRescan);
822 break;
823 }
824 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400825 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
826 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
827 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
828 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
829 break;
830 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400831 switch (bin->fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400832 case Token::Kind::TK_STAR:
Ethan Nicholascb670962017-04-20 19:31:52 -0400833 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400834 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
835 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400836 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400837 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
838 } else {
839 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400840 // 1 * float4(x) -> float4(x)
841 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400842 delete_left(&b, iter, outUpdated, outNeedsRescan);
843 }
844 }
845 else if (is_constant(*bin->fLeft, 0)) {
846 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500847 bin->fRight->fType.kind() == Type::kVector_Kind &&
848 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400849 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400850 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
851 } else {
852 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400853 // float4(0) * x -> float4(0)
854 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500855 if (!bin->fRight->hasSideEffects()) {
856 delete_right(&b, iter, outUpdated, outNeedsRescan);
857 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400858 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400859 }
860 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400861 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
862 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400863 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400864 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
865 } else {
866 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400867 // float4(x) * 1 -> float4(x)
868 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400869 delete_right(&b, iter, outUpdated, outNeedsRescan);
870 }
871 }
872 else if (is_constant(*bin->fRight, 0)) {
873 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500874 bin->fRight->fType.kind() == Type::kScalar_Kind &&
875 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400876 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400877 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
878 } else {
879 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400880 // x * float4(0) -> float4(0)
881 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500882 if (!bin->fLeft->hasSideEffects()) {
883 delete_left(&b, iter, outUpdated, outNeedsRescan);
884 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400885 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400886 }
887 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400888 case Token::Kind::TK_PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400889 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400890 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
891 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400892 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400893 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
894 } else {
895 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400896 // 0 + float4(x) -> float4(x)
897 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400898 delete_left(&b, iter, outUpdated, outNeedsRescan);
899 }
900 } else if (is_constant(*bin->fRight, 0)) {
901 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
902 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400903 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400904 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
905 } else {
906 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400907 // float4(x) + 0 -> float4(x)
908 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400909 delete_right(&b, iter, outUpdated, outNeedsRescan);
910 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400911 }
912 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400913 case Token::Kind::TK_MINUS:
Ethan Nicholas56e42712017-04-21 10:23:37 -0400914 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400915 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
916 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400917 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400918 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
919 } else {
920 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400921 // float4(x) - 0 -> float4(x)
922 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400923 delete_right(&b, iter, outUpdated, outNeedsRescan);
924 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400925 }
926 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400927 case Token::Kind::TK_SLASH:
Ethan Nicholascb670962017-04-20 19:31:52 -0400928 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400929 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
930 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400931 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400932 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
933 } else {
934 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400935 // float4(x) / 1 -> float4(x)
936 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400937 delete_right(&b, iter, outUpdated, outNeedsRescan);
938 }
939 } else if (is_constant(*bin->fLeft, 0)) {
940 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500941 bin->fRight->fType.kind() == Type::kVector_Kind &&
942 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400943 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400944 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
945 } else {
946 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400947 // float4(0) / x -> float4(0)
948 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500949 if (!bin->fRight->hasSideEffects()) {
950 delete_right(&b, iter, outUpdated, outNeedsRescan);
951 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400952 }
953 }
954 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400955 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400956 if (is_constant(*bin->fRight, 0)) {
957 clear_write(*bin->fLeft);
958 delete_right(&b, iter, outUpdated, outNeedsRescan);
959 }
960 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400961 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400962 if (is_constant(*bin->fRight, 0)) {
963 clear_write(*bin->fLeft);
964 delete_right(&b, iter, outUpdated, outNeedsRescan);
965 }
966 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400967 case Token::Kind::TK_STAREQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400968 if (is_constant(*bin->fRight, 1)) {
969 clear_write(*bin->fLeft);
970 delete_right(&b, iter, outUpdated, outNeedsRescan);
971 }
972 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400973 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400974 if (is_constant(*bin->fRight, 1)) {
975 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400976 delete_right(&b, iter, outUpdated, outNeedsRescan);
977 }
978 break;
979 default:
980 break;
981 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -0400982 break;
983 }
984 case Expression::kSwizzle_Kind: {
985 Swizzle& s = (Swizzle&) *expr;
986 // detect identity swizzles like foo.rgba
987 if ((int) s.fComponents.size() == s.fBase->fType.columns()) {
988 bool identity = true;
989 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
990 if (s.fComponents[i] != i) {
991 identity = false;
992 break;
993 }
994 }
995 if (identity) {
996 *outUpdated = true;
997 if (!try_replace_expression(&b, iter, &s.fBase)) {
998 *outNeedsRescan = true;
999 return;
1000 }
1001 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1002 break;
1003 }
1004 }
1005 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
1006 if (s.fBase->fKind == Expression::kSwizzle_Kind) {
1007 Swizzle& base = (Swizzle&) *s.fBase;
1008 std::vector<int> final;
1009 for (int c : s.fComponents) {
1010 if (c == SKSL_SWIZZLE_0 || c == SKSL_SWIZZLE_1) {
1011 final.push_back(c);
1012 } else {
1013 final.push_back(base.fComponents[c]);
1014 }
1015 }
1016 *outUpdated = true;
1017 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1018 std::move(final)));
1019 if (!try_replace_expression(&b, iter, &replacement)) {
1020 *outNeedsRescan = true;
1021 return;
1022 }
1023 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1024 break;
1025 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001026 }
1027 default:
1028 break;
1029 }
1030}
1031
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001032// returns true if this statement could potentially execute a break at the current level (we ignore
1033// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
Ethan Nicholas5005a222018-08-24 13:06:27 -04001034static bool contains_conditional_break(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001035 switch (s.fKind) {
1036 case Statement::kBlock_Kind:
1037 for (const auto& sub : ((Block&) s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001038 if (contains_conditional_break(*sub, inConditional)) {
1039 return true;
1040 }
1041 }
1042 return false;
1043 case Statement::kBreak_Kind:
1044 return inConditional;
1045 case Statement::kIf_Kind: {
1046 const IfStatement& i = (IfStatement&) s;
1047 return contains_conditional_break(*i.fIfTrue, true) ||
1048 (i.fIfFalse && contains_conditional_break(*i.fIfFalse, true));
1049 }
1050 default:
1051 return false;
1052 }
1053}
1054
1055// returns true if this statement definitely executes a break at the current level (we ignore
1056// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
1057static bool contains_unconditional_break(Statement& s) {
1058 switch (s.fKind) {
1059 case Statement::kBlock_Kind:
1060 for (const auto& sub : ((Block&) s).fStatements) {
1061 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001062 return true;
1063 }
1064 }
1065 return false;
1066 case Statement::kBreak_Kind:
1067 return true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001068 default:
1069 return false;
1070 }
1071}
1072
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001073static void copy_all_but_break(std::unique_ptr<Statement>& stmt,
1074 std::vector<std::unique_ptr<Statement>*>* target) {
1075 switch (stmt->fKind) {
1076 case Statement::kBlock_Kind:
1077 for (auto& s : ((Block&) *stmt).fStatements) {
1078 copy_all_but_break(s, target);
1079 }
1080 break;
1081 case Statement::kBreak_Kind:
1082 return;
1083 default:
1084 target->push_back(&stmt);
1085 }
1086}
1087
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001088// Returns a block containing all of the statements that will be run if the given case matches
1089// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1090// broken by this call and must then be discarded).
1091// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1092// when break statements appear inside conditionals.
1093static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
1094 bool capturing = false;
1095 std::vector<std::unique_ptr<Statement>*> statementPtrs;
1096 for (const auto& current : s->fCases) {
1097 if (current.get() == c) {
1098 capturing = true;
1099 }
1100 if (capturing) {
1101 for (auto& stmt : current->fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001102 if (contains_conditional_break(*stmt, s->fKind == Statement::kIf_Kind)) {
1103 return nullptr;
1104 }
1105 if (contains_unconditional_break(*stmt)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001106 capturing = false;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001107 copy_all_but_break(stmt, &statementPtrs);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001108 break;
1109 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001110 statementPtrs.push_back(&stmt);
1111 }
1112 if (!capturing) {
1113 break;
1114 }
1115 }
1116 }
1117 std::vector<std::unique_ptr<Statement>> statements;
1118 for (const auto& s : statementPtrs) {
1119 statements.push_back(std::move(*s));
1120 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001121 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001122}
1123
Ethan Nicholascb670962017-04-20 19:31:52 -04001124void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001125 BasicBlock& b,
1126 std::vector<BasicBlock::Node>::iterator* iter,
1127 std::unordered_set<const Variable*>* undefinedVariables,
1128 bool* outUpdated,
1129 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001130 Statement* stmt = (*iter)->statement()->get();
1131 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001132 case Statement::kVarDeclaration_Kind: {
1133 const auto& varDecl = (VarDeclaration&) *stmt;
1134 if (varDecl.fVar->dead() &&
1135 (!varDecl.fValue ||
1136 !varDecl.fValue->hasSideEffects())) {
1137 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001138 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001139 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1140 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001141 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001142 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001143 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001144 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001145 }
1146 break;
1147 }
1148 case Statement::kIf_Kind: {
1149 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001150 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1151 // constant if, collapse down to a single branch
1152 if (((BoolLiteral&) *i.fTest).fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001153 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001154 (*iter)->setStatement(std::move(i.fIfTrue));
1155 } else {
1156 if (i.fIfFalse) {
1157 (*iter)->setStatement(std::move(i.fIfFalse));
1158 } else {
1159 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1160 }
1161 }
1162 *outUpdated = true;
1163 *outNeedsRescan = true;
1164 break;
1165 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001166 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1167 // else block doesn't do anything, remove it
1168 i.fIfFalse.reset();
1169 *outUpdated = true;
1170 *outNeedsRescan = true;
1171 }
1172 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1173 // if block doesn't do anything, no else block
1174 if (i.fTest->hasSideEffects()) {
1175 // test has side effects, keep it
1176 (*iter)->setStatement(std::unique_ptr<Statement>(
1177 new ExpressionStatement(std::move(i.fTest))));
1178 } else {
1179 // no if, no else, no test side effects, kill the whole if
1180 // statement
1181 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1182 }
1183 *outUpdated = true;
1184 *outNeedsRescan = true;
1185 }
1186 break;
1187 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001188 case Statement::kSwitch_Kind: {
1189 SwitchStatement& s = (SwitchStatement&) *stmt;
1190 if (s.fValue->isConstant()) {
1191 // switch is constant, replace it with the case that matches
1192 bool found = false;
1193 SwitchCase* defaultCase = nullptr;
1194 for (const auto& c : s.fCases) {
1195 if (!c->fValue) {
1196 defaultCase = c.get();
1197 continue;
1198 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001199 SkASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001200 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001201 if (found) {
1202 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1203 if (newBlock) {
1204 (*iter)->setStatement(std::move(newBlock));
1205 break;
1206 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001207 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001208 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001209 "static switch contains non-static conditional break");
1210 s.fIsStatic = false;
1211 }
1212 return; // can't simplify
1213 }
1214 }
1215 }
1216 if (!found) {
1217 // no matching case. use default if it exists, or kill the whole thing
1218 if (defaultCase) {
1219 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1220 if (newBlock) {
1221 (*iter)->setStatement(std::move(newBlock));
1222 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001223 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001224 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001225 "static switch contains non-static conditional break");
1226 s.fIsStatic = false;
1227 }
1228 return; // can't simplify
1229 }
1230 } else {
1231 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1232 }
1233 }
1234 *outUpdated = true;
1235 *outNeedsRescan = true;
1236 }
1237 break;
1238 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001239 case Statement::kExpression_Kind: {
1240 ExpressionStatement& e = (ExpressionStatement&) *stmt;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001241 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001242 if (!e.fExpression->hasSideEffects()) {
1243 // Expression statement with no side effects, kill it
1244 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1245 *outNeedsRescan = true;
1246 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001247 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001248 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1249 *outUpdated = true;
1250 }
1251 break;
1252 }
1253 default:
1254 break;
1255 }
1256}
1257
1258void Compiler::scanCFG(FunctionDefinition& f) {
1259 CFG cfg = CFGGenerator().getCFG(f);
1260 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001261
1262 // check for unreachable code
1263 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001264 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001265 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001266 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001267 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1268 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001269 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001270 break;
1271 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001272 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001273 if ((*cfg.fBlocks[i].fNodes[0].expression())->fKind ==
1274 Expression::kBoolLiteral_Kind) {
1275 // Function inlining can generate do { ... } while(false) loops which always
1276 // break, so the boolean condition is considered unreachable. Since not
1277 // being able to reach a literal is a non-issue in the first place, we
1278 // don't report an error in this case.
1279 continue;
1280 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001281 break;
1282 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001283 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001284 }
1285 }
1286 if (fErrorCount) {
1287 return;
1288 }
1289
Ethan Nicholascb670962017-04-20 19:31:52 -04001290 // check for dead code & undefined variables, perform constant propagation
1291 std::unordered_set<const Variable*> undefinedVariables;
1292 bool updated;
1293 bool needsRescan = false;
1294 do {
1295 if (needsRescan) {
1296 cfg = CFGGenerator().getCFG(f);
1297 this->computeDataFlow(&cfg);
1298 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001299 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001300
1301 updated = false;
1302 for (BasicBlock& b : cfg.fBlocks) {
1303 DefinitionMap definitions = b.fBefore;
1304
1305 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1306 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1307 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1308 &needsRescan);
1309 } else {
1310 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1311 &needsRescan);
1312 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001313 if (needsRescan) {
1314 break;
1315 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001316 this->addDefinitions(*iter, &definitions);
1317 }
1318 }
1319 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001320 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001321
Ethan Nicholas91a10532017-06-22 11:24:38 -04001322 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001323 for (BasicBlock& b : cfg.fBlocks) {
1324 DefinitionMap definitions = b.fBefore;
1325
Ethan Nicholas91a10532017-06-22 11:24:38 -04001326 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001327 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1328 const Statement& s = **iter->statement();
1329 switch (s.fKind) {
1330 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001331 if (((const IfStatement&) s).fIsStatic &&
1332 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001333 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001334 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001335 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001336 break;
1337 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001338 if (((const SwitchStatement&) s).fIsStatic &&
1339 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001340 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001341 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001342 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001343 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001344 case Statement::kVarDeclarations_Kind: {
1345 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1346 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1347 if ((*varIter)->fKind == Statement::kNop_Kind) {
1348 varIter = decls.fVars.erase(varIter);
1349 } else {
1350 ++varIter;
1351 }
1352 }
1353 if (!decls.fVars.size()) {
1354 iter = b.fNodes.erase(iter);
1355 } else {
1356 ++iter;
1357 }
1358 break;
1359 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001360 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001361 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001362 break;
1363 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001364 } else {
1365 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001366 }
1367 }
1368 }
1369
ethannicholas22f939e2016-10-13 13:25:34 -07001370 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001371 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001372 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001373 this->error(f.fOffset, String("function '" + String(f.fDeclaration.fName) +
1374 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001375 }
1376 }
1377}
1378
Ethan Nicholas91164d12019-05-15 15:29:54 -04001379void Compiler::registerExternalValue(ExternalValue* value) {
1380 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1381}
1382
1383Symbol* Compiler::takeOwnership(std::unique_ptr<Symbol> symbol) {
1384 return fIRGenerator->fRootSymbolTable->takeOwnership(std::move(symbol));
1385}
1386
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001387std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001388 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001389 fErrorText = "";
1390 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001391 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001392 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001393 switch (kind) {
1394 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001395 inherited = &fVertexInclude;
1396 fIRGenerator->fSymbolTable = fVertexSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001397 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001398 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001399 break;
1400 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001401 inherited = &fFragmentInclude;
1402 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001403 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001404 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001405 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001406 case Program::kGeometry_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001407 inherited = &fGeometryInclude;
1408 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001409 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001410 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001411 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001412 case Program::kFragmentProcessor_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001413 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001414 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001415 fIRGenerator->start(&settings, nullptr);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001416 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Robert Phillipsfe8da172018-01-24 14:52:02 +00001417 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001418 &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001419 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001420 break;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001421 case Program::kPipelineStage_Kind:
1422 inherited = &fPipelineInclude;
1423 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001424 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001425 fIRGenerator->start(&settings, inherited);
1426 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001427 case Program::kGeneric_Kind:
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001428 inherited = &fInterpreterInclude;
1429 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001430 fIRGenerator->fIntrinsics = &fInterpreterIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001431 fIRGenerator->start(&settings, inherited);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001432 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001433 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001434 for (auto& element : elements) {
1435 if (element->fKind == ProgramElement::kEnum_Kind) {
1436 ((Enum&) *element).fBuiltin = true;
1437 }
1438 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001439 std::unique_ptr<String> textPtr(new String(std::move(text)));
1440 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001441 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001442 auto result = std::unique_ptr<Program>(new Program(kind,
1443 std::move(textPtr),
1444 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001445 fContext,
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001446 inherited,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001447 std::move(elements),
1448 fIRGenerator->fSymbolTable,
1449 fIRGenerator->fInputs));
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001450 if (fErrorCount) {
1451 return nullptr;
1452 }
1453 return result;
1454}
1455
Ethan Nicholas00543112018-07-31 09:44:36 -04001456bool Compiler::optimize(Program& program) {
1457 SkASSERT(!fErrorCount);
1458 if (!program.fIsOptimized) {
1459 program.fIsOptimized = true;
1460 fIRGenerator->fKind = program.fKind;
1461 fIRGenerator->fSettings = &program.fSettings;
1462 for (auto& element : program) {
1463 if (element.fKind == ProgramElement::kFunction_Kind) {
1464 this->scanCFG((FunctionDefinition&) element);
1465 }
1466 }
Ethan Nicholase8ad02c2020-06-03 16:58:20 -04001467 // we wait until after analysis to remove dead functions so that we still report errors
1468 // even in unused code
1469 if (program.fSettings.fRemoveDeadFunctions) {
1470 for (auto iter = program.fElements.begin(); iter != program.fElements.end(); ) {
1471 if ((*iter)->fKind == ProgramElement::kFunction_Kind) {
1472 const FunctionDefinition& f = (const FunctionDefinition&) **iter;
1473 if (!f.fDeclaration.fCallCount && f.fDeclaration.fName != "main") {
1474 iter = program.fElements.erase(iter);
1475 continue;
1476 }
1477 }
1478 ++iter;
1479 }
1480 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001481 if (program.fKind != Program::kFragmentProcessor_Kind) {
1482 for (auto iter = program.fElements.begin(); iter != program.fElements.end();) {
1483 if ((*iter)->fKind == ProgramElement::kVar_Kind) {
1484 VarDeclarations& vars = (VarDeclarations&) **iter;
1485 for (auto varIter = vars.fVars.begin(); varIter != vars.fVars.end();) {
1486 const Variable& var = *((VarDeclaration&) **varIter).fVar;
1487 if (var.dead()) {
1488 varIter = vars.fVars.erase(varIter);
1489 } else {
1490 ++varIter;
1491 }
1492 }
1493 if (vars.fVars.size() == 0) {
1494 iter = program.fElements.erase(iter);
1495 continue;
1496 }
1497 }
1498 ++iter;
1499 }
1500 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001501 }
1502 return fErrorCount == 0;
1503}
1504
1505std::unique_ptr<Program> Compiler::specialize(
1506 Program& program,
1507 const std::unordered_map<SkSL::String, SkSL::Program::Settings::Value>& inputs) {
1508 std::vector<std::unique_ptr<ProgramElement>> elements;
1509 for (const auto& e : program) {
1510 elements.push_back(e.clone());
1511 }
1512 Program::Settings settings;
1513 settings.fCaps = program.fSettings.fCaps;
1514 for (auto iter = inputs.begin(); iter != inputs.end(); ++iter) {
1515 settings.fArgs.insert(*iter);
1516 }
Brian Osman808f0212020-01-21 15:36:47 -05001517 std::unique_ptr<String> sourceCopy(new String(*program.fSource));
Ethan Nicholas00543112018-07-31 09:44:36 -04001518 std::unique_ptr<Program> result(new Program(program.fKind,
Brian Osman808f0212020-01-21 15:36:47 -05001519 std::move(sourceCopy),
Ethan Nicholas00543112018-07-31 09:44:36 -04001520 settings,
1521 program.fContext,
1522 program.fInheritedElements,
1523 std::move(elements),
1524 program.fSymbols,
1525 program.fInputs));
1526 return result;
1527}
1528
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001529#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1530
Ethan Nicholas00543112018-07-31 09:44:36 -04001531bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1532 if (!this->optimize(program)) {
1533 return false;
1534 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001535#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001536 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001537 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001538 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001539 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001540 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001541 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001542 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001543 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001544 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001545 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1546 SkDebugf("SPIR-V validation error: %s\n", m);
1547 };
1548 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001549 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001550 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001551 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001552 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001553 }
1554#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001555 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001556 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001557 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001558 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001559#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001560 return result;
1561}
1562
Ethan Nicholas00543112018-07-31 09:44:36 -04001563bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001564 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001565 bool result = this->toSPIRV(program, buffer);
1566 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001567 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001568 }
1569 return result;
1570}
1571
Ethan Nicholas00543112018-07-31 09:44:36 -04001572bool Compiler::toGLSL(Program& program, OutputStream& out) {
1573 if (!this->optimize(program)) {
1574 return false;
1575 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001576 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001577 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001578 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001579 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001580 return result;
1581}
1582
Ethan Nicholas00543112018-07-31 09:44:36 -04001583bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001584 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001585 bool result = this->toGLSL(program, buffer);
1586 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001587 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001588 }
1589 return result;
1590}
1591
Brian Osmanc0243912020-02-19 15:35:26 -05001592bool Compiler::toHLSL(Program& program, String* out) {
1593 String spirv;
1594 if (!this->toSPIRV(program, &spirv)) {
1595 return false;
1596 }
1597
1598 return SPIRVtoHLSL(spirv, out);
1599}
1600
Ethan Nicholas00543112018-07-31 09:44:36 -04001601bool Compiler::toMetal(Program& program, OutputStream& out) {
1602 if (!this->optimize(program)) {
1603 return false;
1604 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001605 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001606 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001607 return result;
1608}
1609
Ethan Nicholas00543112018-07-31 09:44:36 -04001610bool Compiler::toMetal(Program& program, String* out) {
1611 if (!this->optimize(program)) {
1612 return false;
1613 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001614 StringStream buffer;
1615 bool result = this->toMetal(program, buffer);
1616 if (result) {
1617 *out = buffer.str();
1618 }
1619 return result;
1620}
1621
Ethan Nicholas00543112018-07-31 09:44:36 -04001622bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1623 if (!this->optimize(program)) {
1624 return false;
1625 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001626 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001627 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001628 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001629 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001630 return result;
1631}
1632
Ethan Nicholas00543112018-07-31 09:44:36 -04001633bool Compiler::toH(Program& program, String name, OutputStream& out) {
1634 if (!this->optimize(program)) {
1635 return false;
1636 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001637 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001638 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001639 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001640 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001641 return result;
1642}
1643
Brian Osman2e29ab52019-09-20 12:19:11 -04001644#endif
1645
1646#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osman107c6662019-12-30 15:02:30 -05001647bool Compiler::toPipelineStage(const Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001648 SkASSERT(program.fIsOptimized);
1649 fSource = program.fSource.get();
1650 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001651 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001652 bool result = cg.generateCode();
1653 fSource = nullptr;
1654 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001655 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001656 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001657 return result;
1658}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001659#endif
1660
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001661std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Brian Osman489cf882019-07-09 10:48:28 -04001662#if defined(SK_ENABLE_SKSL_INTERPRETER)
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001663 if (!this->optimize(program)) {
1664 return nullptr;
1665 }
Brian Osman808f0212020-01-21 15:36:47 -05001666 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001667 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001668 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1669 bool success = cg.generateCode();
1670 fSource = nullptr;
1671 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001672 return result;
1673 }
Brian Osman489cf882019-07-09 10:48:28 -04001674#else
1675 ABORT("ByteCode interpreter not enabled");
1676#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001677 return nullptr;
1678}
1679
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001680const char* Compiler::OperatorName(Token::Kind kind) {
1681 switch (kind) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001682 case Token::Kind::TK_PLUS: return "+";
1683 case Token::Kind::TK_MINUS: return "-";
1684 case Token::Kind::TK_STAR: return "*";
1685 case Token::Kind::TK_SLASH: return "/";
1686 case Token::Kind::TK_PERCENT: return "%";
1687 case Token::Kind::TK_SHL: return "<<";
1688 case Token::Kind::TK_SHR: return ">>";
1689 case Token::Kind::TK_LOGICALNOT: return "!";
1690 case Token::Kind::TK_LOGICALAND: return "&&";
1691 case Token::Kind::TK_LOGICALOR: return "||";
1692 case Token::Kind::TK_LOGICALXOR: return "^^";
1693 case Token::Kind::TK_BITWISENOT: return "~";
1694 case Token::Kind::TK_BITWISEAND: return "&";
1695 case Token::Kind::TK_BITWISEOR: return "|";
1696 case Token::Kind::TK_BITWISEXOR: return "^";
1697 case Token::Kind::TK_EQ: return "=";
1698 case Token::Kind::TK_EQEQ: return "==";
1699 case Token::Kind::TK_NEQ: return "!=";
1700 case Token::Kind::TK_LT: return "<";
1701 case Token::Kind::TK_GT: return ">";
1702 case Token::Kind::TK_LTEQ: return "<=";
1703 case Token::Kind::TK_GTEQ: return ">=";
1704 case Token::Kind::TK_PLUSEQ: return "+=";
1705 case Token::Kind::TK_MINUSEQ: return "-=";
1706 case Token::Kind::TK_STAREQ: return "*=";
1707 case Token::Kind::TK_SLASHEQ: return "/=";
1708 case Token::Kind::TK_PERCENTEQ: return "%=";
1709 case Token::Kind::TK_SHLEQ: return "<<=";
1710 case Token::Kind::TK_SHREQ: return ">>=";
1711 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1712 case Token::Kind::TK_LOGICALOREQ: return "||=";
1713 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1714 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1715 case Token::Kind::TK_BITWISEOREQ: return "|=";
1716 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1717 case Token::Kind::TK_PLUSPLUS: return "++";
1718 case Token::Kind::TK_MINUSMINUS: return "--";
1719 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001720 default:
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001721 ABORT("unsupported operator: %d\n", (int) kind);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001722 }
1723}
1724
1725
1726bool Compiler::IsAssignment(Token::Kind op) {
1727 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001728 case Token::Kind::TK_EQ: // fall through
1729 case Token::Kind::TK_PLUSEQ: // fall through
1730 case Token::Kind::TK_MINUSEQ: // fall through
1731 case Token::Kind::TK_STAREQ: // fall through
1732 case Token::Kind::TK_SLASHEQ: // fall through
1733 case Token::Kind::TK_PERCENTEQ: // fall through
1734 case Token::Kind::TK_SHLEQ: // fall through
1735 case Token::Kind::TK_SHREQ: // fall through
1736 case Token::Kind::TK_BITWISEOREQ: // fall through
1737 case Token::Kind::TK_BITWISEXOREQ: // fall through
1738 case Token::Kind::TK_BITWISEANDEQ: // fall through
1739 case Token::Kind::TK_LOGICALOREQ: // fall through
1740 case Token::Kind::TK_LOGICALXOREQ: // fall through
1741 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001742 return true;
1743 default:
1744 return false;
1745 }
1746}
1747
1748Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001749 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001750 int line = 1;
1751 int column = 1;
1752 for (int i = 0; i < offset; i++) {
1753 if ((*fSource)[i] == '\n') {
1754 ++line;
1755 column = 1;
1756 }
1757 else {
1758 ++column;
1759 }
1760 }
1761 return Position(line, column);
1762}
1763
1764void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001765 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001766 Position pos = this->position(offset);
1767 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001768}
1769
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001770String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001771 this->writeErrorCount();
1772 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001773 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001774 return result;
1775}
1776
1777void Compiler::writeErrorCount() {
1778 if (fErrorCount) {
1779 fErrorText += to_string(fErrorCount) + " error";
1780 if (fErrorCount > 1) {
1781 fErrorText += "s";
1782 }
1783 fErrorText += "\n";
1784 }
1785}
1786
ethannicholasb3058bd2016-07-01 08:22:01 -07001787} // namespace