blob: 09af06b4ebea3fe9068ed1e6ca01a6767ef5407e [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
ethannicholasb3058bd2016-07-01 08:22:01 -07008#include "SkSLCompiler.h"
9
ethannicholas22f939e2016-10-13 13:25:34 -070010#include "SkSLCFGGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040011#include "SkSLCPPCodeGenerator.h"
Ethan Nicholas941e7e22016-12-12 15:33:30 -050012#include "SkSLGLSLCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040013#include "SkSLHCodeGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070014#include "SkSLIRGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040015#include "SkSLMetalCodeGenerator.h"
Ethan Nicholas00543112018-07-31 09:44:36 -040016#include "SkSLPipelineStageCodeGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070017#include "SkSLSPIRVCodeGenerator.h"
Ethan Nicholasaae47c82017-11-10 15:34:03 -050018#include "ir/SkSLEnum.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070019#include "ir/SkSLExpression.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040020#include "ir/SkSLExpressionStatement.h"
Ethan Nicholasc6a19f12018-03-29 16:46:56 -040021#include "ir/SkSLFunctionCall.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070022#include "ir/SkSLIntLiteral.h"
ethannicholas5961bc92016-10-12 06:39:56 -070023#include "ir/SkSLModifiersDeclaration.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040024#include "ir/SkSLNop.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070025#include "ir/SkSLSymbolTable.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040026#include "ir/SkSLTernaryExpression.h"
ethannicholasddb37d62016-10-20 09:54:00 -070027#include "ir/SkSLUnresolvedFunction.h"
ethannicholas22f939e2016-10-13 13:25:34 -070028#include "ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070029
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040030#ifdef SK_ENABLE_SPIRV_VALIDATION
31#include "spirv-tools/libspirv.hpp"
32#endif
33
ethannicholasb3058bd2016-07-01 08:22:01 -070034// include the built-in shader symbols as static strings
35
Ethan Nicholas79707652017-11-16 11:20:11 -050036#define STRINGIFY(x) #x
37
ethannicholas5961bc92016-10-12 06:39:56 -070038static const char* SKSL_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050039#include "sksl.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070040;
41
ethannicholas5961bc92016-10-12 06:39:56 -070042static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050043#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070044;
45
ethannicholas5961bc92016-10-12 06:39:56 -070046static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050047#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070048;
49
Ethan Nicholas52cad152017-02-16 16:37:32 -050050static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050051#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050052;
53
Ethan Nicholas762466e2017-06-29 10:03:38 -040054static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050055#include "sksl_enums.inc"
56#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040057;
58
Ethan Nicholas00543112018-07-31 09:44:36 -040059static const char* SKSL_PIPELINE_STAGE_INCLUDE =
Ethan Nicholas222e2752018-10-11 11:21:34 -040060#include "sksl_enums.inc"
Ethan Nicholas00543112018-07-31 09:44:36 -040061#include "sksl_pipeline.inc"
Ethan Nicholas26a9aad2018-03-27 14:10:52 -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;
ethannicholas22f939e2016-10-13 13:25:34 -0700299 default:
300 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400301 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700302 }
303}
304
305// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400306void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500307 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700308 switch (node.fKind) {
309 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400310 SkASSERT(node.expression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400311 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500312 switch (expr->fKind) {
313 case Expression::kBinary_Kind: {
314 BinaryExpression* b = (BinaryExpression*) expr;
315 if (b->fOperator == Token::EQ) {
316 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700317 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500318 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400319 b->fLeft.get(),
320 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
321 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500322
323 }
324 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700325 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400326 case Expression::kFunctionCall_Kind: {
327 const FunctionCall& c = (const FunctionCall&) *expr;
328 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
329 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
330 this->addDefinition(
331 c.fArguments[i].get(),
332 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
333 definitions);
334 }
335 }
336 break;
337 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500338 case Expression::kPrefix_Kind: {
339 const PrefixExpression* p = (PrefixExpression*) expr;
340 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
341 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400342 p->fOperand.get(),
343 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
344 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500345 }
346 break;
347 }
348 case Expression::kPostfix_Kind: {
349 const PostfixExpression* p = (PostfixExpression*) 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 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400358 case Expression::kVariableReference_Kind: {
359 const VariableReference* v = (VariableReference*) expr;
360 if (v->fRefKind != VariableReference::kRead_RefKind) {
361 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400362 v,
363 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
364 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400365 }
366 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500367 default:
368 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700369 }
370 break;
371 }
372 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400373 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000374 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
375 VarDeclaration& vd = (VarDeclaration&) *stmt;
376 if (vd.fValue) {
377 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700378 }
379 }
380 break;
381 }
382 }
383}
384
385void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
386 BasicBlock& block = cfg->fBlocks[blockId];
387
388 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500389 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700390 for (const BasicBlock::Node& n : block.fNodes) {
391 this->addDefinitions(n, &after);
392 }
393
394 // propagate definitions to exits
395 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400396 if (exitId == blockId) {
397 continue;
398 }
ethannicholas22f939e2016-10-13 13:25:34 -0700399 BasicBlock& exit = cfg->fBlocks[exitId];
400 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500401 std::unique_ptr<Expression>* e1 = pair.second;
402 auto found = exit.fBefore.find(pair.first);
403 if (found == exit.fBefore.end()) {
404 // exit has no definition for it, just copy it
405 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700406 exit.fBefore[pair.first] = e1;
407 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500408 // exit has a (possibly different) value already defined
409 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700410 if (e1 != e2) {
411 // definition has changed, merge and add exit block to worklist
412 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500413 if (e1 && e2) {
414 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400415 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500416 } else {
417 exit.fBefore[pair.first] = nullptr;
418 }
ethannicholas22f939e2016-10-13 13:25:34 -0700419 }
420 }
421 }
422 }
423}
424
425// returns a map which maps all local variables in the function to null, indicating that their value
426// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500427static DefinitionMap compute_start_state(const CFG& cfg) {
428 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400429 for (const auto& block : cfg.fBlocks) {
430 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700431 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400432 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400433 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700434 if (s->fKind == Statement::kVarDeclarations_Kind) {
435 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000436 for (const auto& decl : vd->fDeclaration->fVars) {
437 if (decl->fKind == Statement::kVarDeclaration_Kind) {
438 result[((VarDeclaration&) *decl).fVar] = nullptr;
439 }
Mike Klein6ad99092016-10-26 10:35:22 -0400440 }
ethannicholas22f939e2016-10-13 13:25:34 -0700441 }
442 }
443 }
444 }
445 return result;
446}
447
Ethan Nicholascb670962017-04-20 19:31:52 -0400448/**
449 * Returns true if assigning to this lvalue has no effect.
450 */
451static bool is_dead(const Expression& lvalue) {
452 switch (lvalue.fKind) {
453 case Expression::kVariableReference_Kind:
454 return ((VariableReference&) lvalue).fVariable.dead();
455 case Expression::kSwizzle_Kind:
456 return is_dead(*((Swizzle&) lvalue).fBase);
457 case Expression::kFieldAccess_Kind:
458 return is_dead(*((FieldAccess&) lvalue).fBase);
459 case Expression::kIndex_Kind: {
460 const IndexExpression& idx = (IndexExpression&) lvalue;
461 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
462 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500463 case Expression::kTernary_Kind: {
464 const TernaryExpression& t = (TernaryExpression&) lvalue;
465 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
466 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400467 default:
468 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
469 }
470}
ethannicholas22f939e2016-10-13 13:25:34 -0700471
Ethan Nicholascb670962017-04-20 19:31:52 -0400472/**
473 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
474 * to a dead target and lack of side effects on the left hand side.
475 */
476static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700477 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400478 return false;
479 }
480 return is_dead(*b.fLeft);
481}
482
483void Compiler::computeDataFlow(CFG* cfg) {
484 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700485 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400486 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700487 workList.insert(i);
488 }
489 while (workList.size()) {
490 BlockId next = *workList.begin();
491 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400492 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700493 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400494}
495
496/**
497 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
498 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
499 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
500 * need to be regenerated).
501 */
502bool try_replace_expression(BasicBlock* b,
503 std::vector<BasicBlock::Node>::iterator* iter,
504 std::unique_ptr<Expression>* newExpression) {
505 std::unique_ptr<Expression>* target = (*iter)->expression();
506 if (!b->tryRemoveExpression(iter)) {
507 *target = std::move(*newExpression);
508 return false;
509 }
510 *target = std::move(*newExpression);
511 return b->tryInsertExpression(iter, target);
512}
513
514/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400515 * Returns true if the expression is a constant numeric literal with the specified value, or a
516 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400517 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400518bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400519 switch (expr.fKind) {
520 case Expression::kIntLiteral_Kind:
521 return ((IntLiteral&) expr).fValue == value;
522 case Expression::kFloatLiteral_Kind:
523 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400524 case Expression::kConstructor_Kind: {
525 Constructor& c = (Constructor&) expr;
526 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
527 for (int i = 0; i < c.fType.columns(); ++i) {
528 if (!is_constant(c.getVecComponent(i), value)) {
529 return false;
530 }
531 }
532 return true;
533 }
534 return false;
535 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400536 default:
537 return false;
538 }
539}
540
541/**
542 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
543 * and CFG structures).
544 */
545void delete_left(BasicBlock* b,
546 std::vector<BasicBlock::Node>::iterator* iter,
547 bool* outUpdated,
548 bool* outNeedsRescan) {
549 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400550 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400551 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400552 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400553 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400554 bool result;
555 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400556 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400557 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400558 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400559 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400560 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400561 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400562 *outNeedsRescan = true;
563 return;
564 }
565 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400566 *outNeedsRescan = true;
567 return;
568 }
569 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400570 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
571 (*iter)->expression() != &bin.fRight) {
572 *outNeedsRescan = true;
573 return;
574 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400575 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400576 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400577}
578
579/**
580 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
581 * CFG structures).
582 */
583void delete_right(BasicBlock* b,
584 std::vector<BasicBlock::Node>::iterator* iter,
585 bool* outUpdated,
586 bool* outNeedsRescan) {
587 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400588 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400589 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400590 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400591 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400592 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
593 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400594 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400595 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400596 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400597 *target = std::move(bin.fLeft);
598 if (*iter == b->fNodes.begin()) {
599 *outNeedsRescan = true;
600 return;
601 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400602 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400603 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
604 (*iter)->expression() != &bin.fLeft)) {
605 *outNeedsRescan = true;
606 return;
607 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400608 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400609 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400610}
611
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400612/**
613 * Constructs the specified type using a single argument.
614 */
615static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
616 std::vector<std::unique_ptr<Expression>> args;
617 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700618 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400619 return result;
620}
621
622/**
623 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
624 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
625 */
626static void vectorize(BasicBlock* b,
627 std::vector<BasicBlock::Node>::iterator* iter,
628 const Type& type,
629 std::unique_ptr<Expression>* otherExpression,
630 bool* outUpdated,
631 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400632 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
633 SkASSERT(type.kind() == Type::kVector_Kind);
634 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400635 *outUpdated = true;
636 std::unique_ptr<Expression>* target = (*iter)->expression();
637 if (!b->tryRemoveExpression(iter)) {
638 *target = construct(type, std::move(*otherExpression));
639 *outNeedsRescan = true;
640 } else {
641 *target = construct(type, std::move(*otherExpression));
642 if (!b->tryInsertExpression(iter, target)) {
643 *outNeedsRescan = true;
644 }
645 }
646}
647
648/**
649 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
650 * left to yield vec<n>(x).
651 */
652static void vectorize_left(BasicBlock* b,
653 std::vector<BasicBlock::Node>::iterator* iter,
654 bool* outUpdated,
655 bool* outNeedsRescan) {
656 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
657 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
658}
659
660/**
661 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
662 * right to yield vec<n>(y).
663 */
664static void vectorize_right(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.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
670}
671
672// Mark that an expression which we were writing to is no longer being written to
673void clear_write(const Expression& expr) {
674 switch (expr.fKind) {
675 case Expression::kVariableReference_Kind: {
676 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
677 break;
678 }
679 case Expression::kFieldAccess_Kind:
680 clear_write(*((FieldAccess&) expr).fBase);
681 break;
682 case Expression::kSwizzle_Kind:
683 clear_write(*((Swizzle&) expr).fBase);
684 break;
685 case Expression::kIndex_Kind:
686 clear_write(*((IndexExpression&) expr).fBase);
687 break;
688 default:
689 ABORT("shouldn't be writing to this kind of expression\n");
690 break;
691 }
692}
693
Ethan Nicholascb670962017-04-20 19:31:52 -0400694void Compiler::simplifyExpression(DefinitionMap& definitions,
695 BasicBlock& b,
696 std::vector<BasicBlock::Node>::iterator* iter,
697 std::unordered_set<const Variable*>* undefinedVariables,
698 bool* outUpdated,
699 bool* outNeedsRescan) {
700 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400701 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400702 if ((*iter)->fConstantPropagation) {
703 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
704 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400705 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400706 if (!try_replace_expression(&b, iter, &optimized)) {
707 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400708 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400709 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400710 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400711 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400712 }
713 }
714 switch (expr->fKind) {
715 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400716 const VariableReference& ref = (VariableReference&) *expr;
717 const Variable& var = ref.fVariable;
718 if (ref.refKind() != VariableReference::kWrite_RefKind &&
719 ref.refKind() != VariableReference::kPointer_RefKind &&
720 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400721 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
722 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000723 this->error(expr->fOffset,
724 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400725 }
726 break;
727 }
728 case Expression::kTernary_Kind: {
729 TernaryExpression* t = (TernaryExpression*) expr;
730 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
731 // ternary has a constant test, replace it with either the true or
732 // false branch
733 if (((BoolLiteral&) *t->fTest).fValue) {
734 (*iter)->setExpression(std::move(t->fIfTrue));
735 } else {
736 (*iter)->setExpression(std::move(t->fIfFalse));
737 }
738 *outUpdated = true;
739 *outNeedsRescan = true;
740 }
741 break;
742 }
743 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400744 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400745 if (dead_assignment(*bin)) {
746 delete_left(&b, iter, outUpdated, outNeedsRescan);
747 break;
748 }
749 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400750 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
751 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
752 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
753 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
754 break;
755 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400756 switch (bin->fOperator) {
757 case Token::STAR:
758 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400759 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
760 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400761 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400762 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
763 } else {
764 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400765 // 1 * float4(x) -> float4(x)
766 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400767 delete_left(&b, iter, outUpdated, outNeedsRescan);
768 }
769 }
770 else if (is_constant(*bin->fLeft, 0)) {
771 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500772 bin->fRight->fType.kind() == Type::kVector_Kind &&
773 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400774 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400775 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
776 } else {
777 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400778 // float4(0) * x -> float4(0)
779 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500780 if (!bin->fRight->hasSideEffects()) {
781 delete_right(&b, iter, outUpdated, outNeedsRescan);
782 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400783 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400784 }
785 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400786 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
787 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400788 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400789 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
790 } else {
791 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400792 // float4(x) * 1 -> float4(x)
793 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400794 delete_right(&b, iter, outUpdated, outNeedsRescan);
795 }
796 }
797 else if (is_constant(*bin->fRight, 0)) {
798 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500799 bin->fRight->fType.kind() == Type::kScalar_Kind &&
800 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400801 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400802 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
803 } else {
804 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400805 // x * float4(0) -> float4(0)
806 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500807 if (!bin->fLeft->hasSideEffects()) {
808 delete_left(&b, iter, outUpdated, outNeedsRescan);
809 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400810 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400811 }
812 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400813 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400814 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400815 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
816 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400817 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400818 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
819 } else {
820 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400821 // 0 + float4(x) -> float4(x)
822 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400823 delete_left(&b, iter, outUpdated, outNeedsRescan);
824 }
825 } else if (is_constant(*bin->fRight, 0)) {
826 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
827 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400828 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400829 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
830 } else {
831 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400832 // float4(x) + 0 -> float4(x)
833 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400834 delete_right(&b, iter, outUpdated, outNeedsRescan);
835 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400836 }
837 break;
838 case Token::MINUS:
839 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400840 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
841 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400842 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400843 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
844 } else {
845 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400846 // float4(x) - 0 -> float4(x)
847 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400848 delete_right(&b, iter, outUpdated, outNeedsRescan);
849 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400850 }
851 break;
852 case Token::SLASH:
853 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400854 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
855 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400856 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400857 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
858 } else {
859 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400860 // float4(x) / 1 -> float4(x)
861 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400862 delete_right(&b, iter, outUpdated, outNeedsRescan);
863 }
864 } else if (is_constant(*bin->fLeft, 0)) {
865 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500866 bin->fRight->fType.kind() == Type::kVector_Kind &&
867 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400868 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400869 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
870 } else {
871 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400872 // float4(0) / x -> float4(0)
873 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500874 if (!bin->fRight->hasSideEffects()) {
875 delete_right(&b, iter, outUpdated, outNeedsRescan);
876 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400877 }
878 }
879 break;
880 case Token::PLUSEQ:
881 if (is_constant(*bin->fRight, 0)) {
882 clear_write(*bin->fLeft);
883 delete_right(&b, iter, outUpdated, outNeedsRescan);
884 }
885 break;
886 case Token::MINUSEQ:
887 if (is_constant(*bin->fRight, 0)) {
888 clear_write(*bin->fLeft);
889 delete_right(&b, iter, outUpdated, outNeedsRescan);
890 }
891 break;
892 case Token::STAREQ:
893 if (is_constant(*bin->fRight, 1)) {
894 clear_write(*bin->fLeft);
895 delete_right(&b, iter, outUpdated, outNeedsRescan);
896 }
897 break;
898 case Token::SLASHEQ:
899 if (is_constant(*bin->fRight, 1)) {
900 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400901 delete_right(&b, iter, outUpdated, outNeedsRescan);
902 }
903 break;
904 default:
905 break;
906 }
907 }
908 default:
909 break;
910 }
911}
912
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400913// returns true if this statement could potentially execute a break at the current level (we ignore
914// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
Ethan Nicholas5005a222018-08-24 13:06:27 -0400915static bool contains_conditional_break(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400916 switch (s.fKind) {
917 case Statement::kBlock_Kind:
918 for (const auto& sub : ((Block&) s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -0400919 if (contains_conditional_break(*sub, inConditional)) {
920 return true;
921 }
922 }
923 return false;
924 case Statement::kBreak_Kind:
925 return inConditional;
926 case Statement::kIf_Kind: {
927 const IfStatement& i = (IfStatement&) s;
928 return contains_conditional_break(*i.fIfTrue, true) ||
929 (i.fIfFalse && contains_conditional_break(*i.fIfFalse, true));
930 }
931 default:
932 return false;
933 }
934}
935
936// returns true if this statement definitely executes a break at the current level (we ignore
937// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
938static bool contains_unconditional_break(Statement& s) {
939 switch (s.fKind) {
940 case Statement::kBlock_Kind:
941 for (const auto& sub : ((Block&) s).fStatements) {
942 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400943 return true;
944 }
945 }
946 return false;
947 case Statement::kBreak_Kind:
948 return true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400949 default:
950 return false;
951 }
952}
953
954// Returns a block containing all of the statements that will be run if the given case matches
955// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
956// broken by this call and must then be discarded).
957// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
958// when break statements appear inside conditionals.
959static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
960 bool capturing = false;
961 std::vector<std::unique_ptr<Statement>*> statementPtrs;
962 for (const auto& current : s->fCases) {
963 if (current.get() == c) {
964 capturing = true;
965 }
966 if (capturing) {
967 for (auto& stmt : current->fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -0400968 if (contains_conditional_break(*stmt, s->fKind == Statement::kIf_Kind)) {
969 return nullptr;
970 }
971 if (contains_unconditional_break(*stmt)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400972 capturing = false;
973 break;
974 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400975 statementPtrs.push_back(&stmt);
976 }
977 if (!capturing) {
978 break;
979 }
980 }
981 }
982 std::vector<std::unique_ptr<Statement>> statements;
983 for (const auto& s : statementPtrs) {
984 statements.push_back(std::move(*s));
985 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700986 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400987}
988
Ethan Nicholascb670962017-04-20 19:31:52 -0400989void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400990 BasicBlock& b,
991 std::vector<BasicBlock::Node>::iterator* iter,
992 std::unordered_set<const Variable*>* undefinedVariables,
993 bool* outUpdated,
994 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400995 Statement* stmt = (*iter)->statement()->get();
996 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000997 case Statement::kVarDeclaration_Kind: {
998 const auto& varDecl = (VarDeclaration&) *stmt;
999 if (varDecl.fVar->dead() &&
1000 (!varDecl.fValue ||
1001 !varDecl.fValue->hasSideEffects())) {
1002 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001003 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001004 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1005 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001006 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001007 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001008 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001009 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001010 }
1011 break;
1012 }
1013 case Statement::kIf_Kind: {
1014 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001015 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1016 // constant if, collapse down to a single branch
1017 if (((BoolLiteral&) *i.fTest).fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001018 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001019 (*iter)->setStatement(std::move(i.fIfTrue));
1020 } else {
1021 if (i.fIfFalse) {
1022 (*iter)->setStatement(std::move(i.fIfFalse));
1023 } else {
1024 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1025 }
1026 }
1027 *outUpdated = true;
1028 *outNeedsRescan = true;
1029 break;
1030 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001031 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1032 // else block doesn't do anything, remove it
1033 i.fIfFalse.reset();
1034 *outUpdated = true;
1035 *outNeedsRescan = true;
1036 }
1037 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1038 // if block doesn't do anything, no else block
1039 if (i.fTest->hasSideEffects()) {
1040 // test has side effects, keep it
1041 (*iter)->setStatement(std::unique_ptr<Statement>(
1042 new ExpressionStatement(std::move(i.fTest))));
1043 } else {
1044 // no if, no else, no test side effects, kill the whole if
1045 // statement
1046 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1047 }
1048 *outUpdated = true;
1049 *outNeedsRescan = true;
1050 }
1051 break;
1052 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001053 case Statement::kSwitch_Kind: {
1054 SwitchStatement& s = (SwitchStatement&) *stmt;
1055 if (s.fValue->isConstant()) {
1056 // switch is constant, replace it with the case that matches
1057 bool found = false;
1058 SwitchCase* defaultCase = nullptr;
1059 for (const auto& c : s.fCases) {
1060 if (!c->fValue) {
1061 defaultCase = c.get();
1062 continue;
1063 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001064 SkASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001065 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001066 if (found) {
1067 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1068 if (newBlock) {
1069 (*iter)->setStatement(std::move(newBlock));
1070 break;
1071 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001072 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001073 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001074 "static switch contains non-static conditional break");
1075 s.fIsStatic = false;
1076 }
1077 return; // can't simplify
1078 }
1079 }
1080 }
1081 if (!found) {
1082 // no matching case. use default if it exists, or kill the whole thing
1083 if (defaultCase) {
1084 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1085 if (newBlock) {
1086 (*iter)->setStatement(std::move(newBlock));
1087 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001088 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001089 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001090 "static switch contains non-static conditional break");
1091 s.fIsStatic = false;
1092 }
1093 return; // can't simplify
1094 }
1095 } else {
1096 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1097 }
1098 }
1099 *outUpdated = true;
1100 *outNeedsRescan = true;
1101 }
1102 break;
1103 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001104 case Statement::kExpression_Kind: {
1105 ExpressionStatement& e = (ExpressionStatement&) *stmt;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001106 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001107 if (!e.fExpression->hasSideEffects()) {
1108 // Expression statement with no side effects, kill it
1109 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1110 *outNeedsRescan = true;
1111 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001112 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001113 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1114 *outUpdated = true;
1115 }
1116 break;
1117 }
1118 default:
1119 break;
1120 }
1121}
1122
1123void Compiler::scanCFG(FunctionDefinition& f) {
1124 CFG cfg = CFGGenerator().getCFG(f);
1125 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001126
1127 // check for unreachable code
1128 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001129 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001130 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001131 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001132 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1133 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001134 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001135 break;
1136 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001137 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001138 break;
1139 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001140 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001141 }
1142 }
1143 if (fErrorCount) {
1144 return;
1145 }
1146
Ethan Nicholascb670962017-04-20 19:31:52 -04001147 // check for dead code & undefined variables, perform constant propagation
1148 std::unordered_set<const Variable*> undefinedVariables;
1149 bool updated;
1150 bool needsRescan = false;
1151 do {
1152 if (needsRescan) {
1153 cfg = CFGGenerator().getCFG(f);
1154 this->computeDataFlow(&cfg);
1155 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001156 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001157
1158 updated = false;
1159 for (BasicBlock& b : cfg.fBlocks) {
1160 DefinitionMap definitions = b.fBefore;
1161
1162 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1163 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1164 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1165 &needsRescan);
1166 } else {
1167 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1168 &needsRescan);
1169 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001170 if (needsRescan) {
1171 break;
1172 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001173 this->addDefinitions(*iter, &definitions);
1174 }
1175 }
1176 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001177 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001178
Ethan Nicholas91a10532017-06-22 11:24:38 -04001179 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001180 for (BasicBlock& b : cfg.fBlocks) {
1181 DefinitionMap definitions = b.fBefore;
1182
Ethan Nicholas91a10532017-06-22 11:24:38 -04001183 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001184 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1185 const Statement& s = **iter->statement();
1186 switch (s.fKind) {
1187 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001188 if (((const IfStatement&) s).fIsStatic &&
1189 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001190 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001191 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001192 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001193 break;
1194 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001195 if (((const SwitchStatement&) s).fIsStatic &&
1196 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001197 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001198 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001199 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001200 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001201 case Statement::kVarDeclarations_Kind: {
1202 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1203 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1204 if ((*varIter)->fKind == Statement::kNop_Kind) {
1205 varIter = decls.fVars.erase(varIter);
1206 } else {
1207 ++varIter;
1208 }
1209 }
1210 if (!decls.fVars.size()) {
1211 iter = b.fNodes.erase(iter);
1212 } else {
1213 ++iter;
1214 }
1215 break;
1216 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001217 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001218 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001219 break;
1220 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001221 } else {
1222 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001223 }
1224 }
1225 }
1226
ethannicholas22f939e2016-10-13 13:25:34 -07001227 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001228 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001229 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001230 this->error(f.fOffset, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001231 }
1232 }
1233}
1234
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001235std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001236 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001237 fErrorText = "";
1238 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001239 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001240 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001241 switch (kind) {
1242 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001243 inherited = &fVertexInclude;
1244 fIRGenerator->fSymbolTable = fVertexSymbolTable;
1245 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001246 break;
1247 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001248 inherited = &fFragmentInclude;
1249 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
1250 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001251 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001252 case Program::kGeometry_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001253 inherited = &fGeometryInclude;
1254 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
1255 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001256 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001257 case Program::kFragmentProcessor_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001258 inherited = nullptr;
1259 fIRGenerator->start(&settings, nullptr);
Robert Phillipsfe8da172018-01-24 14:52:02 +00001260 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001261 &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001262 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001263 break;
Ethan Nicholas00543112018-07-31 09:44:36 -04001264 case Program::kPipelineStage_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001265 inherited = nullptr;
1266 fIRGenerator->start(&settings, nullptr);
Ethan Nicholas00543112018-07-31 09:44:36 -04001267 fIRGenerator->convertProgram(kind, SKSL_PIPELINE_STAGE_INCLUDE,
1268 strlen(SKSL_PIPELINE_STAGE_INCLUDE), *fTypes, &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001269 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001270 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001271 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001272 for (auto& element : elements) {
1273 if (element->fKind == ProgramElement::kEnum_Kind) {
1274 ((Enum&) *element).fBuiltin = true;
1275 }
1276 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001277 std::unique_ptr<String> textPtr(new String(std::move(text)));
1278 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001279 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001280 auto result = std::unique_ptr<Program>(new Program(kind,
1281 std::move(textPtr),
1282 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001283 fContext,
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001284 inherited,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001285 std::move(elements),
1286 fIRGenerator->fSymbolTable,
1287 fIRGenerator->fInputs));
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001288 if (fErrorCount) {
1289 return nullptr;
1290 }
1291 return result;
1292}
1293
Ethan Nicholas00543112018-07-31 09:44:36 -04001294bool Compiler::optimize(Program& program) {
1295 SkASSERT(!fErrorCount);
1296 if (!program.fIsOptimized) {
1297 program.fIsOptimized = true;
1298 fIRGenerator->fKind = program.fKind;
1299 fIRGenerator->fSettings = &program.fSettings;
1300 for (auto& element : program) {
1301 if (element.fKind == ProgramElement::kFunction_Kind) {
1302 this->scanCFG((FunctionDefinition&) element);
1303 }
1304 }
1305 fSource = nullptr;
1306 }
1307 return fErrorCount == 0;
1308}
1309
1310std::unique_ptr<Program> Compiler::specialize(
1311 Program& program,
1312 const std::unordered_map<SkSL::String, SkSL::Program::Settings::Value>& inputs) {
1313 std::vector<std::unique_ptr<ProgramElement>> elements;
1314 for (const auto& e : program) {
1315 elements.push_back(e.clone());
1316 }
1317 Program::Settings settings;
1318 settings.fCaps = program.fSettings.fCaps;
1319 for (auto iter = inputs.begin(); iter != inputs.end(); ++iter) {
1320 settings.fArgs.insert(*iter);
1321 }
1322 std::unique_ptr<Program> result(new Program(program.fKind,
1323 nullptr,
1324 settings,
1325 program.fContext,
1326 program.fInheritedElements,
1327 std::move(elements),
1328 program.fSymbols,
1329 program.fInputs));
1330 return result;
1331}
1332
1333bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1334 if (!this->optimize(program)) {
1335 return false;
1336 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001337#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001338 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001339 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001340 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001341 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001342 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001343 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001344 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001345 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001346 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001347 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1348 SkDebugf("SPIR-V validation error: %s\n", m);
1349 };
1350 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001351 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001352 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001353 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001354 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001355 }
1356#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001357 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001358 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001359 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001360 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001361#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001362 return result;
1363}
1364
Ethan Nicholas00543112018-07-31 09:44:36 -04001365bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001366 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001367 bool result = this->toSPIRV(program, buffer);
1368 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001369 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001370 }
1371 return result;
1372}
1373
Ethan Nicholas00543112018-07-31 09:44:36 -04001374bool Compiler::toGLSL(Program& program, OutputStream& out) {
1375 if (!this->optimize(program)) {
1376 return false;
1377 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001378 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001379 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001380 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001381 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001382 return result;
1383}
1384
Ethan Nicholas00543112018-07-31 09:44:36 -04001385bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001386 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001387 bool result = this->toGLSL(program, buffer);
1388 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001389 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001390 }
1391 return result;
1392}
1393
Ethan Nicholas00543112018-07-31 09:44:36 -04001394bool Compiler::toMetal(Program& program, OutputStream& out) {
1395 if (!this->optimize(program)) {
1396 return false;
1397 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001398 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001399 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001400 return result;
1401}
1402
Ethan Nicholas00543112018-07-31 09:44:36 -04001403bool Compiler::toMetal(Program& program, String* out) {
1404 if (!this->optimize(program)) {
1405 return false;
1406 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001407 StringStream buffer;
1408 bool result = this->toMetal(program, buffer);
1409 if (result) {
1410 *out = buffer.str();
1411 }
1412 return result;
1413}
1414
Ethan Nicholas00543112018-07-31 09:44:36 -04001415bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1416 if (!this->optimize(program)) {
1417 return false;
1418 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001419 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001420 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001421 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001422 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001423 return result;
1424}
1425
Ethan Nicholas00543112018-07-31 09:44:36 -04001426bool Compiler::toH(Program& program, String name, OutputStream& out) {
1427 if (!this->optimize(program)) {
1428 return false;
1429 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001430 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001431 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001432 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001433 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001434 return result;
1435}
1436
1437bool Compiler::toPipelineStage(const Program& program, String* out,
1438 std::vector<FormatArg>* outFormatArgs) {
1439 SkASSERT(program.fIsOptimized);
1440 fSource = program.fSource.get();
1441 StringStream buffer;
1442 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outFormatArgs);
1443 bool result = cg.generateCode();
1444 fSource = nullptr;
1445 if (result) {
1446 *out = buffer.str();
1447 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001448 return result;
1449}
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001450
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001451const char* Compiler::OperatorName(Token::Kind kind) {
1452 switch (kind) {
1453 case Token::PLUS: return "+";
1454 case Token::MINUS: return "-";
1455 case Token::STAR: return "*";
1456 case Token::SLASH: return "/";
1457 case Token::PERCENT: return "%";
1458 case Token::SHL: return "<<";
1459 case Token::SHR: return ">>";
1460 case Token::LOGICALNOT: return "!";
1461 case Token::LOGICALAND: return "&&";
1462 case Token::LOGICALOR: return "||";
1463 case Token::LOGICALXOR: return "^^";
1464 case Token::BITWISENOT: return "~";
1465 case Token::BITWISEAND: return "&";
1466 case Token::BITWISEOR: return "|";
1467 case Token::BITWISEXOR: return "^";
1468 case Token::EQ: return "=";
1469 case Token::EQEQ: return "==";
1470 case Token::NEQ: return "!=";
1471 case Token::LT: return "<";
1472 case Token::GT: return ">";
1473 case Token::LTEQ: return "<=";
1474 case Token::GTEQ: return ">=";
1475 case Token::PLUSEQ: return "+=";
1476 case Token::MINUSEQ: return "-=";
1477 case Token::STAREQ: return "*=";
1478 case Token::SLASHEQ: return "/=";
1479 case Token::PERCENTEQ: return "%=";
1480 case Token::SHLEQ: return "<<=";
1481 case Token::SHREQ: return ">>=";
1482 case Token::LOGICALANDEQ: return "&&=";
1483 case Token::LOGICALOREQ: return "||=";
1484 case Token::LOGICALXOREQ: return "^^=";
1485 case Token::BITWISEANDEQ: return "&=";
1486 case Token::BITWISEOREQ: return "|=";
1487 case Token::BITWISEXOREQ: return "^=";
1488 case Token::PLUSPLUS: return "++";
1489 case Token::MINUSMINUS: return "--";
1490 case Token::COMMA: return ",";
1491 default:
1492 ABORT("unsupported operator: %d\n", kind);
1493 }
1494}
1495
1496
1497bool Compiler::IsAssignment(Token::Kind op) {
1498 switch (op) {
1499 case Token::EQ: // fall through
1500 case Token::PLUSEQ: // fall through
1501 case Token::MINUSEQ: // fall through
1502 case Token::STAREQ: // fall through
1503 case Token::SLASHEQ: // fall through
1504 case Token::PERCENTEQ: // fall through
1505 case Token::SHLEQ: // fall through
1506 case Token::SHREQ: // fall through
1507 case Token::BITWISEOREQ: // fall through
1508 case Token::BITWISEXOREQ: // fall through
1509 case Token::BITWISEANDEQ: // fall through
1510 case Token::LOGICALOREQ: // fall through
1511 case Token::LOGICALXOREQ: // fall through
1512 case Token::LOGICALANDEQ:
1513 return true;
1514 default:
1515 return false;
1516 }
1517}
1518
1519Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001520 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001521 int line = 1;
1522 int column = 1;
1523 for (int i = 0; i < offset; i++) {
1524 if ((*fSource)[i] == '\n') {
1525 ++line;
1526 column = 1;
1527 }
1528 else {
1529 ++column;
1530 }
1531 }
1532 return Position(line, column);
1533}
1534
1535void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001536 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001537 Position pos = this->position(offset);
1538 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001539}
1540
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001541String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001542 this->writeErrorCount();
1543 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001544 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001545 return result;
1546}
1547
1548void Compiler::writeErrorCount() {
1549 if (fErrorCount) {
1550 fErrorText += to_string(fErrorCount) + " error";
1551 if (fErrorCount > 1) {
1552 fErrorText += "s";
1553 }
1554 fErrorText += "\n";
1555 }
1556}
1557
ethannicholasb3058bd2016-07-01 08:22:01 -07001558} // namespace