blob: 2d541a3b5339ea78a1ff21d84e8941a8ae1d678d [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 Nicholas941e7e22016-12-12 15:33:30 -050011#include "SkSLGLSLCodeGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070012#include "SkSLIRGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070013#include "SkSLSPIRVCodeGenerator.h"
14#include "ir/SkSLExpression.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040015#include "ir/SkSLExpressionStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070016#include "ir/SkSLIntLiteral.h"
ethannicholas5961bc92016-10-12 06:39:56 -070017#include "ir/SkSLModifiersDeclaration.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040018#include "ir/SkSLNop.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070019#include "ir/SkSLSymbolTable.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040020#include "ir/SkSLTernaryExpression.h"
ethannicholasddb37d62016-10-20 09:54:00 -070021#include "ir/SkSLUnresolvedFunction.h"
ethannicholas22f939e2016-10-13 13:25:34 -070022#include "ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070023
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040024#ifdef SK_ENABLE_SPIRV_VALIDATION
25#include "spirv-tools/libspirv.hpp"
26#endif
27
ethannicholasb3058bd2016-07-01 08:22:01 -070028#define STRINGIFY(x) #x
29
30// include the built-in shader symbols as static strings
31
ethannicholas5961bc92016-10-12 06:39:56 -070032static const char* SKSL_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070033#include "sksl.include"
34;
35
ethannicholas5961bc92016-10-12 06:39:56 -070036static const char* SKSL_VERT_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070037#include "sksl_vert.include"
38;
39
ethannicholas5961bc92016-10-12 06:39:56 -070040static const char* SKSL_FRAG_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070041#include "sksl_frag.include"
42;
43
Ethan Nicholas52cad152017-02-16 16:37:32 -050044static const char* SKSL_GEOM_INCLUDE =
45#include "sksl_geom.include"
46;
47
ethannicholasb3058bd2016-07-01 08:22:01 -070048namespace SkSL {
49
Mike Klein6ad99092016-10-26 10:35:22 -040050Compiler::Compiler()
ethannicholasb3058bd2016-07-01 08:22:01 -070051: fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -040052 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
53 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
ethannicholasd598f792016-07-25 10:08:54 -070054 fIRGenerator = new IRGenerator(&fContext, symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070055 fTypes = types;
ethannicholasd598f792016-07-25 10:08:54 -070056 #define ADD_TYPE(t) types->addWithoutOwnership(fContext.f ## t ## _Type->fName, \
57 fContext.f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070058 ADD_TYPE(Void);
59 ADD_TYPE(Float);
60 ADD_TYPE(Vec2);
61 ADD_TYPE(Vec3);
62 ADD_TYPE(Vec4);
63 ADD_TYPE(Double);
64 ADD_TYPE(DVec2);
65 ADD_TYPE(DVec3);
66 ADD_TYPE(DVec4);
67 ADD_TYPE(Int);
68 ADD_TYPE(IVec2);
69 ADD_TYPE(IVec3);
70 ADD_TYPE(IVec4);
71 ADD_TYPE(UInt);
72 ADD_TYPE(UVec2);
73 ADD_TYPE(UVec3);
74 ADD_TYPE(UVec4);
75 ADD_TYPE(Bool);
76 ADD_TYPE(BVec2);
77 ADD_TYPE(BVec3);
78 ADD_TYPE(BVec4);
79 ADD_TYPE(Mat2x2);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040080 types->addWithoutOwnership(String("mat2x2"), fContext.fMat2x2_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070081 ADD_TYPE(Mat2x3);
82 ADD_TYPE(Mat2x4);
83 ADD_TYPE(Mat3x2);
84 ADD_TYPE(Mat3x3);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040085 types->addWithoutOwnership(String("mat3x3"), fContext.fMat3x3_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070086 ADD_TYPE(Mat3x4);
87 ADD_TYPE(Mat4x2);
88 ADD_TYPE(Mat4x3);
89 ADD_TYPE(Mat4x4);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040090 types->addWithoutOwnership(String("mat4x4"), fContext.fMat4x4_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070091 ADD_TYPE(GenType);
92 ADD_TYPE(GenDType);
93 ADD_TYPE(GenIType);
94 ADD_TYPE(GenUType);
95 ADD_TYPE(GenBType);
96 ADD_TYPE(Mat);
97 ADD_TYPE(Vec);
98 ADD_TYPE(GVec);
99 ADD_TYPE(GVec2);
100 ADD_TYPE(GVec3);
101 ADD_TYPE(GVec4);
102 ADD_TYPE(DVec);
103 ADD_TYPE(IVec);
104 ADD_TYPE(UVec);
105 ADD_TYPE(BVec);
106
107 ADD_TYPE(Sampler1D);
108 ADD_TYPE(Sampler2D);
109 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700110 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700111 ADD_TYPE(SamplerCube);
112 ADD_TYPE(Sampler2DRect);
113 ADD_TYPE(Sampler1DArray);
114 ADD_TYPE(Sampler2DArray);
115 ADD_TYPE(SamplerCubeArray);
116 ADD_TYPE(SamplerBuffer);
117 ADD_TYPE(Sampler2DMS);
118 ADD_TYPE(Sampler2DMSArray);
119
Brian Salomonbf7b6202016-11-11 16:08:03 -0500120 ADD_TYPE(ISampler2D);
121
Brian Salomon2a51de82016-11-16 12:06:01 -0500122 ADD_TYPE(Image2D);
123 ADD_TYPE(IImage2D);
124
Greg Daniel64773e62016-11-22 09:44:03 -0500125 ADD_TYPE(SubpassInput);
126 ADD_TYPE(SubpassInputMS);
127
ethannicholasb3058bd2016-07-01 08:22:01 -0700128 ADD_TYPE(GSampler1D);
129 ADD_TYPE(GSampler2D);
130 ADD_TYPE(GSampler3D);
131 ADD_TYPE(GSamplerCube);
132 ADD_TYPE(GSampler2DRect);
133 ADD_TYPE(GSampler1DArray);
134 ADD_TYPE(GSampler2DArray);
135 ADD_TYPE(GSamplerCubeArray);
136 ADD_TYPE(GSamplerBuffer);
137 ADD_TYPE(GSampler2DMS);
138 ADD_TYPE(GSampler2DMSArray);
139
140 ADD_TYPE(Sampler1DShadow);
141 ADD_TYPE(Sampler2DShadow);
142 ADD_TYPE(SamplerCubeShadow);
143 ADD_TYPE(Sampler2DRectShadow);
144 ADD_TYPE(Sampler1DArrayShadow);
145 ADD_TYPE(Sampler2DArrayShadow);
146 ADD_TYPE(SamplerCubeArrayShadow);
147 ADD_TYPE(GSampler2DArrayShadow);
148 ADD_TYPE(GSamplerCubeArrayShadow);
149
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400150 String skCapsName("sk_Caps");
151 Variable* skCaps = new Variable(Position(), Modifiers(), skCapsName,
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500152 *fContext.fSkCaps_Type, Variable::kGlobal_Storage);
153 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
154
ethannicholas5961bc92016-10-12 06:39:56 -0700155 Modifiers::Flag ignored1;
156 std::vector<std::unique_ptr<ProgramElement>> ignored2;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400157 fIRGenerator->convertProgram(String(SKSL_INCLUDE), *fTypes, &ignored1, &ignored2);
ethannicholasddb37d62016-10-20 09:54:00 -0700158 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
ethannicholasb3058bd2016-07-01 08:22:01 -0700159 ASSERT(!fErrorCount);
160}
161
162Compiler::~Compiler() {
163 delete fIRGenerator;
164}
165
ethannicholas22f939e2016-10-13 13:25:34 -0700166// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500167void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
168 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700169 switch (lvalue->fKind) {
170 case Expression::kVariableReference_Kind: {
171 const Variable& var = ((VariableReference*) lvalue)->fVariable;
172 if (var.fStorage == Variable::kLocal_Storage) {
173 (*definitions)[&var] = expr;
174 }
175 break;
176 }
177 case Expression::kSwizzle_Kind:
178 // We consider the variable written to as long as at least some of its components have
179 // been written to. This will lead to some false negatives (we won't catch it if you
180 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400181 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
182 // 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 -0700183 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400184 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500185 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700186 definitions);
187 break;
188 case Expression::kIndex_Kind:
189 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400190 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500191 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700192 definitions);
193 break;
194 case Expression::kFieldAccess_Kind:
195 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400196 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500197 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700198 definitions);
199 break;
200 default:
201 // not an lvalue, can't happen
202 ASSERT(false);
203 }
204}
205
206// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400207void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500208 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700209 switch (node.fKind) {
210 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400211 ASSERT(node.expression());
212 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500213 switch (expr->fKind) {
214 case Expression::kBinary_Kind: {
215 BinaryExpression* b = (BinaryExpression*) expr;
216 if (b->fOperator == Token::EQ) {
217 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
218 } else if (Token::IsAssignment(b->fOperator)) {
219 this->addDefinition(
220 b->fLeft.get(),
221 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
222 definitions);
223
224 }
225 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700226 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500227 case Expression::kPrefix_Kind: {
228 const PrefixExpression* p = (PrefixExpression*) expr;
229 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
230 this->addDefinition(
231 p->fOperand.get(),
232 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
233 definitions);
234 }
235 break;
236 }
237 case Expression::kPostfix_Kind: {
238 const PostfixExpression* p = (PostfixExpression*) expr;
239 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
240 this->addDefinition(
241 p->fOperand.get(),
242 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
243 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500244 }
245 break;
246 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400247 case Expression::kVariableReference_Kind: {
248 const VariableReference* v = (VariableReference*) expr;
249 if (v->fRefKind != VariableReference::kRead_RefKind) {
250 this->addDefinition(
251 v,
252 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
253 definitions);
254 }
255 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500256 default:
257 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700258 }
259 break;
260 }
261 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400262 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400263 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
264 VarDeclaration& vd = (VarDeclaration&) *stmt;
265 if (vd.fValue) {
266 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700267 }
268 }
269 break;
270 }
271 }
272}
273
274void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
275 BasicBlock& block = cfg->fBlocks[blockId];
276
277 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500278 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700279 for (const BasicBlock::Node& n : block.fNodes) {
280 this->addDefinitions(n, &after);
281 }
282
283 // propagate definitions to exits
284 for (BlockId exitId : block.fExits) {
285 BasicBlock& exit = cfg->fBlocks[exitId];
286 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500287 std::unique_ptr<Expression>* e1 = pair.second;
288 auto found = exit.fBefore.find(pair.first);
289 if (found == exit.fBefore.end()) {
290 // exit has no definition for it, just copy it
291 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700292 exit.fBefore[pair.first] = e1;
293 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500294 // exit has a (possibly different) value already defined
295 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700296 if (e1 != e2) {
297 // definition has changed, merge and add exit block to worklist
298 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500299 if (e1 && e2) {
300 exit.fBefore[pair.first] =
Ethan Nicholas86a43402017-01-19 13:32:00 -0500301 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500302 } else {
303 exit.fBefore[pair.first] = nullptr;
304 }
ethannicholas22f939e2016-10-13 13:25:34 -0700305 }
306 }
307 }
308 }
309}
310
311// returns a map which maps all local variables in the function to null, indicating that their value
312// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500313static DefinitionMap compute_start_state(const CFG& cfg) {
314 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400315 for (const auto& block : cfg.fBlocks) {
316 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700317 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400318 ASSERT(node.statement());
319 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700320 if (s->fKind == Statement::kVarDeclarations_Kind) {
321 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholascb670962017-04-20 19:31:52 -0400322 for (const auto& decl : vd->fDeclaration->fVars) {
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400323 result[((VarDeclaration&) *decl).fVar] = nullptr;
Mike Klein6ad99092016-10-26 10:35:22 -0400324 }
ethannicholas22f939e2016-10-13 13:25:34 -0700325 }
326 }
327 }
328 }
329 return result;
330}
331
Ethan Nicholascb670962017-04-20 19:31:52 -0400332/**
333 * Returns true if assigning to this lvalue has no effect.
334 */
335static bool is_dead(const Expression& lvalue) {
336 switch (lvalue.fKind) {
337 case Expression::kVariableReference_Kind:
338 return ((VariableReference&) lvalue).fVariable.dead();
339 case Expression::kSwizzle_Kind:
340 return is_dead(*((Swizzle&) lvalue).fBase);
341 case Expression::kFieldAccess_Kind:
342 return is_dead(*((FieldAccess&) lvalue).fBase);
343 case Expression::kIndex_Kind: {
344 const IndexExpression& idx = (IndexExpression&) lvalue;
345 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
346 }
347 default:
348 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
349 }
350}
ethannicholas22f939e2016-10-13 13:25:34 -0700351
Ethan Nicholascb670962017-04-20 19:31:52 -0400352/**
353 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
354 * to a dead target and lack of side effects on the left hand side.
355 */
356static bool dead_assignment(const BinaryExpression& b) {
357 if (!Token::IsAssignment(b.fOperator)) {
358 return false;
359 }
360 return is_dead(*b.fLeft);
361}
362
363void Compiler::computeDataFlow(CFG* cfg) {
364 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700365 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400366 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700367 workList.insert(i);
368 }
369 while (workList.size()) {
370 BlockId next = *workList.begin();
371 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400372 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700373 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400374}
375
376/**
377 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
378 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
379 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
380 * need to be regenerated).
381 */
382bool try_replace_expression(BasicBlock* b,
383 std::vector<BasicBlock::Node>::iterator* iter,
384 std::unique_ptr<Expression>* newExpression) {
385 std::unique_ptr<Expression>* target = (*iter)->expression();
386 if (!b->tryRemoveExpression(iter)) {
387 *target = std::move(*newExpression);
388 return false;
389 }
390 *target = std::move(*newExpression);
391 return b->tryInsertExpression(iter, target);
392}
393
394/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400395 * Returns true if the expression is a constant numeric literal with the specified value, or a
396 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400397 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400398bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400399 switch (expr.fKind) {
400 case Expression::kIntLiteral_Kind:
401 return ((IntLiteral&) expr).fValue == value;
402 case Expression::kFloatLiteral_Kind:
403 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400404 case Expression::kConstructor_Kind: {
405 Constructor& c = (Constructor&) expr;
406 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
407 for (int i = 0; i < c.fType.columns(); ++i) {
408 if (!is_constant(c.getVecComponent(i), value)) {
409 return false;
410 }
411 }
412 return true;
413 }
414 return false;
415 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400416 default:
417 return false;
418 }
419}
420
421/**
422 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
423 * and CFG structures).
424 */
425void delete_left(BasicBlock* b,
426 std::vector<BasicBlock::Node>::iterator* iter,
427 bool* outUpdated,
428 bool* outNeedsRescan) {
429 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400430 std::unique_ptr<Expression>* target = (*iter)->expression();
431 ASSERT((*target)->fKind == Expression::kBinary_Kind);
432 BinaryExpression& bin = (BinaryExpression&) **target;
433 bool result;
434 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400435 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400436 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400437 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400438 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400439 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400440 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400441 *outNeedsRescan = true;
442 return;
443 }
444 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400445 *outNeedsRescan = true;
446 return;
447 }
448 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400449 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
450 (*iter)->expression() != &bin.fRight) {
451 *outNeedsRescan = true;
452 return;
453 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400454 *iter = b->fNodes.erase(*iter);
455 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400456}
457
458/**
459 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
460 * CFG structures).
461 */
462void delete_right(BasicBlock* b,
463 std::vector<BasicBlock::Node>::iterator* iter,
464 bool* outUpdated,
465 bool* outNeedsRescan) {
466 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400467 std::unique_ptr<Expression>* target = (*iter)->expression();
468 ASSERT((*target)->fKind == Expression::kBinary_Kind);
469 BinaryExpression& bin = (BinaryExpression&) **target;
470 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
471 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400472 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400473 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400474 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400475 *target = std::move(bin.fLeft);
476 if (*iter == b->fNodes.begin()) {
477 *outNeedsRescan = true;
478 return;
479 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400480 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400481 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
482 (*iter)->expression() != &bin.fLeft)) {
483 *outNeedsRescan = true;
484 return;
485 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400486 *iter = b->fNodes.erase(*iter);
487 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400488}
489
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400490/**
491 * Constructs the specified type using a single argument.
492 */
493static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
494 std::vector<std::unique_ptr<Expression>> args;
495 args.push_back(std::move(v));
496 auto result = std::unique_ptr<Expression>(new Constructor(Position(), type, std::move(args)));
497 return result;
498}
499
500/**
501 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
502 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
503 */
504static void vectorize(BasicBlock* b,
505 std::vector<BasicBlock::Node>::iterator* iter,
506 const Type& type,
507 std::unique_ptr<Expression>* otherExpression,
508 bool* outUpdated,
509 bool* outNeedsRescan) {
510 ASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
511 ASSERT(type.kind() == Type::kVector_Kind);
512 ASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
513 *outUpdated = true;
514 std::unique_ptr<Expression>* target = (*iter)->expression();
515 if (!b->tryRemoveExpression(iter)) {
516 *target = construct(type, std::move(*otherExpression));
517 *outNeedsRescan = true;
518 } else {
519 *target = construct(type, std::move(*otherExpression));
520 if (!b->tryInsertExpression(iter, target)) {
521 *outNeedsRescan = true;
522 }
523 }
524}
525
526/**
527 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
528 * left to yield vec<n>(x).
529 */
530static void vectorize_left(BasicBlock* b,
531 std::vector<BasicBlock::Node>::iterator* iter,
532 bool* outUpdated,
533 bool* outNeedsRescan) {
534 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
535 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
536}
537
538/**
539 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
540 * right to yield vec<n>(y).
541 */
542static void vectorize_right(BasicBlock* b,
543 std::vector<BasicBlock::Node>::iterator* iter,
544 bool* outUpdated,
545 bool* outNeedsRescan) {
546 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
547 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
548}
549
550// Mark that an expression which we were writing to is no longer being written to
551void clear_write(const Expression& expr) {
552 switch (expr.fKind) {
553 case Expression::kVariableReference_Kind: {
554 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
555 break;
556 }
557 case Expression::kFieldAccess_Kind:
558 clear_write(*((FieldAccess&) expr).fBase);
559 break;
560 case Expression::kSwizzle_Kind:
561 clear_write(*((Swizzle&) expr).fBase);
562 break;
563 case Expression::kIndex_Kind:
564 clear_write(*((IndexExpression&) expr).fBase);
565 break;
566 default:
567 ABORT("shouldn't be writing to this kind of expression\n");
568 break;
569 }
570}
571
Ethan Nicholascb670962017-04-20 19:31:52 -0400572void Compiler::simplifyExpression(DefinitionMap& definitions,
573 BasicBlock& b,
574 std::vector<BasicBlock::Node>::iterator* iter,
575 std::unordered_set<const Variable*>* undefinedVariables,
576 bool* outUpdated,
577 bool* outNeedsRescan) {
578 Expression* expr = (*iter)->expression()->get();
579 ASSERT(expr);
580 if ((*iter)->fConstantPropagation) {
581 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
582 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400583 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400584 if (!try_replace_expression(&b, iter, &optimized)) {
585 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400586 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400587 }
588 ASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
589 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400590 }
591 }
592 switch (expr->fKind) {
593 case Expression::kVariableReference_Kind: {
594 const Variable& var = ((VariableReference*) expr)->fVariable;
595 if (var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
596 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
597 (*undefinedVariables).insert(&var);
598 this->error(expr->fPosition,
599 "'" + var.fName + "' has not been assigned");
600 }
601 break;
602 }
603 case Expression::kTernary_Kind: {
604 TernaryExpression* t = (TernaryExpression*) expr;
605 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
606 // ternary has a constant test, replace it with either the true or
607 // false branch
608 if (((BoolLiteral&) *t->fTest).fValue) {
609 (*iter)->setExpression(std::move(t->fIfTrue));
610 } else {
611 (*iter)->setExpression(std::move(t->fIfFalse));
612 }
613 *outUpdated = true;
614 *outNeedsRescan = true;
615 }
616 break;
617 }
618 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400619 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400620 if (dead_assignment(*bin)) {
621 delete_left(&b, iter, outUpdated, outNeedsRescan);
622 break;
623 }
624 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400625 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
626 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
627 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
628 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
629 break;
630 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400631 switch (bin->fOperator) {
632 case Token::STAR:
633 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400634 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
635 bin->fRight->fType.kind() == Type::kScalar_Kind) {
636 // vec4(1) * x -> vec4(x)
637 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
638 } else {
639 // 1 * x -> x
640 // 1 * vec4(x) -> vec4(x)
641 // vec4(1) * vec4(x) -> vec4(x)
642 delete_left(&b, iter, outUpdated, outNeedsRescan);
643 }
644 }
645 else if (is_constant(*bin->fLeft, 0)) {
646 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
647 bin->fRight->fType.kind() == Type::kVector_Kind) {
648 // 0 * vec4(x) -> vec4(0)
649 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
650 } else {
651 // 0 * x -> 0
652 // vec4(0) * x -> vec4(0)
653 // vec4(0) * vec4(x) -> vec4(0)
654 delete_right(&b, iter, outUpdated, outNeedsRescan);
655 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400656 }
657 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400658 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
659 bin->fRight->fType.kind() == Type::kVector_Kind) {
660 // x * vec4(1) -> vec4(x)
661 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
662 } else {
663 // x * 1 -> x
664 // vec4(x) * 1 -> vec4(x)
665 // vec4(x) * vec4(1) -> vec4(x)
666 delete_right(&b, iter, outUpdated, outNeedsRescan);
667 }
668 }
669 else if (is_constant(*bin->fRight, 0)) {
670 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
671 bin->fRight->fType.kind() == Type::kScalar_Kind) {
672 // vec4(x) * 0 -> vec4(0)
673 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
674 } else {
675 // x * 0 -> 0
676 // x * vec4(0) -> vec4(0)
677 // vec4(x) * vec4(0) -> vec4(0)
678 delete_left(&b, iter, outUpdated, outNeedsRescan);
679 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400680 }
681 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400682 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400683 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400684 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
685 bin->fRight->fType.kind() == Type::kScalar_Kind) {
686 // vec4(0) + x -> vec4(x)
687 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
688 } else {
689 // 0 + x -> x
690 // 0 + vec4(x) -> vec4(x)
691 // vec4(0) + vec4(x) -> vec4(x)
692 delete_left(&b, iter, outUpdated, outNeedsRescan);
693 }
694 } else if (is_constant(*bin->fRight, 0)) {
695 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
696 bin->fRight->fType.kind() == Type::kVector_Kind) {
697 // x + vec4(0) -> vec4(x)
698 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
699 } else {
700 // x + 0 -> x
701 // vec4(x) + 0 -> vec4(x)
702 // vec4(x) + vec4(0) -> vec4(x)
703 delete_right(&b, iter, outUpdated, outNeedsRescan);
704 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400705 }
706 break;
707 case Token::MINUS:
708 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400709 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
710 bin->fRight->fType.kind() == Type::kVector_Kind) {
711 // x - vec4(0) -> vec4(x)
712 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
713 } else {
714 // x - 0 -> x
715 // vec4(x) - 0 -> vec4(x)
716 // vec4(x) - vec4(0) -> vec4(x)
717 delete_right(&b, iter, outUpdated, outNeedsRescan);
718 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400719 }
720 break;
721 case Token::SLASH:
722 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400723 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
724 bin->fRight->fType.kind() == Type::kVector_Kind) {
725 // x / vec4(1) -> vec4(x)
726 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
727 } else {
728 // x / 1 -> x
729 // vec4(x) / 1 -> vec4(x)
730 // vec4(x) / vec4(1) -> vec4(x)
731 delete_right(&b, iter, outUpdated, outNeedsRescan);
732 }
733 } else if (is_constant(*bin->fLeft, 0)) {
734 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
735 bin->fRight->fType.kind() == Type::kVector_Kind) {
736 // 0 / vec4(x) -> vec4(0)
737 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
738 } else {
739 // 0 / x -> 0
740 // vec4(0) / x -> vec4(0)
741 // vec4(0) / vec4(x) -> vec4(0)
742 delete_right(&b, iter, outUpdated, outNeedsRescan);
743 }
744 }
745 break;
746 case Token::PLUSEQ:
747 if (is_constant(*bin->fRight, 0)) {
748 clear_write(*bin->fLeft);
749 delete_right(&b, iter, outUpdated, outNeedsRescan);
750 }
751 break;
752 case Token::MINUSEQ:
753 if (is_constant(*bin->fRight, 0)) {
754 clear_write(*bin->fLeft);
755 delete_right(&b, iter, outUpdated, outNeedsRescan);
756 }
757 break;
758 case Token::STAREQ:
759 if (is_constant(*bin->fRight, 1)) {
760 clear_write(*bin->fLeft);
761 delete_right(&b, iter, outUpdated, outNeedsRescan);
762 }
763 break;
764 case Token::SLASHEQ:
765 if (is_constant(*bin->fRight, 1)) {
766 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400767 delete_right(&b, iter, outUpdated, outNeedsRescan);
768 }
769 break;
770 default:
771 break;
772 }
773 }
774 default:
775 break;
776 }
777}
778
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400779
780// returns true if this statement could potentially execute a break at the current level (we ignore
781// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
782static bool contains_break(Statement& s) {
783 switch (s.fKind) {
784 case Statement::kBlock_Kind:
785 for (const auto& sub : ((Block&) s).fStatements) {
786 if (contains_break(*sub)) {
787 return true;
788 }
789 }
790 return false;
791 case Statement::kBreak_Kind:
792 return true;
793 case Statement::kIf_Kind: {
794 const IfStatement& i = (IfStatement&) s;
795 return contains_break(*i.fIfTrue) || (i.fIfFalse && contains_break(*i.fIfFalse));
796 }
797 default:
798 return false;
799 }
800}
801
802// Returns a block containing all of the statements that will be run if the given case matches
803// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
804// broken by this call and must then be discarded).
805// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
806// when break statements appear inside conditionals.
807static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
808 bool capturing = false;
809 std::vector<std::unique_ptr<Statement>*> statementPtrs;
810 for (const auto& current : s->fCases) {
811 if (current.get() == c) {
812 capturing = true;
813 }
814 if (capturing) {
815 for (auto& stmt : current->fStatements) {
816 if (stmt->fKind == Statement::kBreak_Kind) {
817 capturing = false;
818 break;
819 }
820 if (contains_break(*stmt)) {
821 return nullptr;
822 }
823 statementPtrs.push_back(&stmt);
824 }
825 if (!capturing) {
826 break;
827 }
828 }
829 }
830 std::vector<std::unique_ptr<Statement>> statements;
831 for (const auto& s : statementPtrs) {
832 statements.push_back(std::move(*s));
833 }
834 return std::unique_ptr<Statement>(new Block(Position(), std::move(statements)));
835}
836
Ethan Nicholascb670962017-04-20 19:31:52 -0400837void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400838 BasicBlock& b,
839 std::vector<BasicBlock::Node>::iterator* iter,
840 std::unordered_set<const Variable*>* undefinedVariables,
841 bool* outUpdated,
842 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400843 Statement* stmt = (*iter)->statement()->get();
844 switch (stmt->fKind) {
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400845 case Statement::kVarDeclaration_Kind: {
846 const auto& varDecl = (VarDeclaration&) *stmt;
847 if (varDecl.fVar->dead() &&
848 (!varDecl.fValue ||
849 !varDecl.fValue->hasSideEffects())) {
850 if (varDecl.fValue) {
851 ASSERT((*iter)->statement()->get() == stmt);
852 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
853 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400854 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400855 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400856 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400857 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400858 }
859 break;
860 }
861 case Statement::kIf_Kind: {
862 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400863 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
864 // constant if, collapse down to a single branch
865 if (((BoolLiteral&) *i.fTest).fValue) {
866 ASSERT(i.fIfTrue);
867 (*iter)->setStatement(std::move(i.fIfTrue));
868 } else {
869 if (i.fIfFalse) {
870 (*iter)->setStatement(std::move(i.fIfFalse));
871 } else {
872 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
873 }
874 }
875 *outUpdated = true;
876 *outNeedsRescan = true;
877 break;
878 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400879 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
880 // else block doesn't do anything, remove it
881 i.fIfFalse.reset();
882 *outUpdated = true;
883 *outNeedsRescan = true;
884 }
885 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
886 // if block doesn't do anything, no else block
887 if (i.fTest->hasSideEffects()) {
888 // test has side effects, keep it
889 (*iter)->setStatement(std::unique_ptr<Statement>(
890 new ExpressionStatement(std::move(i.fTest))));
891 } else {
892 // no if, no else, no test side effects, kill the whole if
893 // statement
894 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
895 }
896 *outUpdated = true;
897 *outNeedsRescan = true;
898 }
899 break;
900 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400901 case Statement::kSwitch_Kind: {
902 SwitchStatement& s = (SwitchStatement&) *stmt;
903 if (s.fValue->isConstant()) {
904 // switch is constant, replace it with the case that matches
905 bool found = false;
906 SwitchCase* defaultCase = nullptr;
907 for (const auto& c : s.fCases) {
908 if (!c->fValue) {
909 defaultCase = c.get();
910 continue;
911 }
912 ASSERT(c->fValue->fKind == s.fValue->fKind);
913 found = c->fValue->compareConstant(fContext, *s.fValue);
914 if (found) {
915 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
916 if (newBlock) {
917 (*iter)->setStatement(std::move(newBlock));
918 break;
919 } else {
920 if (s.fIsStatic) {
921 this->error(s.fPosition,
922 "static switch contains non-static conditional break");
923 s.fIsStatic = false;
924 }
925 return; // can't simplify
926 }
927 }
928 }
929 if (!found) {
930 // no matching case. use default if it exists, or kill the whole thing
931 if (defaultCase) {
932 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
933 if (newBlock) {
934 (*iter)->setStatement(std::move(newBlock));
935 } else {
936 if (s.fIsStatic) {
937 this->error(s.fPosition,
938 "static switch contains non-static conditional break");
939 s.fIsStatic = false;
940 }
941 return; // can't simplify
942 }
943 } else {
944 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
945 }
946 }
947 *outUpdated = true;
948 *outNeedsRescan = true;
949 }
950 break;
951 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400952 case Statement::kExpression_Kind: {
953 ExpressionStatement& e = (ExpressionStatement&) *stmt;
954 ASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -0400955 if (!e.fExpression->hasSideEffects()) {
956 // Expression statement with no side effects, kill it
957 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
958 *outNeedsRescan = true;
959 }
960 ASSERT((*iter)->statement()->get() == stmt);
961 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
962 *outUpdated = true;
963 }
964 break;
965 }
966 default:
967 break;
968 }
969}
970
971void Compiler::scanCFG(FunctionDefinition& f) {
972 CFG cfg = CFGGenerator().getCFG(f);
973 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700974
975 // check for unreachable code
976 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -0400977 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -0700978 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500979 Position p;
980 switch (cfg.fBlocks[i].fNodes[0].fKind) {
981 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholascb670962017-04-20 19:31:52 -0400982 p = (*cfg.fBlocks[i].fNodes[0].statement())->fPosition;
Ethan Nicholas86a43402017-01-19 13:32:00 -0500983 break;
984 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholascb670962017-04-20 19:31:52 -0400985 p = (*cfg.fBlocks[i].fNodes[0].expression())->fPosition;
Ethan Nicholas86a43402017-01-19 13:32:00 -0500986 break;
987 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400988 this->error(p, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -0700989 }
990 }
991 if (fErrorCount) {
992 return;
993 }
994
Ethan Nicholascb670962017-04-20 19:31:52 -0400995 // check for dead code & undefined variables, perform constant propagation
996 std::unordered_set<const Variable*> undefinedVariables;
997 bool updated;
998 bool needsRescan = false;
999 do {
1000 if (needsRescan) {
1001 cfg = CFGGenerator().getCFG(f);
1002 this->computeDataFlow(&cfg);
1003 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001004 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001005
1006 updated = false;
1007 for (BasicBlock& b : cfg.fBlocks) {
1008 DefinitionMap definitions = b.fBefore;
1009
1010 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1011 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1012 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1013 &needsRescan);
1014 } else {
1015 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1016 &needsRescan);
1017 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001018 if (needsRescan) {
1019 break;
1020 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001021 this->addDefinitions(*iter, &definitions);
1022 }
1023 }
1024 } while (updated);
1025 ASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001026
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001027 // verify static ifs & switches
1028 for (BasicBlock& b : cfg.fBlocks) {
1029 DefinitionMap definitions = b.fBefore;
1030
1031 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1032 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1033 const Statement& s = **iter->statement();
1034 switch (s.fKind) {
1035 case Statement::kIf_Kind:
1036 if (((const IfStatement&) s).fIsStatic) {
1037 this->error(s.fPosition, "static if has non-static test");
1038 }
1039 break;
1040 case Statement::kSwitch_Kind:
1041 if (((const SwitchStatement&) s).fIsStatic) {
1042 this->error(s.fPosition, "static switch has non-static test");
1043 }
1044 break;
1045 default:
1046 break;
1047 }
1048 }
1049 }
1050 }
1051
ethannicholas22f939e2016-10-13 13:25:34 -07001052 // check for missing return
1053 if (f.fDeclaration.fReturnType != *fContext.fVoid_Type) {
1054 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001055 this->error(f.fPosition, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001056 }
1057 }
1058}
1059
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001060std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001061 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001062 fErrorText = "";
1063 fErrorCount = 0;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001064 fIRGenerator->start(&settings);
ethannicholasd598f792016-07-25 10:08:54 -07001065 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholas5961bc92016-10-12 06:39:56 -07001066 Modifiers::Flag ignored;
ethannicholasb3058bd2016-07-01 08:22:01 -07001067 switch (kind) {
1068 case Program::kVertex_Kind:
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001069 fIRGenerator->convertProgram(String(SKSL_VERT_INCLUDE), *fTypes, &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001070 break;
1071 case Program::kFragment_Kind:
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001072 fIRGenerator->convertProgram(String(SKSL_FRAG_INCLUDE), *fTypes, &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001073 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001074 case Program::kGeometry_Kind:
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001075 fIRGenerator->convertProgram(String(SKSL_GEOM_INCLUDE), *fTypes, &ignored, &elements);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001076 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001077 }
ethannicholasddb37d62016-10-20 09:54:00 -07001078 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
ethannicholas5961bc92016-10-12 06:39:56 -07001079 Modifiers::Flag defaultPrecision;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001080 fIRGenerator->convertProgram(text, *fTypes, &defaultPrecision, &elements);
1081 if (!fErrorCount) {
1082 for (auto& element : elements) {
1083 if (element->fKind == ProgramElement::kFunction_Kind) {
1084 this->scanCFG((FunctionDefinition&) *element);
1085 }
1086 }
1087 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001088 auto result = std::unique_ptr<Program>(new Program(kind, settings, defaultPrecision, &fContext,
1089 std::move(elements),
1090 fIRGenerator->fSymbolTable,
1091 fIRGenerator->fInputs));
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001092 fIRGenerator->finish();
ethannicholasb3058bd2016-07-01 08:22:01 -07001093 this->writeErrorCount();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001094 if (fErrorCount) {
1095 return nullptr;
1096 }
1097 return result;
1098}
1099
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001100bool Compiler::toSPIRV(const Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001101#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001102 StringStream buffer;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001103 SPIRVCodeGenerator cg(&fContext, &program, this, &buffer);
1104 bool result = cg.generateCode();
1105 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001106 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001107 ASSERT(0 == buffer.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001108 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1109 SkDebugf("SPIR-V validation error: %s\n", m);
1110 };
1111 tools.SetMessageConsumer(dumpmsg);
1112 // Verify that the SPIR-V we produced is valid. If this assert fails, check the logs prior
1113 // to the failure to see the validation errors.
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001114 ASSERT_RESULT(tools.Validate((const uint32_t*) buffer.data(), buffer.size() / 4));
1115 out.write(buffer.data(), buffer.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001116 }
1117#else
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001118 SPIRVCodeGenerator cg(&fContext, &program, this, &out);
1119 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001120#endif
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001121 this->writeErrorCount();
Ethan Nicholasce33f102016-12-09 17:22:59 -05001122 return result;
1123}
1124
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001125bool Compiler::toSPIRV(const Program& program, String* out) {
1126 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001127 bool result = this->toSPIRV(program, buffer);
1128 if (result) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001129 *out = String(buffer.data(), buffer.size());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001130 }
1131 return result;
1132}
1133
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001134bool Compiler::toGLSL(const Program& program, OutputStream& out) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001135 GLSLCodeGenerator cg(&fContext, &program, this, &out);
1136 bool result = cg.generateCode();
1137 this->writeErrorCount();
1138 return result;
1139}
1140
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001141bool Compiler::toGLSL(const Program& program, String* out) {
1142 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001143 bool result = this->toGLSL(program, buffer);
1144 if (result) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001145 *out = String(buffer.data(), buffer.size());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001146 }
1147 return result;
1148}
1149
1150
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001151void Compiler::error(Position position, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001152 fErrorCount++;
1153 fErrorText += "error: " + position.description() + ": " + msg.c_str() + "\n";
1154}
1155
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001156String Compiler::errorText() {
1157 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001158 return result;
1159}
1160
1161void Compiler::writeErrorCount() {
1162 if (fErrorCount) {
1163 fErrorText += to_string(fErrorCount) + " error";
1164 if (fErrorCount > 1) {
1165 fErrorText += "s";
1166 }
1167 fErrorText += "\n";
1168 }
1169}
1170
ethannicholasb3058bd2016-07-01 08:22:01 -07001171} // namespace