blob: cd5962bc0b47f7368d0e346d8f9a039e8b6033db [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 Nicholasa6ae1f72017-03-16 09:56:54 -040031#ifdef SK_ENABLE_SPIRV_VALIDATION
32#include "spirv-tools/libspirv.hpp"
33#endif
34
ethannicholasb3058bd2016-07-01 08:22:01 -070035// include the built-in shader symbols as static strings
36
Ethan Nicholas79707652017-11-16 11:20:11 -050037#define STRINGIFY(x) #x
38
Ethan Nicholas8da1e652019-05-24 11:01:59 -040039static const char* SKSL_GPU_INCLUDE =
40#include "sksl_gpu.inc"
41;
42
43static const char* SKSL_INTERP_INCLUDE =
44#include "sksl_interp.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070045;
46
ethannicholas5961bc92016-10-12 06:39:56 -070047static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050048#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070049;
50
ethannicholas5961bc92016-10-12 06:39:56 -070051static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050052#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070053;
54
Ethan Nicholas52cad152017-02-16 16:37:32 -050055static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050056#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050057;
58
Ethan Nicholas762466e2017-06-29 10:03:38 -040059static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050060#include "sksl_enums.inc"
61#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040062;
63
Ethan Nicholas8da1e652019-05-24 11:01:59 -040064static const char* SKSL_PIPELINE_INCLUDE =
65#include "sksl_pipeline.inc"
Ethan Nicholas0d997662019-04-08 09:46:01 -040066;
67
ethannicholasb3058bd2016-07-01 08:22:01 -070068namespace SkSL {
69
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040070Compiler::Compiler(Flags flags)
71: fFlags(flags)
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040072, fContext(new Context())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040073, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -040074 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
75 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040076 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070077 fTypes = types;
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040078 #define ADD_TYPE(t) types->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
79 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070080 ADD_TYPE(Void);
81 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040082 ADD_TYPE(Float2);
83 ADD_TYPE(Float3);
84 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040085 ADD_TYPE(Half);
86 ADD_TYPE(Half2);
87 ADD_TYPE(Half3);
88 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -070089 ADD_TYPE(Double);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040090 ADD_TYPE(Double2);
91 ADD_TYPE(Double3);
92 ADD_TYPE(Double4);
ethannicholasb3058bd2016-07-01 08:22:01 -070093 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040094 ADD_TYPE(Int2);
95 ADD_TYPE(Int3);
96 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -070097 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040098 ADD_TYPE(UInt2);
99 ADD_TYPE(UInt3);
100 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400101 ADD_TYPE(Short);
102 ADD_TYPE(Short2);
103 ADD_TYPE(Short3);
104 ADD_TYPE(Short4);
105 ADD_TYPE(UShort);
106 ADD_TYPE(UShort2);
107 ADD_TYPE(UShort3);
108 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400109 ADD_TYPE(Byte);
110 ADD_TYPE(Byte2);
111 ADD_TYPE(Byte3);
112 ADD_TYPE(Byte4);
113 ADD_TYPE(UByte);
114 ADD_TYPE(UByte2);
115 ADD_TYPE(UByte3);
116 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700117 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400118 ADD_TYPE(Bool2);
119 ADD_TYPE(Bool3);
120 ADD_TYPE(Bool4);
121 ADD_TYPE(Float2x2);
122 ADD_TYPE(Float2x3);
123 ADD_TYPE(Float2x4);
124 ADD_TYPE(Float3x2);
125 ADD_TYPE(Float3x3);
126 ADD_TYPE(Float3x4);
127 ADD_TYPE(Float4x2);
128 ADD_TYPE(Float4x3);
129 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400130 ADD_TYPE(Half2x2);
131 ADD_TYPE(Half2x3);
132 ADD_TYPE(Half2x4);
133 ADD_TYPE(Half3x2);
134 ADD_TYPE(Half3x3);
135 ADD_TYPE(Half3x4);
136 ADD_TYPE(Half4x2);
137 ADD_TYPE(Half4x3);
138 ADD_TYPE(Half4x4);
139 ADD_TYPE(Double2x2);
140 ADD_TYPE(Double2x3);
141 ADD_TYPE(Double2x4);
142 ADD_TYPE(Double3x2);
143 ADD_TYPE(Double3x3);
144 ADD_TYPE(Double3x4);
145 ADD_TYPE(Double4x2);
146 ADD_TYPE(Double4x3);
147 ADD_TYPE(Double4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700148 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400149 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700150 ADD_TYPE(GenDType);
151 ADD_TYPE(GenIType);
152 ADD_TYPE(GenUType);
153 ADD_TYPE(GenBType);
154 ADD_TYPE(Mat);
155 ADD_TYPE(Vec);
156 ADD_TYPE(GVec);
157 ADD_TYPE(GVec2);
158 ADD_TYPE(GVec3);
159 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400160 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700161 ADD_TYPE(DVec);
162 ADD_TYPE(IVec);
163 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400164 ADD_TYPE(SVec);
165 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400166 ADD_TYPE(ByteVec);
167 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700168 ADD_TYPE(BVec);
169
170 ADD_TYPE(Sampler1D);
171 ADD_TYPE(Sampler2D);
172 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700173 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700174 ADD_TYPE(SamplerCube);
175 ADD_TYPE(Sampler2DRect);
176 ADD_TYPE(Sampler1DArray);
177 ADD_TYPE(Sampler2DArray);
178 ADD_TYPE(SamplerCubeArray);
179 ADD_TYPE(SamplerBuffer);
180 ADD_TYPE(Sampler2DMS);
181 ADD_TYPE(Sampler2DMSArray);
182
Brian Salomonbf7b6202016-11-11 16:08:03 -0500183 ADD_TYPE(ISampler2D);
184
Brian Salomon2a51de82016-11-16 12:06:01 -0500185 ADD_TYPE(Image2D);
186 ADD_TYPE(IImage2D);
187
Greg Daniel64773e62016-11-22 09:44:03 -0500188 ADD_TYPE(SubpassInput);
189 ADD_TYPE(SubpassInputMS);
190
ethannicholasb3058bd2016-07-01 08:22:01 -0700191 ADD_TYPE(GSampler1D);
192 ADD_TYPE(GSampler2D);
193 ADD_TYPE(GSampler3D);
194 ADD_TYPE(GSamplerCube);
195 ADD_TYPE(GSampler2DRect);
196 ADD_TYPE(GSampler1DArray);
197 ADD_TYPE(GSampler2DArray);
198 ADD_TYPE(GSamplerCubeArray);
199 ADD_TYPE(GSamplerBuffer);
200 ADD_TYPE(GSampler2DMS);
201 ADD_TYPE(GSampler2DMSArray);
202
203 ADD_TYPE(Sampler1DShadow);
204 ADD_TYPE(Sampler2DShadow);
205 ADD_TYPE(SamplerCubeShadow);
206 ADD_TYPE(Sampler2DRectShadow);
207 ADD_TYPE(Sampler1DArrayShadow);
208 ADD_TYPE(Sampler2DArrayShadow);
209 ADD_TYPE(SamplerCubeArrayShadow);
210 ADD_TYPE(GSampler2DArrayShadow);
211 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400212 ADD_TYPE(FragmentProcessor);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400213 ADD_TYPE(SkRasterPipeline);
ethannicholasb3058bd2016-07-01 08:22:01 -0700214
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700215 StringFragment skCapsName("sk_Caps");
216 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400217 *fContext->fSkCaps_Type, Variable::kGlobal_Storage);
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500218 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
219
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700220 StringFragment skArgsName("sk_Args");
221 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400222 *fContext->fSkArgs_Type, Variable::kGlobal_Storage);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400223 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
224
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400225 std::vector<std::unique_ptr<ProgramElement>> ignored;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400226 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, strlen(SKSL_GPU_INCLUDE),
227 symbols, &ignored, &fGpuSymbolTable);
228 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, strlen(SKSL_VERT_INCLUDE),
229 fGpuSymbolTable, &fVertexInclude, &fVertexSymbolTable);
230 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, strlen(SKSL_FRAG_INCLUDE),
231 fGpuSymbolTable, &fFragmentInclude, &fFragmentSymbolTable);
232 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, strlen(SKSL_GEOM_INCLUDE),
233 fGpuSymbolTable, &fGeometryInclude, &fGeometrySymbolTable);
234 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
235 strlen(SKSL_PIPELINE_INCLUDE), fGpuSymbolTable, &fPipelineInclude,
236 &fPipelineSymbolTable);
237 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
238 strlen(SKSL_INTERP_INCLUDE), symbols, &fInterpreterInclude,
239 &fInterpreterSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -0700240}
241
242Compiler::~Compiler() {
243 delete fIRGenerator;
244}
245
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400246void Compiler::processIncludeFile(Program::Kind kind, const char* src, size_t length,
247 std::shared_ptr<SymbolTable> base,
248 std::vector<std::unique_ptr<ProgramElement>>* outElements,
249 std::shared_ptr<SymbolTable>* outSymbolTable) {
250 fIRGenerator->fSymbolTable = std::move(base);
251 Program::Settings settings;
252 fIRGenerator->start(&settings, nullptr);
253 fIRGenerator->convertProgram(kind, src, length, *fTypes, outElements);
254 if (this->fErrorCount) {
255 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
256 }
257 SkASSERT(!fErrorCount);
258 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
259 *outSymbolTable = fIRGenerator->fSymbolTable;
260}
261
ethannicholas22f939e2016-10-13 13:25:34 -0700262// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500263void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
264 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700265 switch (lvalue->fKind) {
266 case Expression::kVariableReference_Kind: {
267 const Variable& var = ((VariableReference*) lvalue)->fVariable;
268 if (var.fStorage == Variable::kLocal_Storage) {
269 (*definitions)[&var] = expr;
270 }
271 break;
272 }
273 case Expression::kSwizzle_Kind:
274 // We consider the variable written to as long as at least some of its components have
275 // been written to. This will lead to some false negatives (we won't catch it if you
276 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400277 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
278 // 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 -0700279 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400280 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400281 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700282 definitions);
283 break;
284 case Expression::kIndex_Kind:
285 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400286 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400287 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700288 definitions);
289 break;
290 case Expression::kFieldAccess_Kind:
291 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400292 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400293 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700294 definitions);
295 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500296 case Expression::kTernary_Kind:
297 // To simplify analysis, we just pretend that we write to both sides of the ternary.
298 // This allows for false positives (meaning we fail to detect that a variable might not
299 // have been assigned), but is preferable to false negatives.
300 this->addDefinition(((TernaryExpression*) lvalue)->fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400301 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500302 definitions);
303 this->addDefinition(((TernaryExpression*) lvalue)->fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400304 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500305 definitions);
306 break;
Ethan Nicholas91164d12019-05-15 15:29:54 -0400307 case Expression::kExternalValue_Kind:
308 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700309 default:
310 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400311 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700312 }
313}
314
315// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400316void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500317 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700318 switch (node.fKind) {
319 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400320 SkASSERT(node.expression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400321 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500322 switch (expr->fKind) {
323 case Expression::kBinary_Kind: {
324 BinaryExpression* b = (BinaryExpression*) expr;
325 if (b->fOperator == Token::EQ) {
326 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700327 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500328 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400329 b->fLeft.get(),
330 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
331 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500332
333 }
334 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700335 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400336 case Expression::kFunctionCall_Kind: {
337 const FunctionCall& c = (const FunctionCall&) *expr;
338 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
339 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
340 this->addDefinition(
341 c.fArguments[i].get(),
342 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
343 definitions);
344 }
345 }
346 break;
347 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500348 case Expression::kPrefix_Kind: {
349 const PrefixExpression* p = (PrefixExpression*) expr;
350 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
351 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400352 p->fOperand.get(),
353 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
354 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500355 }
356 break;
357 }
358 case Expression::kPostfix_Kind: {
359 const PostfixExpression* p = (PostfixExpression*) expr;
360 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
361 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400362 p->fOperand.get(),
363 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
364 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500365 }
366 break;
367 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400368 case Expression::kVariableReference_Kind: {
369 const VariableReference* v = (VariableReference*) expr;
370 if (v->fRefKind != VariableReference::kRead_RefKind) {
371 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400372 v,
373 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
374 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400375 }
376 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500377 default:
378 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700379 }
380 break;
381 }
382 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400383 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000384 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
385 VarDeclaration& vd = (VarDeclaration&) *stmt;
386 if (vd.fValue) {
387 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700388 }
389 }
390 break;
391 }
392 }
393}
394
395void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
396 BasicBlock& block = cfg->fBlocks[blockId];
397
398 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500399 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700400 for (const BasicBlock::Node& n : block.fNodes) {
401 this->addDefinitions(n, &after);
402 }
403
404 // propagate definitions to exits
405 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400406 if (exitId == blockId) {
407 continue;
408 }
ethannicholas22f939e2016-10-13 13:25:34 -0700409 BasicBlock& exit = cfg->fBlocks[exitId];
410 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500411 std::unique_ptr<Expression>* e1 = pair.second;
412 auto found = exit.fBefore.find(pair.first);
413 if (found == exit.fBefore.end()) {
414 // exit has no definition for it, just copy it
415 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700416 exit.fBefore[pair.first] = e1;
417 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500418 // exit has a (possibly different) value already defined
419 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700420 if (e1 != e2) {
421 // definition has changed, merge and add exit block to worklist
422 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500423 if (e1 && e2) {
424 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400425 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500426 } else {
427 exit.fBefore[pair.first] = nullptr;
428 }
ethannicholas22f939e2016-10-13 13:25:34 -0700429 }
430 }
431 }
432 }
433}
434
435// returns a map which maps all local variables in the function to null, indicating that their value
436// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500437static DefinitionMap compute_start_state(const CFG& cfg) {
438 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400439 for (const auto& block : cfg.fBlocks) {
440 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700441 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400442 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400443 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700444 if (s->fKind == Statement::kVarDeclarations_Kind) {
445 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000446 for (const auto& decl : vd->fDeclaration->fVars) {
447 if (decl->fKind == Statement::kVarDeclaration_Kind) {
448 result[((VarDeclaration&) *decl).fVar] = nullptr;
449 }
Mike Klein6ad99092016-10-26 10:35:22 -0400450 }
ethannicholas22f939e2016-10-13 13:25:34 -0700451 }
452 }
453 }
454 }
455 return result;
456}
457
Ethan Nicholascb670962017-04-20 19:31:52 -0400458/**
459 * Returns true if assigning to this lvalue has no effect.
460 */
461static bool is_dead(const Expression& lvalue) {
462 switch (lvalue.fKind) {
463 case Expression::kVariableReference_Kind:
464 return ((VariableReference&) lvalue).fVariable.dead();
465 case Expression::kSwizzle_Kind:
466 return is_dead(*((Swizzle&) lvalue).fBase);
467 case Expression::kFieldAccess_Kind:
468 return is_dead(*((FieldAccess&) lvalue).fBase);
469 case Expression::kIndex_Kind: {
470 const IndexExpression& idx = (IndexExpression&) lvalue;
471 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
472 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500473 case Expression::kTernary_Kind: {
474 const TernaryExpression& t = (TernaryExpression&) lvalue;
475 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
476 }
Ethan Nicholas91164d12019-05-15 15:29:54 -0400477 case Expression::kExternalValue_Kind:
478 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400479 default:
480 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
481 }
482}
ethannicholas22f939e2016-10-13 13:25:34 -0700483
Ethan Nicholascb670962017-04-20 19:31:52 -0400484/**
485 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
486 * to a dead target and lack of side effects on the left hand side.
487 */
488static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700489 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400490 return false;
491 }
492 return is_dead(*b.fLeft);
493}
494
495void Compiler::computeDataFlow(CFG* cfg) {
496 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700497 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400498 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700499 workList.insert(i);
500 }
501 while (workList.size()) {
502 BlockId next = *workList.begin();
503 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400504 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700505 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400506}
507
508/**
509 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
510 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
511 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
512 * need to be regenerated).
513 */
514bool try_replace_expression(BasicBlock* b,
515 std::vector<BasicBlock::Node>::iterator* iter,
516 std::unique_ptr<Expression>* newExpression) {
517 std::unique_ptr<Expression>* target = (*iter)->expression();
518 if (!b->tryRemoveExpression(iter)) {
519 *target = std::move(*newExpression);
520 return false;
521 }
522 *target = std::move(*newExpression);
523 return b->tryInsertExpression(iter, target);
524}
525
526/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400527 * Returns true if the expression is a constant numeric literal with the specified value, or a
528 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400529 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400530bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400531 switch (expr.fKind) {
532 case Expression::kIntLiteral_Kind:
533 return ((IntLiteral&) expr).fValue == value;
534 case Expression::kFloatLiteral_Kind:
535 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400536 case Expression::kConstructor_Kind: {
537 Constructor& c = (Constructor&) expr;
538 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
539 for (int i = 0; i < c.fType.columns(); ++i) {
Ethan Nicholas898a8a52019-04-19 09:39:14 -0400540 if (!is_constant(*c.getVecComponent(i), value)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400541 return false;
542 }
543 }
544 return true;
545 }
546 return false;
547 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400548 default:
549 return false;
550 }
551}
552
553/**
554 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
555 * and CFG structures).
556 */
557void delete_left(BasicBlock* b,
558 std::vector<BasicBlock::Node>::iterator* iter,
559 bool* outUpdated,
560 bool* outNeedsRescan) {
561 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400562 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400563 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400564 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400565 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400566 bool result;
567 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400568 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400569 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400570 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400571 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400572 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400573 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400574 *outNeedsRescan = true;
575 return;
576 }
577 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400578 *outNeedsRescan = true;
579 return;
580 }
581 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400582 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
583 (*iter)->expression() != &bin.fRight) {
584 *outNeedsRescan = true;
585 return;
586 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400587 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400588 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400589}
590
591/**
592 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
593 * CFG structures).
594 */
595void delete_right(BasicBlock* b,
596 std::vector<BasicBlock::Node>::iterator* iter,
597 bool* outUpdated,
598 bool* outNeedsRescan) {
599 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400600 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400601 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400602 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400603 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400604 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
605 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400606 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400607 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400608 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400609 *target = std::move(bin.fLeft);
610 if (*iter == b->fNodes.begin()) {
611 *outNeedsRescan = true;
612 return;
613 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400614 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400615 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
616 (*iter)->expression() != &bin.fLeft)) {
617 *outNeedsRescan = true;
618 return;
619 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400620 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400621 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400622}
623
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400624/**
625 * Constructs the specified type using a single argument.
626 */
627static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
628 std::vector<std::unique_ptr<Expression>> args;
629 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700630 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400631 return result;
632}
633
634/**
635 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
636 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
637 */
638static void vectorize(BasicBlock* b,
639 std::vector<BasicBlock::Node>::iterator* iter,
640 const Type& type,
641 std::unique_ptr<Expression>* otherExpression,
642 bool* outUpdated,
643 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400644 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
645 SkASSERT(type.kind() == Type::kVector_Kind);
646 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400647 *outUpdated = true;
648 std::unique_ptr<Expression>* target = (*iter)->expression();
649 if (!b->tryRemoveExpression(iter)) {
650 *target = construct(type, std::move(*otherExpression));
651 *outNeedsRescan = true;
652 } else {
653 *target = construct(type, std::move(*otherExpression));
654 if (!b->tryInsertExpression(iter, target)) {
655 *outNeedsRescan = true;
656 }
657 }
658}
659
660/**
661 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
662 * left to yield vec<n>(x).
663 */
664static void vectorize_left(BasicBlock* b,
665 std::vector<BasicBlock::Node>::iterator* iter,
666 bool* outUpdated,
667 bool* outNeedsRescan) {
668 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
669 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
670}
671
672/**
673 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
674 * right to yield vec<n>(y).
675 */
676static void vectorize_right(BasicBlock* b,
677 std::vector<BasicBlock::Node>::iterator* iter,
678 bool* outUpdated,
679 bool* outNeedsRescan) {
680 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
681 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
682}
683
684// Mark that an expression which we were writing to is no longer being written to
685void clear_write(const Expression& expr) {
686 switch (expr.fKind) {
687 case Expression::kVariableReference_Kind: {
688 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
689 break;
690 }
691 case Expression::kFieldAccess_Kind:
692 clear_write(*((FieldAccess&) expr).fBase);
693 break;
694 case Expression::kSwizzle_Kind:
695 clear_write(*((Swizzle&) expr).fBase);
696 break;
697 case Expression::kIndex_Kind:
698 clear_write(*((IndexExpression&) expr).fBase);
699 break;
700 default:
701 ABORT("shouldn't be writing to this kind of expression\n");
702 break;
703 }
704}
705
Ethan Nicholascb670962017-04-20 19:31:52 -0400706void Compiler::simplifyExpression(DefinitionMap& definitions,
707 BasicBlock& b,
708 std::vector<BasicBlock::Node>::iterator* iter,
709 std::unordered_set<const Variable*>* undefinedVariables,
710 bool* outUpdated,
711 bool* outNeedsRescan) {
712 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400713 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400714 if ((*iter)->fConstantPropagation) {
715 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
716 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400717 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400718 if (!try_replace_expression(&b, iter, &optimized)) {
719 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400720 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400721 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400722 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400723 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400724 }
725 }
726 switch (expr->fKind) {
727 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400728 const VariableReference& ref = (VariableReference&) *expr;
729 const Variable& var = ref.fVariable;
730 if (ref.refKind() != VariableReference::kWrite_RefKind &&
731 ref.refKind() != VariableReference::kPointer_RefKind &&
732 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400733 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
734 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000735 this->error(expr->fOffset,
736 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400737 }
738 break;
739 }
740 case Expression::kTernary_Kind: {
741 TernaryExpression* t = (TernaryExpression*) expr;
742 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
743 // ternary has a constant test, replace it with either the true or
744 // false branch
745 if (((BoolLiteral&) *t->fTest).fValue) {
746 (*iter)->setExpression(std::move(t->fIfTrue));
747 } else {
748 (*iter)->setExpression(std::move(t->fIfFalse));
749 }
750 *outUpdated = true;
751 *outNeedsRescan = true;
752 }
753 break;
754 }
755 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400756 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400757 if (dead_assignment(*bin)) {
758 delete_left(&b, iter, outUpdated, outNeedsRescan);
759 break;
760 }
761 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400762 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
763 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
764 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
765 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
766 break;
767 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400768 switch (bin->fOperator) {
769 case Token::STAR:
770 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400771 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
772 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400773 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400774 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
775 } else {
776 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400777 // 1 * float4(x) -> float4(x)
778 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400779 delete_left(&b, iter, outUpdated, outNeedsRescan);
780 }
781 }
782 else if (is_constant(*bin->fLeft, 0)) {
783 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500784 bin->fRight->fType.kind() == Type::kVector_Kind &&
785 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400786 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400787 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
788 } else {
789 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400790 // float4(0) * x -> float4(0)
791 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500792 if (!bin->fRight->hasSideEffects()) {
793 delete_right(&b, iter, outUpdated, outNeedsRescan);
794 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400795 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400796 }
797 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400798 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
799 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400800 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400801 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
802 } else {
803 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400804 // float4(x) * 1 -> float4(x)
805 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400806 delete_right(&b, iter, outUpdated, outNeedsRescan);
807 }
808 }
809 else if (is_constant(*bin->fRight, 0)) {
810 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500811 bin->fRight->fType.kind() == Type::kScalar_Kind &&
812 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400813 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400814 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
815 } else {
816 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400817 // x * float4(0) -> float4(0)
818 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500819 if (!bin->fLeft->hasSideEffects()) {
820 delete_left(&b, iter, outUpdated, outNeedsRescan);
821 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400822 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400823 }
824 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400825 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400826 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400827 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
828 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400829 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400830 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
831 } else {
832 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400833 // 0 + float4(x) -> float4(x)
834 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400835 delete_left(&b, iter, outUpdated, outNeedsRescan);
836 }
837 } else if (is_constant(*bin->fRight, 0)) {
838 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
839 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400840 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400841 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
842 } else {
843 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400844 // float4(x) + 0 -> float4(x)
845 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400846 delete_right(&b, iter, outUpdated, outNeedsRescan);
847 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400848 }
849 break;
850 case Token::MINUS:
851 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400852 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
853 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400854 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400855 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
856 } else {
857 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400858 // float4(x) - 0 -> float4(x)
859 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400860 delete_right(&b, iter, outUpdated, outNeedsRescan);
861 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400862 }
863 break;
864 case Token::SLASH:
865 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400866 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
867 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400868 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400869 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
870 } else {
871 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400872 // float4(x) / 1 -> float4(x)
873 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400874 delete_right(&b, iter, outUpdated, outNeedsRescan);
875 }
876 } else if (is_constant(*bin->fLeft, 0)) {
877 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500878 bin->fRight->fType.kind() == Type::kVector_Kind &&
879 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400880 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400881 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
882 } else {
883 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400884 // float4(0) / x -> float4(0)
885 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500886 if (!bin->fRight->hasSideEffects()) {
887 delete_right(&b, iter, outUpdated, outNeedsRescan);
888 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400889 }
890 }
891 break;
892 case Token::PLUSEQ:
893 if (is_constant(*bin->fRight, 0)) {
894 clear_write(*bin->fLeft);
895 delete_right(&b, iter, outUpdated, outNeedsRescan);
896 }
897 break;
898 case Token::MINUSEQ:
899 if (is_constant(*bin->fRight, 0)) {
900 clear_write(*bin->fLeft);
901 delete_right(&b, iter, outUpdated, outNeedsRescan);
902 }
903 break;
904 case Token::STAREQ:
905 if (is_constant(*bin->fRight, 1)) {
906 clear_write(*bin->fLeft);
907 delete_right(&b, iter, outUpdated, outNeedsRescan);
908 }
909 break;
910 case Token::SLASHEQ:
911 if (is_constant(*bin->fRight, 1)) {
912 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400913 delete_right(&b, iter, outUpdated, outNeedsRescan);
914 }
915 break;
916 default:
917 break;
918 }
919 }
920 default:
921 break;
922 }
923}
924
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400925// returns true if this statement could potentially execute a break at the current level (we ignore
926// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
Ethan Nicholas5005a222018-08-24 13:06:27 -0400927static bool contains_conditional_break(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400928 switch (s.fKind) {
929 case Statement::kBlock_Kind:
930 for (const auto& sub : ((Block&) s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -0400931 if (contains_conditional_break(*sub, inConditional)) {
932 return true;
933 }
934 }
935 return false;
936 case Statement::kBreak_Kind:
937 return inConditional;
938 case Statement::kIf_Kind: {
939 const IfStatement& i = (IfStatement&) s;
940 return contains_conditional_break(*i.fIfTrue, true) ||
941 (i.fIfFalse && contains_conditional_break(*i.fIfFalse, true));
942 }
943 default:
944 return false;
945 }
946}
947
948// returns true if this statement definitely executes a break at the current level (we ignore
949// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
950static bool contains_unconditional_break(Statement& s) {
951 switch (s.fKind) {
952 case Statement::kBlock_Kind:
953 for (const auto& sub : ((Block&) s).fStatements) {
954 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400955 return true;
956 }
957 }
958 return false;
959 case Statement::kBreak_Kind:
960 return true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400961 default:
962 return false;
963 }
964}
965
966// Returns a block containing all of the statements that will be run if the given case matches
967// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
968// broken by this call and must then be discarded).
969// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
970// when break statements appear inside conditionals.
971static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
972 bool capturing = false;
973 std::vector<std::unique_ptr<Statement>*> statementPtrs;
974 for (const auto& current : s->fCases) {
975 if (current.get() == c) {
976 capturing = true;
977 }
978 if (capturing) {
979 for (auto& stmt : current->fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -0400980 if (contains_conditional_break(*stmt, s->fKind == Statement::kIf_Kind)) {
981 return nullptr;
982 }
983 if (contains_unconditional_break(*stmt)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400984 capturing = false;
985 break;
986 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400987 statementPtrs.push_back(&stmt);
988 }
989 if (!capturing) {
990 break;
991 }
992 }
993 }
994 std::vector<std::unique_ptr<Statement>> statements;
995 for (const auto& s : statementPtrs) {
996 statements.push_back(std::move(*s));
997 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700998 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400999}
1000
Ethan Nicholascb670962017-04-20 19:31:52 -04001001void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001002 BasicBlock& b,
1003 std::vector<BasicBlock::Node>::iterator* iter,
1004 std::unordered_set<const Variable*>* undefinedVariables,
1005 bool* outUpdated,
1006 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001007 Statement* stmt = (*iter)->statement()->get();
1008 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001009 case Statement::kVarDeclaration_Kind: {
1010 const auto& varDecl = (VarDeclaration&) *stmt;
1011 if (varDecl.fVar->dead() &&
1012 (!varDecl.fValue ||
1013 !varDecl.fValue->hasSideEffects())) {
1014 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001015 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001016 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1017 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001018 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001019 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001020 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001021 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001022 }
1023 break;
1024 }
1025 case Statement::kIf_Kind: {
1026 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001027 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1028 // constant if, collapse down to a single branch
1029 if (((BoolLiteral&) *i.fTest).fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001030 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001031 (*iter)->setStatement(std::move(i.fIfTrue));
1032 } else {
1033 if (i.fIfFalse) {
1034 (*iter)->setStatement(std::move(i.fIfFalse));
1035 } else {
1036 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1037 }
1038 }
1039 *outUpdated = true;
1040 *outNeedsRescan = true;
1041 break;
1042 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001043 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1044 // else block doesn't do anything, remove it
1045 i.fIfFalse.reset();
1046 *outUpdated = true;
1047 *outNeedsRescan = true;
1048 }
1049 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1050 // if block doesn't do anything, no else block
1051 if (i.fTest->hasSideEffects()) {
1052 // test has side effects, keep it
1053 (*iter)->setStatement(std::unique_ptr<Statement>(
1054 new ExpressionStatement(std::move(i.fTest))));
1055 } else {
1056 // no if, no else, no test side effects, kill the whole if
1057 // statement
1058 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1059 }
1060 *outUpdated = true;
1061 *outNeedsRescan = true;
1062 }
1063 break;
1064 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001065 case Statement::kSwitch_Kind: {
1066 SwitchStatement& s = (SwitchStatement&) *stmt;
1067 if (s.fValue->isConstant()) {
1068 // switch is constant, replace it with the case that matches
1069 bool found = false;
1070 SwitchCase* defaultCase = nullptr;
1071 for (const auto& c : s.fCases) {
1072 if (!c->fValue) {
1073 defaultCase = c.get();
1074 continue;
1075 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001076 SkASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001077 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001078 if (found) {
1079 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1080 if (newBlock) {
1081 (*iter)->setStatement(std::move(newBlock));
1082 break;
1083 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001084 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001085 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001086 "static switch contains non-static conditional break");
1087 s.fIsStatic = false;
1088 }
1089 return; // can't simplify
1090 }
1091 }
1092 }
1093 if (!found) {
1094 // no matching case. use default if it exists, or kill the whole thing
1095 if (defaultCase) {
1096 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1097 if (newBlock) {
1098 (*iter)->setStatement(std::move(newBlock));
1099 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001100 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001101 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001102 "static switch contains non-static conditional break");
1103 s.fIsStatic = false;
1104 }
1105 return; // can't simplify
1106 }
1107 } else {
1108 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1109 }
1110 }
1111 *outUpdated = true;
1112 *outNeedsRescan = true;
1113 }
1114 break;
1115 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001116 case Statement::kExpression_Kind: {
1117 ExpressionStatement& e = (ExpressionStatement&) *stmt;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001118 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001119 if (!e.fExpression->hasSideEffects()) {
1120 // Expression statement with no side effects, kill it
1121 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1122 *outNeedsRescan = true;
1123 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001124 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001125 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1126 *outUpdated = true;
1127 }
1128 break;
1129 }
1130 default:
1131 break;
1132 }
1133}
1134
1135void Compiler::scanCFG(FunctionDefinition& f) {
1136 CFG cfg = CFGGenerator().getCFG(f);
1137 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001138
1139 // check for unreachable code
1140 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001141 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001142 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001143 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001144 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1145 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001146 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001147 break;
1148 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001149 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001150 break;
1151 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001152 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001153 }
1154 }
1155 if (fErrorCount) {
1156 return;
1157 }
1158
Ethan Nicholascb670962017-04-20 19:31:52 -04001159 // check for dead code & undefined variables, perform constant propagation
1160 std::unordered_set<const Variable*> undefinedVariables;
1161 bool updated;
1162 bool needsRescan = false;
1163 do {
1164 if (needsRescan) {
1165 cfg = CFGGenerator().getCFG(f);
1166 this->computeDataFlow(&cfg);
1167 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001168 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001169
1170 updated = false;
1171 for (BasicBlock& b : cfg.fBlocks) {
1172 DefinitionMap definitions = b.fBefore;
1173
1174 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1175 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1176 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1177 &needsRescan);
1178 } else {
1179 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1180 &needsRescan);
1181 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001182 if (needsRescan) {
1183 break;
1184 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001185 this->addDefinitions(*iter, &definitions);
1186 }
1187 }
1188 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001189 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001190
Ethan Nicholas91a10532017-06-22 11:24:38 -04001191 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001192 for (BasicBlock& b : cfg.fBlocks) {
1193 DefinitionMap definitions = b.fBefore;
1194
Ethan Nicholas91a10532017-06-22 11:24:38 -04001195 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001196 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1197 const Statement& s = **iter->statement();
1198 switch (s.fKind) {
1199 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001200 if (((const IfStatement&) s).fIsStatic &&
1201 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001202 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001203 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001204 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001205 break;
1206 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001207 if (((const SwitchStatement&) s).fIsStatic &&
1208 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001209 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001210 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001211 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001212 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001213 case Statement::kVarDeclarations_Kind: {
1214 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1215 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1216 if ((*varIter)->fKind == Statement::kNop_Kind) {
1217 varIter = decls.fVars.erase(varIter);
1218 } else {
1219 ++varIter;
1220 }
1221 }
1222 if (!decls.fVars.size()) {
1223 iter = b.fNodes.erase(iter);
1224 } else {
1225 ++iter;
1226 }
1227 break;
1228 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001229 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001230 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001231 break;
1232 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001233 } else {
1234 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001235 }
1236 }
1237 }
1238
ethannicholas22f939e2016-10-13 13:25:34 -07001239 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001240 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001241 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001242 this->error(f.fOffset, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001243 }
1244 }
1245}
1246
Ethan Nicholas91164d12019-05-15 15:29:54 -04001247void Compiler::registerExternalValue(ExternalValue* value) {
1248 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1249}
1250
1251Symbol* Compiler::takeOwnership(std::unique_ptr<Symbol> symbol) {
1252 return fIRGenerator->fRootSymbolTable->takeOwnership(std::move(symbol));
1253}
1254
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001255std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001256 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001257 fErrorText = "";
1258 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001259 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001260 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001261 switch (kind) {
1262 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001263 inherited = &fVertexInclude;
1264 fIRGenerator->fSymbolTable = fVertexSymbolTable;
1265 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001266 break;
1267 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001268 inherited = &fFragmentInclude;
1269 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
1270 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001271 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001272 case Program::kGeometry_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001273 inherited = &fGeometryInclude;
1274 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
1275 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001276 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001277 case Program::kFragmentProcessor_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001278 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001279 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001280 fIRGenerator->start(&settings, nullptr);
Robert Phillipsfe8da172018-01-24 14:52:02 +00001281 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001282 &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001283 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001284 break;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001285 case Program::kPipelineStage_Kind:
1286 inherited = &fPipelineInclude;
1287 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
1288 fIRGenerator->start(&settings, inherited);
1289 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001290 case Program::kGeneric_Kind:
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001291 inherited = &fInterpreterInclude;
1292 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
1293 fIRGenerator->start(&settings, inherited);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001294 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001295 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001296 for (auto& element : elements) {
1297 if (element->fKind == ProgramElement::kEnum_Kind) {
1298 ((Enum&) *element).fBuiltin = true;
1299 }
1300 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001301 std::unique_ptr<String> textPtr(new String(std::move(text)));
1302 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001303 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001304 auto result = std::unique_ptr<Program>(new Program(kind,
1305 std::move(textPtr),
1306 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001307 fContext,
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001308 inherited,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001309 std::move(elements),
1310 fIRGenerator->fSymbolTable,
1311 fIRGenerator->fInputs));
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001312 if (fErrorCount) {
1313 return nullptr;
1314 }
1315 return result;
1316}
1317
Ethan Nicholas00543112018-07-31 09:44:36 -04001318bool Compiler::optimize(Program& program) {
1319 SkASSERT(!fErrorCount);
1320 if (!program.fIsOptimized) {
1321 program.fIsOptimized = true;
1322 fIRGenerator->fKind = program.fKind;
1323 fIRGenerator->fSettings = &program.fSettings;
1324 for (auto& element : program) {
1325 if (element.fKind == ProgramElement::kFunction_Kind) {
1326 this->scanCFG((FunctionDefinition&) element);
1327 }
1328 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001329 if (program.fKind != Program::kFragmentProcessor_Kind) {
1330 for (auto iter = program.fElements.begin(); iter != program.fElements.end();) {
1331 if ((*iter)->fKind == ProgramElement::kVar_Kind) {
1332 VarDeclarations& vars = (VarDeclarations&) **iter;
1333 for (auto varIter = vars.fVars.begin(); varIter != vars.fVars.end();) {
1334 const Variable& var = *((VarDeclaration&) **varIter).fVar;
1335 if (var.dead()) {
1336 varIter = vars.fVars.erase(varIter);
1337 } else {
1338 ++varIter;
1339 }
1340 }
1341 if (vars.fVars.size() == 0) {
1342 iter = program.fElements.erase(iter);
1343 continue;
1344 }
1345 }
1346 ++iter;
1347 }
1348 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001349 }
1350 return fErrorCount == 0;
1351}
1352
1353std::unique_ptr<Program> Compiler::specialize(
1354 Program& program,
1355 const std::unordered_map<SkSL::String, SkSL::Program::Settings::Value>& inputs) {
1356 std::vector<std::unique_ptr<ProgramElement>> elements;
1357 for (const auto& e : program) {
1358 elements.push_back(e.clone());
1359 }
1360 Program::Settings settings;
1361 settings.fCaps = program.fSettings.fCaps;
1362 for (auto iter = inputs.begin(); iter != inputs.end(); ++iter) {
1363 settings.fArgs.insert(*iter);
1364 }
1365 std::unique_ptr<Program> result(new Program(program.fKind,
1366 nullptr,
1367 settings,
1368 program.fContext,
1369 program.fInheritedElements,
1370 std::move(elements),
1371 program.fSymbols,
1372 program.fInputs));
1373 return result;
1374}
1375
1376bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1377 if (!this->optimize(program)) {
1378 return false;
1379 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001380#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001381 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001382 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001383 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001384 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001385 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001386 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001387 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001388 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001389 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001390 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1391 SkDebugf("SPIR-V validation error: %s\n", m);
1392 };
1393 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001394 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001395 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001396 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001397 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001398 }
1399#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001400 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001401 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001402 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001403 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001404#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001405 return result;
1406}
1407
Ethan Nicholas00543112018-07-31 09:44:36 -04001408bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001409 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001410 bool result = this->toSPIRV(program, buffer);
1411 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001412 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001413 }
1414 return result;
1415}
1416
Ethan Nicholas00543112018-07-31 09:44:36 -04001417bool Compiler::toGLSL(Program& program, OutputStream& out) {
1418 if (!this->optimize(program)) {
1419 return false;
1420 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001421 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001422 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001423 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001424 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001425 return result;
1426}
1427
Ethan Nicholas00543112018-07-31 09:44:36 -04001428bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001429 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001430 bool result = this->toGLSL(program, buffer);
1431 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001432 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001433 }
1434 return result;
1435}
1436
Ethan Nicholas00543112018-07-31 09:44:36 -04001437bool Compiler::toMetal(Program& program, OutputStream& out) {
1438 if (!this->optimize(program)) {
1439 return false;
1440 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001441 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001442 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001443 return result;
1444}
1445
Ethan Nicholas00543112018-07-31 09:44:36 -04001446bool Compiler::toMetal(Program& program, String* out) {
1447 if (!this->optimize(program)) {
1448 return false;
1449 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001450 StringStream buffer;
1451 bool result = this->toMetal(program, buffer);
1452 if (result) {
1453 *out = buffer.str();
1454 }
1455 return result;
1456}
1457
Ethan Nicholas00543112018-07-31 09:44:36 -04001458bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1459 if (!this->optimize(program)) {
1460 return false;
1461 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001462 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001463 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001464 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001465 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001466 return result;
1467}
1468
Ethan Nicholas00543112018-07-31 09:44:36 -04001469bool Compiler::toH(Program& program, String name, OutputStream& out) {
1470 if (!this->optimize(program)) {
1471 return false;
1472 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001473 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001474 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001475 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001476 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001477 return result;
1478}
1479
1480bool Compiler::toPipelineStage(const Program& program, String* out,
1481 std::vector<FormatArg>* outFormatArgs) {
1482 SkASSERT(program.fIsOptimized);
1483 fSource = program.fSource.get();
1484 StringStream buffer;
1485 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outFormatArgs);
1486 bool result = cg.generateCode();
1487 fSource = nullptr;
1488 if (result) {
1489 *out = buffer.str();
1490 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001491 return result;
1492}
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001493
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001494std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
1495 if (!this->optimize(program)) {
1496 return nullptr;
1497 }
1498 std::unique_ptr<ByteCode> result(new ByteCode());
1499 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1500 if (cg.generateCode()) {
1501 return result;
1502 }
1503 return nullptr;
1504}
1505
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001506const char* Compiler::OperatorName(Token::Kind kind) {
1507 switch (kind) {
1508 case Token::PLUS: return "+";
1509 case Token::MINUS: return "-";
1510 case Token::STAR: return "*";
1511 case Token::SLASH: return "/";
1512 case Token::PERCENT: return "%";
1513 case Token::SHL: return "<<";
1514 case Token::SHR: return ">>";
1515 case Token::LOGICALNOT: return "!";
1516 case Token::LOGICALAND: return "&&";
1517 case Token::LOGICALOR: return "||";
1518 case Token::LOGICALXOR: return "^^";
1519 case Token::BITWISENOT: return "~";
1520 case Token::BITWISEAND: return "&";
1521 case Token::BITWISEOR: return "|";
1522 case Token::BITWISEXOR: return "^";
1523 case Token::EQ: return "=";
1524 case Token::EQEQ: return "==";
1525 case Token::NEQ: return "!=";
1526 case Token::LT: return "<";
1527 case Token::GT: return ">";
1528 case Token::LTEQ: return "<=";
1529 case Token::GTEQ: return ">=";
1530 case Token::PLUSEQ: return "+=";
1531 case Token::MINUSEQ: return "-=";
1532 case Token::STAREQ: return "*=";
1533 case Token::SLASHEQ: return "/=";
1534 case Token::PERCENTEQ: return "%=";
1535 case Token::SHLEQ: return "<<=";
1536 case Token::SHREQ: return ">>=";
1537 case Token::LOGICALANDEQ: return "&&=";
1538 case Token::LOGICALOREQ: return "||=";
1539 case Token::LOGICALXOREQ: return "^^=";
1540 case Token::BITWISEANDEQ: return "&=";
1541 case Token::BITWISEOREQ: return "|=";
1542 case Token::BITWISEXOREQ: return "^=";
1543 case Token::PLUSPLUS: return "++";
1544 case Token::MINUSMINUS: return "--";
1545 case Token::COMMA: return ",";
1546 default:
1547 ABORT("unsupported operator: %d\n", kind);
1548 }
1549}
1550
1551
1552bool Compiler::IsAssignment(Token::Kind op) {
1553 switch (op) {
1554 case Token::EQ: // fall through
1555 case Token::PLUSEQ: // fall through
1556 case Token::MINUSEQ: // fall through
1557 case Token::STAREQ: // fall through
1558 case Token::SLASHEQ: // fall through
1559 case Token::PERCENTEQ: // fall through
1560 case Token::SHLEQ: // fall through
1561 case Token::SHREQ: // fall through
1562 case Token::BITWISEOREQ: // fall through
1563 case Token::BITWISEXOREQ: // fall through
1564 case Token::BITWISEANDEQ: // fall through
1565 case Token::LOGICALOREQ: // fall through
1566 case Token::LOGICALXOREQ: // fall through
1567 case Token::LOGICALANDEQ:
1568 return true;
1569 default:
1570 return false;
1571 }
1572}
1573
1574Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001575 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001576 int line = 1;
1577 int column = 1;
1578 for (int i = 0; i < offset; i++) {
1579 if ((*fSource)[i] == '\n') {
1580 ++line;
1581 column = 1;
1582 }
1583 else {
1584 ++column;
1585 }
1586 }
1587 return Position(line, column);
1588}
1589
1590void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001591 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001592 Position pos = this->position(offset);
1593 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001594}
1595
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001596String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001597 this->writeErrorCount();
1598 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001599 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001600 return result;
1601}
1602
1603void Compiler::writeErrorCount() {
1604 if (fErrorCount) {
1605 fErrorText += to_string(fErrorCount) + " error";
1606 if (fErrorCount > 1) {
1607 fErrorText += "s";
1608 }
1609 fErrorText += "\n";
1610 }
1611}
1612
ethannicholasb3058bd2016-07-01 08:22:01 -07001613} // namespace