blob: 45065bc0e78fc40b5d894d809a5863f8a671b7b9 [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
ethannicholas5961bc92016-10-12 06:39:56 -070039static const char* SKSL_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050040#include "sksl.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070041;
42
ethannicholas5961bc92016-10-12 06:39:56 -070043static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050044#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070045;
46
ethannicholas5961bc92016-10-12 06:39:56 -070047static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050048#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070049;
50
Ethan Nicholas52cad152017-02-16 16:37:32 -050051static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050052#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050053;
54
Ethan Nicholas762466e2017-06-29 10:03:38 -040055static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050056#include "sksl_enums.inc"
57#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040058;
59
Ethan Nicholas746035a2019-04-23 13:31:09 -040060static const char* SKSL_GENERIC_INCLUDE =
61#include "sksl_generic.inc"
Ethan Nicholas0d997662019-04-08 09:46:01 -040062;
63
ethannicholasb3058bd2016-07-01 08:22:01 -070064namespace SkSL {
65
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040066Compiler::Compiler(Flags flags)
67: fFlags(flags)
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040068, fContext(new Context())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040069, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -040070 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
71 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040072 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070073 fTypes = types;
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040074 #define ADD_TYPE(t) types->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
75 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070076 ADD_TYPE(Void);
77 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040078 ADD_TYPE(Float2);
79 ADD_TYPE(Float3);
80 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040081 ADD_TYPE(Half);
82 ADD_TYPE(Half2);
83 ADD_TYPE(Half3);
84 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -070085 ADD_TYPE(Double);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040086 ADD_TYPE(Double2);
87 ADD_TYPE(Double3);
88 ADD_TYPE(Double4);
ethannicholasb3058bd2016-07-01 08:22:01 -070089 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040090 ADD_TYPE(Int2);
91 ADD_TYPE(Int3);
92 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -070093 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040094 ADD_TYPE(UInt2);
95 ADD_TYPE(UInt3);
96 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040097 ADD_TYPE(Short);
98 ADD_TYPE(Short2);
99 ADD_TYPE(Short3);
100 ADD_TYPE(Short4);
101 ADD_TYPE(UShort);
102 ADD_TYPE(UShort2);
103 ADD_TYPE(UShort3);
104 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400105 ADD_TYPE(Byte);
106 ADD_TYPE(Byte2);
107 ADD_TYPE(Byte3);
108 ADD_TYPE(Byte4);
109 ADD_TYPE(UByte);
110 ADD_TYPE(UByte2);
111 ADD_TYPE(UByte3);
112 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700113 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400114 ADD_TYPE(Bool2);
115 ADD_TYPE(Bool3);
116 ADD_TYPE(Bool4);
117 ADD_TYPE(Float2x2);
118 ADD_TYPE(Float2x3);
119 ADD_TYPE(Float2x4);
120 ADD_TYPE(Float3x2);
121 ADD_TYPE(Float3x3);
122 ADD_TYPE(Float3x4);
123 ADD_TYPE(Float4x2);
124 ADD_TYPE(Float4x3);
125 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400126 ADD_TYPE(Half2x2);
127 ADD_TYPE(Half2x3);
128 ADD_TYPE(Half2x4);
129 ADD_TYPE(Half3x2);
130 ADD_TYPE(Half3x3);
131 ADD_TYPE(Half3x4);
132 ADD_TYPE(Half4x2);
133 ADD_TYPE(Half4x3);
134 ADD_TYPE(Half4x4);
135 ADD_TYPE(Double2x2);
136 ADD_TYPE(Double2x3);
137 ADD_TYPE(Double2x4);
138 ADD_TYPE(Double3x2);
139 ADD_TYPE(Double3x3);
140 ADD_TYPE(Double3x4);
141 ADD_TYPE(Double4x2);
142 ADD_TYPE(Double4x3);
143 ADD_TYPE(Double4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700144 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400145 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700146 ADD_TYPE(GenDType);
147 ADD_TYPE(GenIType);
148 ADD_TYPE(GenUType);
149 ADD_TYPE(GenBType);
150 ADD_TYPE(Mat);
151 ADD_TYPE(Vec);
152 ADD_TYPE(GVec);
153 ADD_TYPE(GVec2);
154 ADD_TYPE(GVec3);
155 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400156 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700157 ADD_TYPE(DVec);
158 ADD_TYPE(IVec);
159 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400160 ADD_TYPE(SVec);
161 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400162 ADD_TYPE(ByteVec);
163 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700164 ADD_TYPE(BVec);
165
166 ADD_TYPE(Sampler1D);
167 ADD_TYPE(Sampler2D);
168 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700169 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700170 ADD_TYPE(SamplerCube);
171 ADD_TYPE(Sampler2DRect);
172 ADD_TYPE(Sampler1DArray);
173 ADD_TYPE(Sampler2DArray);
174 ADD_TYPE(SamplerCubeArray);
175 ADD_TYPE(SamplerBuffer);
176 ADD_TYPE(Sampler2DMS);
177 ADD_TYPE(Sampler2DMSArray);
178
Brian Salomonbf7b6202016-11-11 16:08:03 -0500179 ADD_TYPE(ISampler2D);
180
Brian Salomon2a51de82016-11-16 12:06:01 -0500181 ADD_TYPE(Image2D);
182 ADD_TYPE(IImage2D);
183
Greg Daniel64773e62016-11-22 09:44:03 -0500184 ADD_TYPE(SubpassInput);
185 ADD_TYPE(SubpassInputMS);
186
ethannicholasb3058bd2016-07-01 08:22:01 -0700187 ADD_TYPE(GSampler1D);
188 ADD_TYPE(GSampler2D);
189 ADD_TYPE(GSampler3D);
190 ADD_TYPE(GSamplerCube);
191 ADD_TYPE(GSampler2DRect);
192 ADD_TYPE(GSampler1DArray);
193 ADD_TYPE(GSampler2DArray);
194 ADD_TYPE(GSamplerCubeArray);
195 ADD_TYPE(GSamplerBuffer);
196 ADD_TYPE(GSampler2DMS);
197 ADD_TYPE(GSampler2DMSArray);
198
199 ADD_TYPE(Sampler1DShadow);
200 ADD_TYPE(Sampler2DShadow);
201 ADD_TYPE(SamplerCubeShadow);
202 ADD_TYPE(Sampler2DRectShadow);
203 ADD_TYPE(Sampler1DArrayShadow);
204 ADD_TYPE(Sampler2DArrayShadow);
205 ADD_TYPE(SamplerCubeArrayShadow);
206 ADD_TYPE(GSampler2DArrayShadow);
207 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400208 ADD_TYPE(FragmentProcessor);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400209 ADD_TYPE(SkRasterPipeline);
ethannicholasb3058bd2016-07-01 08:22:01 -0700210
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700211 StringFragment skCapsName("sk_Caps");
212 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400213 *fContext->fSkCaps_Type, Variable::kGlobal_Storage);
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500214 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
215
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700216 StringFragment skArgsName("sk_Args");
217 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400218 *fContext->fSkArgs_Type, Variable::kGlobal_Storage);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400219 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
220
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400221 std::vector<std::unique_ptr<ProgramElement>> ignored;
Robert Phillipsfe8da172018-01-24 14:52:02 +0000222 fIRGenerator->convertProgram(Program::kFragment_Kind, SKSL_INCLUDE, strlen(SKSL_INCLUDE),
223 *fTypes, &ignored);
ethannicholasddb37d62016-10-20 09:54:00 -0700224 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700225 if (fErrorCount) {
226 printf("Unexpected errors: %s\n", fErrorText.c_str());
227 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400228 SkASSERT(!fErrorCount);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400229
230 Program::Settings settings;
231 fIRGenerator->start(&settings, nullptr);
232 fIRGenerator->convertProgram(Program::kFragment_Kind, SKSL_VERT_INCLUDE,
233 strlen(SKSL_VERT_INCLUDE), *fTypes, &fVertexInclude);
234 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
235 fVertexSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400236
237 fIRGenerator->start(&settings, nullptr);
238 fIRGenerator->convertProgram(Program::kVertex_Kind, SKSL_FRAG_INCLUDE,
239 strlen(SKSL_FRAG_INCLUDE), *fTypes, &fFragmentInclude);
240 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
241 fFragmentSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400242
243 fIRGenerator->start(&settings, nullptr);
244 fIRGenerator->convertProgram(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE,
245 strlen(SKSL_GEOM_INCLUDE), *fTypes, &fGeometryInclude);
246 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
247 fGeometrySymbolTable = fIRGenerator->fSymbolTable;
ethannicholasb3058bd2016-07-01 08:22:01 -0700248}
249
250Compiler::~Compiler() {
251 delete fIRGenerator;
252}
253
ethannicholas22f939e2016-10-13 13:25:34 -0700254// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500255void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
256 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700257 switch (lvalue->fKind) {
258 case Expression::kVariableReference_Kind: {
259 const Variable& var = ((VariableReference*) lvalue)->fVariable;
260 if (var.fStorage == Variable::kLocal_Storage) {
261 (*definitions)[&var] = expr;
262 }
263 break;
264 }
265 case Expression::kSwizzle_Kind:
266 // We consider the variable written to as long as at least some of its components have
267 // been written to. This will lead to some false negatives (we won't catch it if you
268 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400269 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
270 // 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 -0700271 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400272 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400273 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700274 definitions);
275 break;
276 case Expression::kIndex_Kind:
277 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400278 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400279 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700280 definitions);
281 break;
282 case Expression::kFieldAccess_Kind:
283 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400284 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400285 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700286 definitions);
287 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500288 case Expression::kTernary_Kind:
289 // To simplify analysis, we just pretend that we write to both sides of the ternary.
290 // This allows for false positives (meaning we fail to detect that a variable might not
291 // have been assigned), but is preferable to false negatives.
292 this->addDefinition(((TernaryExpression*) lvalue)->fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400293 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500294 definitions);
295 this->addDefinition(((TernaryExpression*) lvalue)->fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400296 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500297 definitions);
298 break;
Ethan Nicholas91164d12019-05-15 15:29:54 -0400299 case Expression::kExternalValue_Kind:
300 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700301 default:
302 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400303 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700304 }
305}
306
307// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400308void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500309 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700310 switch (node.fKind) {
311 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400312 SkASSERT(node.expression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400313 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500314 switch (expr->fKind) {
315 case Expression::kBinary_Kind: {
316 BinaryExpression* b = (BinaryExpression*) expr;
317 if (b->fOperator == Token::EQ) {
318 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700319 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500320 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400321 b->fLeft.get(),
322 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
323 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500324
325 }
326 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700327 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400328 case Expression::kFunctionCall_Kind: {
329 const FunctionCall& c = (const FunctionCall&) *expr;
330 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
331 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
332 this->addDefinition(
333 c.fArguments[i].get(),
334 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
335 definitions);
336 }
337 }
338 break;
339 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500340 case Expression::kPrefix_Kind: {
341 const PrefixExpression* p = (PrefixExpression*) expr;
342 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
343 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400344 p->fOperand.get(),
345 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
346 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500347 }
348 break;
349 }
350 case Expression::kPostfix_Kind: {
351 const PostfixExpression* p = (PostfixExpression*) expr;
352 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
353 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400354 p->fOperand.get(),
355 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
356 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500357 }
358 break;
359 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400360 case Expression::kVariableReference_Kind: {
361 const VariableReference* v = (VariableReference*) expr;
362 if (v->fRefKind != VariableReference::kRead_RefKind) {
363 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400364 v,
365 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
366 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400367 }
368 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500369 default:
370 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700371 }
372 break;
373 }
374 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400375 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000376 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
377 VarDeclaration& vd = (VarDeclaration&) *stmt;
378 if (vd.fValue) {
379 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700380 }
381 }
382 break;
383 }
384 }
385}
386
387void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
388 BasicBlock& block = cfg->fBlocks[blockId];
389
390 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500391 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700392 for (const BasicBlock::Node& n : block.fNodes) {
393 this->addDefinitions(n, &after);
394 }
395
396 // propagate definitions to exits
397 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400398 if (exitId == blockId) {
399 continue;
400 }
ethannicholas22f939e2016-10-13 13:25:34 -0700401 BasicBlock& exit = cfg->fBlocks[exitId];
402 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500403 std::unique_ptr<Expression>* e1 = pair.second;
404 auto found = exit.fBefore.find(pair.first);
405 if (found == exit.fBefore.end()) {
406 // exit has no definition for it, just copy it
407 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700408 exit.fBefore[pair.first] = e1;
409 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500410 // exit has a (possibly different) value already defined
411 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700412 if (e1 != e2) {
413 // definition has changed, merge and add exit block to worklist
414 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500415 if (e1 && e2) {
416 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400417 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500418 } else {
419 exit.fBefore[pair.first] = nullptr;
420 }
ethannicholas22f939e2016-10-13 13:25:34 -0700421 }
422 }
423 }
424 }
425}
426
427// returns a map which maps all local variables in the function to null, indicating that their value
428// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500429static DefinitionMap compute_start_state(const CFG& cfg) {
430 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400431 for (const auto& block : cfg.fBlocks) {
432 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700433 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400434 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400435 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700436 if (s->fKind == Statement::kVarDeclarations_Kind) {
437 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000438 for (const auto& decl : vd->fDeclaration->fVars) {
439 if (decl->fKind == Statement::kVarDeclaration_Kind) {
440 result[((VarDeclaration&) *decl).fVar] = nullptr;
441 }
Mike Klein6ad99092016-10-26 10:35:22 -0400442 }
ethannicholas22f939e2016-10-13 13:25:34 -0700443 }
444 }
445 }
446 }
447 return result;
448}
449
Ethan Nicholascb670962017-04-20 19:31:52 -0400450/**
451 * Returns true if assigning to this lvalue has no effect.
452 */
453static bool is_dead(const Expression& lvalue) {
454 switch (lvalue.fKind) {
455 case Expression::kVariableReference_Kind:
456 return ((VariableReference&) lvalue).fVariable.dead();
457 case Expression::kSwizzle_Kind:
458 return is_dead(*((Swizzle&) lvalue).fBase);
459 case Expression::kFieldAccess_Kind:
460 return is_dead(*((FieldAccess&) lvalue).fBase);
461 case Expression::kIndex_Kind: {
462 const IndexExpression& idx = (IndexExpression&) lvalue;
463 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
464 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500465 case Expression::kTernary_Kind: {
466 const TernaryExpression& t = (TernaryExpression&) lvalue;
467 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
468 }
Ethan Nicholas91164d12019-05-15 15:29:54 -0400469 case Expression::kExternalValue_Kind:
470 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400471 default:
472 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
473 }
474}
ethannicholas22f939e2016-10-13 13:25:34 -0700475
Ethan Nicholascb670962017-04-20 19:31:52 -0400476/**
477 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
478 * to a dead target and lack of side effects on the left hand side.
479 */
480static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700481 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400482 return false;
483 }
484 return is_dead(*b.fLeft);
485}
486
487void Compiler::computeDataFlow(CFG* cfg) {
488 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700489 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400490 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700491 workList.insert(i);
492 }
493 while (workList.size()) {
494 BlockId next = *workList.begin();
495 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400496 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700497 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400498}
499
500/**
501 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
502 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
503 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
504 * need to be regenerated).
505 */
506bool try_replace_expression(BasicBlock* b,
507 std::vector<BasicBlock::Node>::iterator* iter,
508 std::unique_ptr<Expression>* newExpression) {
509 std::unique_ptr<Expression>* target = (*iter)->expression();
510 if (!b->tryRemoveExpression(iter)) {
511 *target = std::move(*newExpression);
512 return false;
513 }
514 *target = std::move(*newExpression);
515 return b->tryInsertExpression(iter, target);
516}
517
518/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400519 * Returns true if the expression is a constant numeric literal with the specified value, or a
520 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400521 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400522bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400523 switch (expr.fKind) {
524 case Expression::kIntLiteral_Kind:
525 return ((IntLiteral&) expr).fValue == value;
526 case Expression::kFloatLiteral_Kind:
527 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400528 case Expression::kConstructor_Kind: {
529 Constructor& c = (Constructor&) expr;
530 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
531 for (int i = 0; i < c.fType.columns(); ++i) {
Ethan Nicholas898a8a52019-04-19 09:39:14 -0400532 if (!is_constant(*c.getVecComponent(i), value)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400533 return false;
534 }
535 }
536 return true;
537 }
538 return false;
539 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400540 default:
541 return false;
542 }
543}
544
545/**
546 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
547 * and CFG structures).
548 */
549void delete_left(BasicBlock* b,
550 std::vector<BasicBlock::Node>::iterator* iter,
551 bool* outUpdated,
552 bool* outNeedsRescan) {
553 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400554 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400555 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400556 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400557 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400558 bool result;
559 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400560 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400561 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400562 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400563 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400564 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400565 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400566 *outNeedsRescan = true;
567 return;
568 }
569 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400570 *outNeedsRescan = true;
571 return;
572 }
573 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400574 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
575 (*iter)->expression() != &bin.fRight) {
576 *outNeedsRescan = true;
577 return;
578 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400579 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400580 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400581}
582
583/**
584 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
585 * CFG structures).
586 */
587void delete_right(BasicBlock* b,
588 std::vector<BasicBlock::Node>::iterator* iter,
589 bool* outUpdated,
590 bool* outNeedsRescan) {
591 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400592 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400593 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400594 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400595 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400596 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
597 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400598 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400599 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400600 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400601 *target = std::move(bin.fLeft);
602 if (*iter == b->fNodes.begin()) {
603 *outNeedsRescan = true;
604 return;
605 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400606 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400607 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
608 (*iter)->expression() != &bin.fLeft)) {
609 *outNeedsRescan = true;
610 return;
611 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400612 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400613 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400614}
615
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400616/**
617 * Constructs the specified type using a single argument.
618 */
619static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
620 std::vector<std::unique_ptr<Expression>> args;
621 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700622 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400623 return result;
624}
625
626/**
627 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
628 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
629 */
630static void vectorize(BasicBlock* b,
631 std::vector<BasicBlock::Node>::iterator* iter,
632 const Type& type,
633 std::unique_ptr<Expression>* otherExpression,
634 bool* outUpdated,
635 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400636 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
637 SkASSERT(type.kind() == Type::kVector_Kind);
638 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400639 *outUpdated = true;
640 std::unique_ptr<Expression>* target = (*iter)->expression();
641 if (!b->tryRemoveExpression(iter)) {
642 *target = construct(type, std::move(*otherExpression));
643 *outNeedsRescan = true;
644 } else {
645 *target = construct(type, std::move(*otherExpression));
646 if (!b->tryInsertExpression(iter, target)) {
647 *outNeedsRescan = true;
648 }
649 }
650}
651
652/**
653 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
654 * left to yield vec<n>(x).
655 */
656static void vectorize_left(BasicBlock* b,
657 std::vector<BasicBlock::Node>::iterator* iter,
658 bool* outUpdated,
659 bool* outNeedsRescan) {
660 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
661 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
662}
663
664/**
665 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
666 * right to yield vec<n>(y).
667 */
668static void vectorize_right(BasicBlock* b,
669 std::vector<BasicBlock::Node>::iterator* iter,
670 bool* outUpdated,
671 bool* outNeedsRescan) {
672 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
673 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
674}
675
676// Mark that an expression which we were writing to is no longer being written to
677void clear_write(const Expression& expr) {
678 switch (expr.fKind) {
679 case Expression::kVariableReference_Kind: {
680 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
681 break;
682 }
683 case Expression::kFieldAccess_Kind:
684 clear_write(*((FieldAccess&) expr).fBase);
685 break;
686 case Expression::kSwizzle_Kind:
687 clear_write(*((Swizzle&) expr).fBase);
688 break;
689 case Expression::kIndex_Kind:
690 clear_write(*((IndexExpression&) expr).fBase);
691 break;
692 default:
693 ABORT("shouldn't be writing to this kind of expression\n");
694 break;
695 }
696}
697
Ethan Nicholascb670962017-04-20 19:31:52 -0400698void Compiler::simplifyExpression(DefinitionMap& definitions,
699 BasicBlock& b,
700 std::vector<BasicBlock::Node>::iterator* iter,
701 std::unordered_set<const Variable*>* undefinedVariables,
702 bool* outUpdated,
703 bool* outNeedsRescan) {
704 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400705 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400706 if ((*iter)->fConstantPropagation) {
707 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
708 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400709 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400710 if (!try_replace_expression(&b, iter, &optimized)) {
711 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400712 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400713 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400714 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400715 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400716 }
717 }
718 switch (expr->fKind) {
719 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400720 const VariableReference& ref = (VariableReference&) *expr;
721 const Variable& var = ref.fVariable;
722 if (ref.refKind() != VariableReference::kWrite_RefKind &&
723 ref.refKind() != VariableReference::kPointer_RefKind &&
724 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400725 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
726 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000727 this->error(expr->fOffset,
728 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400729 }
730 break;
731 }
732 case Expression::kTernary_Kind: {
733 TernaryExpression* t = (TernaryExpression*) expr;
734 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
735 // ternary has a constant test, replace it with either the true or
736 // false branch
737 if (((BoolLiteral&) *t->fTest).fValue) {
738 (*iter)->setExpression(std::move(t->fIfTrue));
739 } else {
740 (*iter)->setExpression(std::move(t->fIfFalse));
741 }
742 *outUpdated = true;
743 *outNeedsRescan = true;
744 }
745 break;
746 }
747 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400748 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400749 if (dead_assignment(*bin)) {
750 delete_left(&b, iter, outUpdated, outNeedsRescan);
751 break;
752 }
753 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400754 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
755 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
756 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
757 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
758 break;
759 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400760 switch (bin->fOperator) {
761 case Token::STAR:
762 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400763 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
764 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400765 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400766 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
767 } else {
768 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400769 // 1 * float4(x) -> float4(x)
770 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400771 delete_left(&b, iter, outUpdated, outNeedsRescan);
772 }
773 }
774 else if (is_constant(*bin->fLeft, 0)) {
775 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500776 bin->fRight->fType.kind() == Type::kVector_Kind &&
777 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400778 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400779 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
780 } else {
781 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400782 // float4(0) * x -> float4(0)
783 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500784 if (!bin->fRight->hasSideEffects()) {
785 delete_right(&b, iter, outUpdated, outNeedsRescan);
786 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400787 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400788 }
789 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400790 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
791 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400792 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400793 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
794 } else {
795 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400796 // float4(x) * 1 -> float4(x)
797 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400798 delete_right(&b, iter, outUpdated, outNeedsRescan);
799 }
800 }
801 else if (is_constant(*bin->fRight, 0)) {
802 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500803 bin->fRight->fType.kind() == Type::kScalar_Kind &&
804 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400805 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400806 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
807 } else {
808 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400809 // x * float4(0) -> float4(0)
810 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500811 if (!bin->fLeft->hasSideEffects()) {
812 delete_left(&b, iter, outUpdated, outNeedsRescan);
813 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400814 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400815 }
816 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400817 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400818 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400819 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
820 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400821 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400822 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
823 } else {
824 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400825 // 0 + float4(x) -> float4(x)
826 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400827 delete_left(&b, iter, outUpdated, outNeedsRescan);
828 }
829 } else if (is_constant(*bin->fRight, 0)) {
830 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
831 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400832 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400833 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
834 } else {
835 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400836 // float4(x) + 0 -> float4(x)
837 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400838 delete_right(&b, iter, outUpdated, outNeedsRescan);
839 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400840 }
841 break;
842 case Token::MINUS:
843 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400844 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
845 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400846 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400847 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
848 } else {
849 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400850 // float4(x) - 0 -> float4(x)
851 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400852 delete_right(&b, iter, outUpdated, outNeedsRescan);
853 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400854 }
855 break;
856 case Token::SLASH:
857 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400858 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
859 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400860 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400861 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
862 } else {
863 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400864 // float4(x) / 1 -> float4(x)
865 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400866 delete_right(&b, iter, outUpdated, outNeedsRescan);
867 }
868 } else if (is_constant(*bin->fLeft, 0)) {
869 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500870 bin->fRight->fType.kind() == Type::kVector_Kind &&
871 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400872 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400873 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
874 } else {
875 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400876 // float4(0) / x -> float4(0)
877 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500878 if (!bin->fRight->hasSideEffects()) {
879 delete_right(&b, iter, outUpdated, outNeedsRescan);
880 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400881 }
882 }
883 break;
884 case Token::PLUSEQ:
885 if (is_constant(*bin->fRight, 0)) {
886 clear_write(*bin->fLeft);
887 delete_right(&b, iter, outUpdated, outNeedsRescan);
888 }
889 break;
890 case Token::MINUSEQ:
891 if (is_constant(*bin->fRight, 0)) {
892 clear_write(*bin->fLeft);
893 delete_right(&b, iter, outUpdated, outNeedsRescan);
894 }
895 break;
896 case Token::STAREQ:
897 if (is_constant(*bin->fRight, 1)) {
898 clear_write(*bin->fLeft);
899 delete_right(&b, iter, outUpdated, outNeedsRescan);
900 }
901 break;
902 case Token::SLASHEQ:
903 if (is_constant(*bin->fRight, 1)) {
904 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400905 delete_right(&b, iter, outUpdated, outNeedsRescan);
906 }
907 break;
908 default:
909 break;
910 }
911 }
912 default:
913 break;
914 }
915}
916
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400917// returns true if this statement could potentially execute a break at the current level (we ignore
918// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
Ethan Nicholas5005a222018-08-24 13:06:27 -0400919static bool contains_conditional_break(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400920 switch (s.fKind) {
921 case Statement::kBlock_Kind:
922 for (const auto& sub : ((Block&) s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -0400923 if (contains_conditional_break(*sub, inConditional)) {
924 return true;
925 }
926 }
927 return false;
928 case Statement::kBreak_Kind:
929 return inConditional;
930 case Statement::kIf_Kind: {
931 const IfStatement& i = (IfStatement&) s;
932 return contains_conditional_break(*i.fIfTrue, true) ||
933 (i.fIfFalse && contains_conditional_break(*i.fIfFalse, true));
934 }
935 default:
936 return false;
937 }
938}
939
940// returns true if this statement definitely executes a break at the current level (we ignore
941// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
942static bool contains_unconditional_break(Statement& s) {
943 switch (s.fKind) {
944 case Statement::kBlock_Kind:
945 for (const auto& sub : ((Block&) s).fStatements) {
946 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400947 return true;
948 }
949 }
950 return false;
951 case Statement::kBreak_Kind:
952 return true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400953 default:
954 return false;
955 }
956}
957
958// Returns a block containing all of the statements that will be run if the given case matches
959// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
960// broken by this call and must then be discarded).
961// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
962// when break statements appear inside conditionals.
963static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
964 bool capturing = false;
965 std::vector<std::unique_ptr<Statement>*> statementPtrs;
966 for (const auto& current : s->fCases) {
967 if (current.get() == c) {
968 capturing = true;
969 }
970 if (capturing) {
971 for (auto& stmt : current->fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -0400972 if (contains_conditional_break(*stmt, s->fKind == Statement::kIf_Kind)) {
973 return nullptr;
974 }
975 if (contains_unconditional_break(*stmt)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400976 capturing = false;
977 break;
978 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400979 statementPtrs.push_back(&stmt);
980 }
981 if (!capturing) {
982 break;
983 }
984 }
985 }
986 std::vector<std::unique_ptr<Statement>> statements;
987 for (const auto& s : statementPtrs) {
988 statements.push_back(std::move(*s));
989 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700990 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400991}
992
Ethan Nicholascb670962017-04-20 19:31:52 -0400993void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400994 BasicBlock& b,
995 std::vector<BasicBlock::Node>::iterator* iter,
996 std::unordered_set<const Variable*>* undefinedVariables,
997 bool* outUpdated,
998 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400999 Statement* stmt = (*iter)->statement()->get();
1000 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001001 case Statement::kVarDeclaration_Kind: {
1002 const auto& varDecl = (VarDeclaration&) *stmt;
1003 if (varDecl.fVar->dead() &&
1004 (!varDecl.fValue ||
1005 !varDecl.fValue->hasSideEffects())) {
1006 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001007 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001008 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1009 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001010 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001011 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001012 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001013 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001014 }
1015 break;
1016 }
1017 case Statement::kIf_Kind: {
1018 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001019 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1020 // constant if, collapse down to a single branch
1021 if (((BoolLiteral&) *i.fTest).fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001022 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001023 (*iter)->setStatement(std::move(i.fIfTrue));
1024 } else {
1025 if (i.fIfFalse) {
1026 (*iter)->setStatement(std::move(i.fIfFalse));
1027 } else {
1028 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1029 }
1030 }
1031 *outUpdated = true;
1032 *outNeedsRescan = true;
1033 break;
1034 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001035 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1036 // else block doesn't do anything, remove it
1037 i.fIfFalse.reset();
1038 *outUpdated = true;
1039 *outNeedsRescan = true;
1040 }
1041 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1042 // if block doesn't do anything, no else block
1043 if (i.fTest->hasSideEffects()) {
1044 // test has side effects, keep it
1045 (*iter)->setStatement(std::unique_ptr<Statement>(
1046 new ExpressionStatement(std::move(i.fTest))));
1047 } else {
1048 // no if, no else, no test side effects, kill the whole if
1049 // statement
1050 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1051 }
1052 *outUpdated = true;
1053 *outNeedsRescan = true;
1054 }
1055 break;
1056 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001057 case Statement::kSwitch_Kind: {
1058 SwitchStatement& s = (SwitchStatement&) *stmt;
1059 if (s.fValue->isConstant()) {
1060 // switch is constant, replace it with the case that matches
1061 bool found = false;
1062 SwitchCase* defaultCase = nullptr;
1063 for (const auto& c : s.fCases) {
1064 if (!c->fValue) {
1065 defaultCase = c.get();
1066 continue;
1067 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001068 SkASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001069 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001070 if (found) {
1071 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1072 if (newBlock) {
1073 (*iter)->setStatement(std::move(newBlock));
1074 break;
1075 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001076 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001077 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001078 "static switch contains non-static conditional break");
1079 s.fIsStatic = false;
1080 }
1081 return; // can't simplify
1082 }
1083 }
1084 }
1085 if (!found) {
1086 // no matching case. use default if it exists, or kill the whole thing
1087 if (defaultCase) {
1088 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1089 if (newBlock) {
1090 (*iter)->setStatement(std::move(newBlock));
1091 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001092 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001093 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001094 "static switch contains non-static conditional break");
1095 s.fIsStatic = false;
1096 }
1097 return; // can't simplify
1098 }
1099 } else {
1100 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1101 }
1102 }
1103 *outUpdated = true;
1104 *outNeedsRescan = true;
1105 }
1106 break;
1107 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001108 case Statement::kExpression_Kind: {
1109 ExpressionStatement& e = (ExpressionStatement&) *stmt;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001110 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001111 if (!e.fExpression->hasSideEffects()) {
1112 // Expression statement with no side effects, kill it
1113 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1114 *outNeedsRescan = true;
1115 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001116 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001117 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1118 *outUpdated = true;
1119 }
1120 break;
1121 }
1122 default:
1123 break;
1124 }
1125}
1126
1127void Compiler::scanCFG(FunctionDefinition& f) {
1128 CFG cfg = CFGGenerator().getCFG(f);
1129 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001130
1131 // check for unreachable code
1132 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001133 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001134 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001135 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001136 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1137 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001138 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001139 break;
1140 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001141 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001142 break;
1143 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001144 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001145 }
1146 }
1147 if (fErrorCount) {
1148 return;
1149 }
1150
Ethan Nicholascb670962017-04-20 19:31:52 -04001151 // check for dead code & undefined variables, perform constant propagation
1152 std::unordered_set<const Variable*> undefinedVariables;
1153 bool updated;
1154 bool needsRescan = false;
1155 do {
1156 if (needsRescan) {
1157 cfg = CFGGenerator().getCFG(f);
1158 this->computeDataFlow(&cfg);
1159 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001160 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001161
1162 updated = false;
1163 for (BasicBlock& b : cfg.fBlocks) {
1164 DefinitionMap definitions = b.fBefore;
1165
1166 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1167 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1168 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1169 &needsRescan);
1170 } else {
1171 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1172 &needsRescan);
1173 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001174 if (needsRescan) {
1175 break;
1176 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001177 this->addDefinitions(*iter, &definitions);
1178 }
1179 }
1180 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001181 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001182
Ethan Nicholas91a10532017-06-22 11:24:38 -04001183 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001184 for (BasicBlock& b : cfg.fBlocks) {
1185 DefinitionMap definitions = b.fBefore;
1186
Ethan Nicholas91a10532017-06-22 11:24:38 -04001187 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001188 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1189 const Statement& s = **iter->statement();
1190 switch (s.fKind) {
1191 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001192 if (((const IfStatement&) s).fIsStatic &&
1193 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001194 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001195 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001196 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001197 break;
1198 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001199 if (((const SwitchStatement&) s).fIsStatic &&
1200 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001201 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001202 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001203 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001204 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001205 case Statement::kVarDeclarations_Kind: {
1206 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1207 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1208 if ((*varIter)->fKind == Statement::kNop_Kind) {
1209 varIter = decls.fVars.erase(varIter);
1210 } else {
1211 ++varIter;
1212 }
1213 }
1214 if (!decls.fVars.size()) {
1215 iter = b.fNodes.erase(iter);
1216 } else {
1217 ++iter;
1218 }
1219 break;
1220 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001221 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001222 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001223 break;
1224 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001225 } else {
1226 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001227 }
1228 }
1229 }
1230
ethannicholas22f939e2016-10-13 13:25:34 -07001231 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001232 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001233 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001234 this->error(f.fOffset, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001235 }
1236 }
1237}
1238
Ethan Nicholas91164d12019-05-15 15:29:54 -04001239void Compiler::registerExternalValue(ExternalValue* value) {
1240 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1241}
1242
1243Symbol* Compiler::takeOwnership(std::unique_ptr<Symbol> symbol) {
1244 return fIRGenerator->fRootSymbolTable->takeOwnership(std::move(symbol));
1245}
1246
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001247std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001248 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001249 fErrorText = "";
1250 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001251 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001252 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001253 switch (kind) {
1254 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001255 inherited = &fVertexInclude;
1256 fIRGenerator->fSymbolTable = fVertexSymbolTable;
1257 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001258 break;
1259 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001260 inherited = &fFragmentInclude;
1261 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
1262 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001263 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001264 case Program::kGeometry_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001265 inherited = &fGeometryInclude;
1266 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
1267 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001268 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001269 case Program::kFragmentProcessor_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001270 inherited = nullptr;
1271 fIRGenerator->start(&settings, nullptr);
Robert Phillipsfe8da172018-01-24 14:52:02 +00001272 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001273 &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001274 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001275 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001276 case Program::kPipelineStage_Kind: // fall through
1277 case Program::kGeneric_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001278 inherited = nullptr;
1279 fIRGenerator->start(&settings, nullptr);
Ethan Nicholas746035a2019-04-23 13:31:09 -04001280 fIRGenerator->convertProgram(kind, SKSL_GENERIC_INCLUDE,
1281 strlen(SKSL_GENERIC_INCLUDE), *fTypes, &elements);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001282 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
1283 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001284 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001285 for (auto& element : elements) {
1286 if (element->fKind == ProgramElement::kEnum_Kind) {
1287 ((Enum&) *element).fBuiltin = true;
1288 }
1289 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001290 std::unique_ptr<String> textPtr(new String(std::move(text)));
1291 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001292 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001293 auto result = std::unique_ptr<Program>(new Program(kind,
1294 std::move(textPtr),
1295 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001296 fContext,
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001297 inherited,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001298 std::move(elements),
1299 fIRGenerator->fSymbolTable,
1300 fIRGenerator->fInputs));
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001301 if (fErrorCount) {
1302 return nullptr;
1303 }
1304 return result;
1305}
1306
Ethan Nicholas00543112018-07-31 09:44:36 -04001307bool Compiler::optimize(Program& program) {
1308 SkASSERT(!fErrorCount);
1309 if (!program.fIsOptimized) {
1310 program.fIsOptimized = true;
1311 fIRGenerator->fKind = program.fKind;
1312 fIRGenerator->fSettings = &program.fSettings;
1313 for (auto& element : program) {
1314 if (element.fKind == ProgramElement::kFunction_Kind) {
1315 this->scanCFG((FunctionDefinition&) element);
1316 }
1317 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001318 if (program.fKind != Program::kFragmentProcessor_Kind) {
1319 for (auto iter = program.fElements.begin(); iter != program.fElements.end();) {
1320 if ((*iter)->fKind == ProgramElement::kVar_Kind) {
1321 VarDeclarations& vars = (VarDeclarations&) **iter;
1322 for (auto varIter = vars.fVars.begin(); varIter != vars.fVars.end();) {
1323 const Variable& var = *((VarDeclaration&) **varIter).fVar;
1324 if (var.dead()) {
1325 varIter = vars.fVars.erase(varIter);
1326 } else {
1327 ++varIter;
1328 }
1329 }
1330 if (vars.fVars.size() == 0) {
1331 iter = program.fElements.erase(iter);
1332 continue;
1333 }
1334 }
1335 ++iter;
1336 }
1337 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001338 }
1339 return fErrorCount == 0;
1340}
1341
1342std::unique_ptr<Program> Compiler::specialize(
1343 Program& program,
1344 const std::unordered_map<SkSL::String, SkSL::Program::Settings::Value>& inputs) {
1345 std::vector<std::unique_ptr<ProgramElement>> elements;
1346 for (const auto& e : program) {
1347 elements.push_back(e.clone());
1348 }
1349 Program::Settings settings;
1350 settings.fCaps = program.fSettings.fCaps;
1351 for (auto iter = inputs.begin(); iter != inputs.end(); ++iter) {
1352 settings.fArgs.insert(*iter);
1353 }
1354 std::unique_ptr<Program> result(new Program(program.fKind,
1355 nullptr,
1356 settings,
1357 program.fContext,
1358 program.fInheritedElements,
1359 std::move(elements),
1360 program.fSymbols,
1361 program.fInputs));
1362 return result;
1363}
1364
1365bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1366 if (!this->optimize(program)) {
1367 return false;
1368 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001369#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001370 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001371 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001372 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001373 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001374 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001375 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001376 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001377 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001378 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001379 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1380 SkDebugf("SPIR-V validation error: %s\n", m);
1381 };
1382 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001383 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001384 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001385 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001386 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001387 }
1388#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001389 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001390 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001391 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001392 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001393#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001394 return result;
1395}
1396
Ethan Nicholas00543112018-07-31 09:44:36 -04001397bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001398 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001399 bool result = this->toSPIRV(program, buffer);
1400 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001401 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001402 }
1403 return result;
1404}
1405
Ethan Nicholas00543112018-07-31 09:44:36 -04001406bool Compiler::toGLSL(Program& program, OutputStream& out) {
1407 if (!this->optimize(program)) {
1408 return false;
1409 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001410 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001411 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001412 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001413 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001414 return result;
1415}
1416
Ethan Nicholas00543112018-07-31 09:44:36 -04001417bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001418 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001419 bool result = this->toGLSL(program, buffer);
1420 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001421 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001422 }
1423 return result;
1424}
1425
Ethan Nicholas00543112018-07-31 09:44:36 -04001426bool Compiler::toMetal(Program& program, OutputStream& out) {
1427 if (!this->optimize(program)) {
1428 return false;
1429 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001430 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001431 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001432 return result;
1433}
1434
Ethan Nicholas00543112018-07-31 09:44:36 -04001435bool Compiler::toMetal(Program& program, String* out) {
1436 if (!this->optimize(program)) {
1437 return false;
1438 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001439 StringStream buffer;
1440 bool result = this->toMetal(program, buffer);
1441 if (result) {
1442 *out = buffer.str();
1443 }
1444 return result;
1445}
1446
Ethan Nicholas00543112018-07-31 09:44:36 -04001447bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1448 if (!this->optimize(program)) {
1449 return false;
1450 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001451 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001452 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001453 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001454 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001455 return result;
1456}
1457
Ethan Nicholas00543112018-07-31 09:44:36 -04001458bool Compiler::toH(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 HCodeGenerator 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 Nicholas00543112018-07-31 09:44:36 -04001466 return result;
1467}
1468
1469bool Compiler::toPipelineStage(const Program& program, String* out,
1470 std::vector<FormatArg>* outFormatArgs) {
1471 SkASSERT(program.fIsOptimized);
1472 fSource = program.fSource.get();
1473 StringStream buffer;
1474 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outFormatArgs);
1475 bool result = cg.generateCode();
1476 fSource = nullptr;
1477 if (result) {
1478 *out = buffer.str();
1479 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001480 return result;
1481}
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001482
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001483std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
1484 if (!this->optimize(program)) {
1485 return nullptr;
1486 }
1487 std::unique_ptr<ByteCode> result(new ByteCode());
1488 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1489 if (cg.generateCode()) {
1490 return result;
1491 }
1492 return nullptr;
1493}
1494
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001495const char* Compiler::OperatorName(Token::Kind kind) {
1496 switch (kind) {
1497 case Token::PLUS: return "+";
1498 case Token::MINUS: return "-";
1499 case Token::STAR: return "*";
1500 case Token::SLASH: return "/";
1501 case Token::PERCENT: return "%";
1502 case Token::SHL: return "<<";
1503 case Token::SHR: return ">>";
1504 case Token::LOGICALNOT: return "!";
1505 case Token::LOGICALAND: return "&&";
1506 case Token::LOGICALOR: return "||";
1507 case Token::LOGICALXOR: return "^^";
1508 case Token::BITWISENOT: return "~";
1509 case Token::BITWISEAND: return "&";
1510 case Token::BITWISEOR: return "|";
1511 case Token::BITWISEXOR: return "^";
1512 case Token::EQ: return "=";
1513 case Token::EQEQ: return "==";
1514 case Token::NEQ: return "!=";
1515 case Token::LT: return "<";
1516 case Token::GT: return ">";
1517 case Token::LTEQ: return "<=";
1518 case Token::GTEQ: return ">=";
1519 case Token::PLUSEQ: return "+=";
1520 case Token::MINUSEQ: return "-=";
1521 case Token::STAREQ: return "*=";
1522 case Token::SLASHEQ: return "/=";
1523 case Token::PERCENTEQ: return "%=";
1524 case Token::SHLEQ: return "<<=";
1525 case Token::SHREQ: return ">>=";
1526 case Token::LOGICALANDEQ: return "&&=";
1527 case Token::LOGICALOREQ: return "||=";
1528 case Token::LOGICALXOREQ: return "^^=";
1529 case Token::BITWISEANDEQ: return "&=";
1530 case Token::BITWISEOREQ: return "|=";
1531 case Token::BITWISEXOREQ: return "^=";
1532 case Token::PLUSPLUS: return "++";
1533 case Token::MINUSMINUS: return "--";
1534 case Token::COMMA: return ",";
1535 default:
1536 ABORT("unsupported operator: %d\n", kind);
1537 }
1538}
1539
1540
1541bool Compiler::IsAssignment(Token::Kind op) {
1542 switch (op) {
1543 case Token::EQ: // fall through
1544 case Token::PLUSEQ: // fall through
1545 case Token::MINUSEQ: // fall through
1546 case Token::STAREQ: // fall through
1547 case Token::SLASHEQ: // fall through
1548 case Token::PERCENTEQ: // fall through
1549 case Token::SHLEQ: // fall through
1550 case Token::SHREQ: // fall through
1551 case Token::BITWISEOREQ: // fall through
1552 case Token::BITWISEXOREQ: // fall through
1553 case Token::BITWISEANDEQ: // fall through
1554 case Token::LOGICALOREQ: // fall through
1555 case Token::LOGICALXOREQ: // fall through
1556 case Token::LOGICALANDEQ:
1557 return true;
1558 default:
1559 return false;
1560 }
1561}
1562
1563Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001564 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001565 int line = 1;
1566 int column = 1;
1567 for (int i = 0; i < offset; i++) {
1568 if ((*fSource)[i] == '\n') {
1569 ++line;
1570 column = 1;
1571 }
1572 else {
1573 ++column;
1574 }
1575 }
1576 return Position(line, column);
1577}
1578
1579void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001580 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001581 Position pos = this->position(offset);
1582 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001583}
1584
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001585String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001586 this->writeErrorCount();
1587 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001588 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001589 return result;
1590}
1591
1592void Compiler::writeErrorCount() {
1593 if (fErrorCount) {
1594 fErrorText += to_string(fErrorCount) + " error";
1595 if (fErrorCount > 1) {
1596 fErrorText += "s";
1597 }
1598 fErrorText += "\n";
1599 }
1600}
1601
ethannicholasb3058bd2016-07-01 08:22:01 -07001602} // namespace