blob: f4176266c54b40cb526d54e1b6f1c2c6815d8225 [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
ethannicholas5961bc92016-10-12 06:39:56 -070010#include "ast/SkSLASTPrecision.h"
ethannicholas22f939e2016-10-13 13:25:34 -070011#include "SkSLCFGGenerator.h"
Ethan Nicholas941e7e22016-12-12 15:33:30 -050012#include "SkSLGLSLCodeGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070013#include "SkSLIRGenerator.h"
14#include "SkSLParser.h"
15#include "SkSLSPIRVCodeGenerator.h"
16#include "ir/SkSLExpression.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040017#include "ir/SkSLExpressionStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070018#include "ir/SkSLIntLiteral.h"
ethannicholas5961bc92016-10-12 06:39:56 -070019#include "ir/SkSLModifiersDeclaration.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040020#include "ir/SkSLNop.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070021#include "ir/SkSLSymbolTable.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040022#include "ir/SkSLTernaryExpression.h"
ethannicholasddb37d62016-10-20 09:54:00 -070023#include "ir/SkSLUnresolvedFunction.h"
ethannicholas22f939e2016-10-13 13:25:34 -070024#include "ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070025
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040026#ifdef SK_ENABLE_SPIRV_VALIDATION
27#include "spirv-tools/libspirv.hpp"
28#endif
29
ethannicholasb3058bd2016-07-01 08:22:01 -070030#define STRINGIFY(x) #x
31
32// include the built-in shader symbols as static strings
33
ethannicholas5961bc92016-10-12 06:39:56 -070034static const char* SKSL_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070035#include "sksl.include"
36;
37
ethannicholas5961bc92016-10-12 06:39:56 -070038static const char* SKSL_VERT_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070039#include "sksl_vert.include"
40;
41
ethannicholas5961bc92016-10-12 06:39:56 -070042static const char* SKSL_FRAG_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070043#include "sksl_frag.include"
44;
45
Ethan Nicholas52cad152017-02-16 16:37:32 -050046static const char* SKSL_GEOM_INCLUDE =
47#include "sksl_geom.include"
48;
49
ethannicholasb3058bd2016-07-01 08:22:01 -070050namespace SkSL {
51
Mike Klein6ad99092016-10-26 10:35:22 -040052Compiler::Compiler()
ethannicholasb3058bd2016-07-01 08:22:01 -070053: fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -040054 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
55 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
ethannicholasd598f792016-07-25 10:08:54 -070056 fIRGenerator = new IRGenerator(&fContext, symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070057 fTypes = types;
ethannicholasd598f792016-07-25 10:08:54 -070058 #define ADD_TYPE(t) types->addWithoutOwnership(fContext.f ## t ## _Type->fName, \
59 fContext.f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070060 ADD_TYPE(Void);
61 ADD_TYPE(Float);
62 ADD_TYPE(Vec2);
63 ADD_TYPE(Vec3);
64 ADD_TYPE(Vec4);
65 ADD_TYPE(Double);
66 ADD_TYPE(DVec2);
67 ADD_TYPE(DVec3);
68 ADD_TYPE(DVec4);
69 ADD_TYPE(Int);
70 ADD_TYPE(IVec2);
71 ADD_TYPE(IVec3);
72 ADD_TYPE(IVec4);
73 ADD_TYPE(UInt);
74 ADD_TYPE(UVec2);
75 ADD_TYPE(UVec3);
76 ADD_TYPE(UVec4);
77 ADD_TYPE(Bool);
78 ADD_TYPE(BVec2);
79 ADD_TYPE(BVec3);
80 ADD_TYPE(BVec4);
81 ADD_TYPE(Mat2x2);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040082 types->addWithoutOwnership(String("mat2x2"), fContext.fMat2x2_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070083 ADD_TYPE(Mat2x3);
84 ADD_TYPE(Mat2x4);
85 ADD_TYPE(Mat3x2);
86 ADD_TYPE(Mat3x3);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040087 types->addWithoutOwnership(String("mat3x3"), fContext.fMat3x3_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070088 ADD_TYPE(Mat3x4);
89 ADD_TYPE(Mat4x2);
90 ADD_TYPE(Mat4x3);
91 ADD_TYPE(Mat4x4);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040092 types->addWithoutOwnership(String("mat4x4"), fContext.fMat4x4_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070093 ADD_TYPE(GenType);
94 ADD_TYPE(GenDType);
95 ADD_TYPE(GenIType);
96 ADD_TYPE(GenUType);
97 ADD_TYPE(GenBType);
98 ADD_TYPE(Mat);
99 ADD_TYPE(Vec);
100 ADD_TYPE(GVec);
101 ADD_TYPE(GVec2);
102 ADD_TYPE(GVec3);
103 ADD_TYPE(GVec4);
104 ADD_TYPE(DVec);
105 ADD_TYPE(IVec);
106 ADD_TYPE(UVec);
107 ADD_TYPE(BVec);
108
109 ADD_TYPE(Sampler1D);
110 ADD_TYPE(Sampler2D);
111 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700112 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700113 ADD_TYPE(SamplerCube);
114 ADD_TYPE(Sampler2DRect);
115 ADD_TYPE(Sampler1DArray);
116 ADD_TYPE(Sampler2DArray);
117 ADD_TYPE(SamplerCubeArray);
118 ADD_TYPE(SamplerBuffer);
119 ADD_TYPE(Sampler2DMS);
120 ADD_TYPE(Sampler2DMSArray);
121
Brian Salomonbf7b6202016-11-11 16:08:03 -0500122 ADD_TYPE(ISampler2D);
123
Brian Salomon2a51de82016-11-16 12:06:01 -0500124 ADD_TYPE(Image2D);
125 ADD_TYPE(IImage2D);
126
Greg Daniel64773e62016-11-22 09:44:03 -0500127 ADD_TYPE(SubpassInput);
128 ADD_TYPE(SubpassInputMS);
129
ethannicholasb3058bd2016-07-01 08:22:01 -0700130 ADD_TYPE(GSampler1D);
131 ADD_TYPE(GSampler2D);
132 ADD_TYPE(GSampler3D);
133 ADD_TYPE(GSamplerCube);
134 ADD_TYPE(GSampler2DRect);
135 ADD_TYPE(GSampler1DArray);
136 ADD_TYPE(GSampler2DArray);
137 ADD_TYPE(GSamplerCubeArray);
138 ADD_TYPE(GSamplerBuffer);
139 ADD_TYPE(GSampler2DMS);
140 ADD_TYPE(GSampler2DMSArray);
141
142 ADD_TYPE(Sampler1DShadow);
143 ADD_TYPE(Sampler2DShadow);
144 ADD_TYPE(SamplerCubeShadow);
145 ADD_TYPE(Sampler2DRectShadow);
146 ADD_TYPE(Sampler1DArrayShadow);
147 ADD_TYPE(Sampler2DArrayShadow);
148 ADD_TYPE(SamplerCubeArrayShadow);
149 ADD_TYPE(GSampler2DArrayShadow);
150 ADD_TYPE(GSamplerCubeArrayShadow);
151
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400152 String skCapsName("sk_Caps");
153 Variable* skCaps = new Variable(Position(), Modifiers(), skCapsName,
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500154 *fContext.fSkCaps_Type, Variable::kGlobal_Storage);
155 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
156
ethannicholas5961bc92016-10-12 06:39:56 -0700157 Modifiers::Flag ignored1;
158 std::vector<std::unique_ptr<ProgramElement>> ignored2;
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400159 this->internalConvertProgram(String(SKSL_INCLUDE), &ignored1, &ignored2);
ethannicholasddb37d62016-10-20 09:54:00 -0700160 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
ethannicholasb3058bd2016-07-01 08:22:01 -0700161 ASSERT(!fErrorCount);
162}
163
164Compiler::~Compiler() {
165 delete fIRGenerator;
166}
167
ethannicholas22f939e2016-10-13 13:25:34 -0700168// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500169void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
170 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700171 switch (lvalue->fKind) {
172 case Expression::kVariableReference_Kind: {
173 const Variable& var = ((VariableReference*) lvalue)->fVariable;
174 if (var.fStorage == Variable::kLocal_Storage) {
175 (*definitions)[&var] = expr;
176 }
177 break;
178 }
179 case Expression::kSwizzle_Kind:
180 // We consider the variable written to as long as at least some of its components have
181 // been written to. This will lead to some false negatives (we won't catch it if you
182 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400183 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
184 // 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 -0700185 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400186 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500187 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700188 definitions);
189 break;
190 case Expression::kIndex_Kind:
191 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400192 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500193 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700194 definitions);
195 break;
196 case Expression::kFieldAccess_Kind:
197 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400198 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500199 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700200 definitions);
201 break;
202 default:
203 // not an lvalue, can't happen
204 ASSERT(false);
205 }
206}
207
208// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400209void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500210 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700211 switch (node.fKind) {
212 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400213 ASSERT(node.expression());
214 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500215 switch (expr->fKind) {
216 case Expression::kBinary_Kind: {
217 BinaryExpression* b = (BinaryExpression*) expr;
218 if (b->fOperator == Token::EQ) {
219 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
220 } else if (Token::IsAssignment(b->fOperator)) {
221 this->addDefinition(
222 b->fLeft.get(),
223 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
224 definitions);
225
226 }
227 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700228 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500229 case Expression::kPrefix_Kind: {
230 const PrefixExpression* p = (PrefixExpression*) expr;
231 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
232 this->addDefinition(
233 p->fOperand.get(),
234 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
235 definitions);
236 }
237 break;
238 }
239 case Expression::kPostfix_Kind: {
240 const PostfixExpression* p = (PostfixExpression*) expr;
241 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
242 this->addDefinition(
243 p->fOperand.get(),
244 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
245 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500246 }
247 break;
248 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400249 case Expression::kVariableReference_Kind: {
250 const VariableReference* v = (VariableReference*) expr;
251 if (v->fRefKind != VariableReference::kRead_RefKind) {
252 this->addDefinition(
253 v,
254 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
255 definitions);
256 }
257 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500258 default:
259 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700260 }
261 break;
262 }
263 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400264 const Statement* stmt = (Statement*) node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700265 if (stmt->fKind == Statement::kVarDeclarations_Kind) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500266 VarDeclarationsStatement* vd = (VarDeclarationsStatement*) stmt;
Ethan Nicholascb670962017-04-20 19:31:52 -0400267 for (const auto& decl : vd->fDeclaration->fVars) {
268 if (decl->fValue) {
269 (*definitions)[decl->fVar] = &decl->fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700270 }
271 }
272 }
273 break;
274 }
275 }
276}
277
278void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
279 BasicBlock& block = cfg->fBlocks[blockId];
280
281 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500282 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700283 for (const BasicBlock::Node& n : block.fNodes) {
284 this->addDefinitions(n, &after);
285 }
286
287 // propagate definitions to exits
288 for (BlockId exitId : block.fExits) {
289 BasicBlock& exit = cfg->fBlocks[exitId];
290 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500291 std::unique_ptr<Expression>* e1 = pair.second;
292 auto found = exit.fBefore.find(pair.first);
293 if (found == exit.fBefore.end()) {
294 // exit has no definition for it, just copy it
295 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700296 exit.fBefore[pair.first] = e1;
297 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500298 // exit has a (possibly different) value already defined
299 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700300 if (e1 != e2) {
301 // definition has changed, merge and add exit block to worklist
302 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500303 if (e1 && e2) {
304 exit.fBefore[pair.first] =
Ethan Nicholas86a43402017-01-19 13:32:00 -0500305 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500306 } else {
307 exit.fBefore[pair.first] = nullptr;
308 }
ethannicholas22f939e2016-10-13 13:25:34 -0700309 }
310 }
311 }
312 }
313}
314
315// returns a map which maps all local variables in the function to null, indicating that their value
316// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500317static DefinitionMap compute_start_state(const CFG& cfg) {
318 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400319 for (const auto& block : cfg.fBlocks) {
320 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700321 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400322 ASSERT(node.statement());
323 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700324 if (s->fKind == Statement::kVarDeclarations_Kind) {
325 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholascb670962017-04-20 19:31:52 -0400326 for (const auto& decl : vd->fDeclaration->fVars) {
327 result[decl->fVar] = nullptr;
Mike Klein6ad99092016-10-26 10:35:22 -0400328 }
ethannicholas22f939e2016-10-13 13:25:34 -0700329 }
330 }
331 }
332 }
333 return result;
334}
335
Ethan Nicholascb670962017-04-20 19:31:52 -0400336/**
337 * Returns true if assigning to this lvalue has no effect.
338 */
339static bool is_dead(const Expression& lvalue) {
340 switch (lvalue.fKind) {
341 case Expression::kVariableReference_Kind:
342 return ((VariableReference&) lvalue).fVariable.dead();
343 case Expression::kSwizzle_Kind:
344 return is_dead(*((Swizzle&) lvalue).fBase);
345 case Expression::kFieldAccess_Kind:
346 return is_dead(*((FieldAccess&) lvalue).fBase);
347 case Expression::kIndex_Kind: {
348 const IndexExpression& idx = (IndexExpression&) lvalue;
349 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
350 }
351 default:
352 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
353 }
354}
ethannicholas22f939e2016-10-13 13:25:34 -0700355
Ethan Nicholascb670962017-04-20 19:31:52 -0400356/**
357 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
358 * to a dead target and lack of side effects on the left hand side.
359 */
360static bool dead_assignment(const BinaryExpression& b) {
361 if (!Token::IsAssignment(b.fOperator)) {
362 return false;
363 }
364 return is_dead(*b.fLeft);
365}
366
367void Compiler::computeDataFlow(CFG* cfg) {
368 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700369 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400370 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700371 workList.insert(i);
372 }
373 while (workList.size()) {
374 BlockId next = *workList.begin();
375 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400376 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700377 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400378}
379
380/**
381 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
382 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
383 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
384 * need to be regenerated).
385 */
386bool try_replace_expression(BasicBlock* b,
387 std::vector<BasicBlock::Node>::iterator* iter,
388 std::unique_ptr<Expression>* newExpression) {
389 std::unique_ptr<Expression>* target = (*iter)->expression();
390 if (!b->tryRemoveExpression(iter)) {
391 *target = std::move(*newExpression);
392 return false;
393 }
394 *target = std::move(*newExpression);
395 return b->tryInsertExpression(iter, target);
396}
397
398/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400399 * Returns true if the expression is a constant numeric literal with the specified value, or a
400 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400401 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400402bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400403 switch (expr.fKind) {
404 case Expression::kIntLiteral_Kind:
405 return ((IntLiteral&) expr).fValue == value;
406 case Expression::kFloatLiteral_Kind:
407 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400408 case Expression::kConstructor_Kind: {
409 Constructor& c = (Constructor&) expr;
410 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
411 for (int i = 0; i < c.fType.columns(); ++i) {
412 if (!is_constant(c.getVecComponent(i), value)) {
413 return false;
414 }
415 }
416 return true;
417 }
418 return false;
419 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400420 default:
421 return false;
422 }
423}
424
425/**
426 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
427 * and CFG structures).
428 */
429void delete_left(BasicBlock* b,
430 std::vector<BasicBlock::Node>::iterator* iter,
431 bool* outUpdated,
432 bool* outNeedsRescan) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400433 ASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400434 *outUpdated = true;
435 if (!try_replace_expression(b, iter, &((BinaryExpression&) **(*iter)->expression()).fRight)) {
436 *outNeedsRescan = true;
437 }
438}
439
440/**
441 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
442 * CFG structures).
443 */
444void delete_right(BasicBlock* b,
445 std::vector<BasicBlock::Node>::iterator* iter,
446 bool* outUpdated,
447 bool* outNeedsRescan) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400448 ASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400449 *outUpdated = true;
450 if (!try_replace_expression(b, iter, &((BinaryExpression&) **(*iter)->expression()).fLeft)) {
451 *outNeedsRescan = true;
452 }
453}
454
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400455/**
456 * Constructs the specified type using a single argument.
457 */
458static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
459 std::vector<std::unique_ptr<Expression>> args;
460 args.push_back(std::move(v));
461 auto result = std::unique_ptr<Expression>(new Constructor(Position(), type, std::move(args)));
462 return result;
463}
464
465/**
466 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
467 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
468 */
469static void vectorize(BasicBlock* b,
470 std::vector<BasicBlock::Node>::iterator* iter,
471 const Type& type,
472 std::unique_ptr<Expression>* otherExpression,
473 bool* outUpdated,
474 bool* outNeedsRescan) {
475 ASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
476 ASSERT(type.kind() == Type::kVector_Kind);
477 ASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
478 *outUpdated = true;
479 std::unique_ptr<Expression>* target = (*iter)->expression();
480 if (!b->tryRemoveExpression(iter)) {
481 *target = construct(type, std::move(*otherExpression));
482 *outNeedsRescan = true;
483 } else {
484 *target = construct(type, std::move(*otherExpression));
485 if (!b->tryInsertExpression(iter, target)) {
486 *outNeedsRescan = true;
487 }
488 }
489}
490
491/**
492 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
493 * left to yield vec<n>(x).
494 */
495static void vectorize_left(BasicBlock* b,
496 std::vector<BasicBlock::Node>::iterator* iter,
497 bool* outUpdated,
498 bool* outNeedsRescan) {
499 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
500 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
501}
502
503/**
504 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
505 * right to yield vec<n>(y).
506 */
507static void vectorize_right(BasicBlock* b,
508 std::vector<BasicBlock::Node>::iterator* iter,
509 bool* outUpdated,
510 bool* outNeedsRescan) {
511 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
512 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
513}
514
515// Mark that an expression which we were writing to is no longer being written to
516void clear_write(const Expression& expr) {
517 switch (expr.fKind) {
518 case Expression::kVariableReference_Kind: {
519 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
520 break;
521 }
522 case Expression::kFieldAccess_Kind:
523 clear_write(*((FieldAccess&) expr).fBase);
524 break;
525 case Expression::kSwizzle_Kind:
526 clear_write(*((Swizzle&) expr).fBase);
527 break;
528 case Expression::kIndex_Kind:
529 clear_write(*((IndexExpression&) expr).fBase);
530 break;
531 default:
532 ABORT("shouldn't be writing to this kind of expression\n");
533 break;
534 }
535}
536
Ethan Nicholascb670962017-04-20 19:31:52 -0400537void Compiler::simplifyExpression(DefinitionMap& definitions,
538 BasicBlock& b,
539 std::vector<BasicBlock::Node>::iterator* iter,
540 std::unordered_set<const Variable*>* undefinedVariables,
541 bool* outUpdated,
542 bool* outNeedsRescan) {
543 Expression* expr = (*iter)->expression()->get();
544 ASSERT(expr);
545 if ((*iter)->fConstantPropagation) {
546 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
547 if (optimized) {
548 if (!try_replace_expression(&b, iter, &optimized)) {
549 *outNeedsRescan = true;
550 }
551 ASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
552 expr = (*iter)->expression()->get();
553 *outUpdated = true;
554 }
555 }
556 switch (expr->fKind) {
557 case Expression::kVariableReference_Kind: {
558 const Variable& var = ((VariableReference*) expr)->fVariable;
559 if (var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
560 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
561 (*undefinedVariables).insert(&var);
562 this->error(expr->fPosition,
563 "'" + var.fName + "' has not been assigned");
564 }
565 break;
566 }
567 case Expression::kTernary_Kind: {
568 TernaryExpression* t = (TernaryExpression*) expr;
569 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
570 // ternary has a constant test, replace it with either the true or
571 // false branch
572 if (((BoolLiteral&) *t->fTest).fValue) {
573 (*iter)->setExpression(std::move(t->fIfTrue));
574 } else {
575 (*iter)->setExpression(std::move(t->fIfFalse));
576 }
577 *outUpdated = true;
578 *outNeedsRescan = true;
579 }
580 break;
581 }
582 case Expression::kBinary_Kind: {
583 // collapse useless expressions like x * 1 or x + 0
584 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400585 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
586 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
587 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
588 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
589 break;
590 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400591 switch (bin->fOperator) {
592 case Token::STAR:
593 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400594 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
595 bin->fRight->fType.kind() == Type::kScalar_Kind) {
596 // vec4(1) * x -> vec4(x)
597 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
598 } else {
599 // 1 * x -> x
600 // 1 * vec4(x) -> vec4(x)
601 // vec4(1) * vec4(x) -> vec4(x)
602 delete_left(&b, iter, outUpdated, outNeedsRescan);
603 }
604 }
605 else if (is_constant(*bin->fLeft, 0)) {
606 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
607 bin->fRight->fType.kind() == Type::kVector_Kind) {
608 // 0 * vec4(x) -> vec4(0)
609 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
610 } else {
611 // 0 * x -> 0
612 // vec4(0) * x -> vec4(0)
613 // vec4(0) * vec4(x) -> vec4(0)
614 delete_right(&b, iter, outUpdated, outNeedsRescan);
615 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400616 }
617 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400618 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
619 bin->fRight->fType.kind() == Type::kVector_Kind) {
620 // x * vec4(1) -> vec4(x)
621 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
622 } else {
623 // x * 1 -> x
624 // vec4(x) * 1 -> vec4(x)
625 // vec4(x) * vec4(1) -> vec4(x)
626 delete_right(&b, iter, outUpdated, outNeedsRescan);
627 }
628 }
629 else if (is_constant(*bin->fRight, 0)) {
630 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
631 bin->fRight->fType.kind() == Type::kScalar_Kind) {
632 // vec4(x) * 0 -> vec4(0)
633 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
634 } else {
635 // x * 0 -> 0
636 // x * vec4(0) -> vec4(0)
637 // vec4(x) * vec4(0) -> vec4(0)
638 delete_left(&b, iter, outUpdated, outNeedsRescan);
639 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400640 }
641 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400642 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400643 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400644 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
645 bin->fRight->fType.kind() == Type::kScalar_Kind) {
646 // vec4(0) + x -> vec4(x)
647 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
648 } else {
649 // 0 + x -> x
650 // 0 + vec4(x) -> vec4(x)
651 // vec4(0) + vec4(x) -> vec4(x)
652 delete_left(&b, iter, outUpdated, outNeedsRescan);
653 }
654 } else if (is_constant(*bin->fRight, 0)) {
655 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
656 bin->fRight->fType.kind() == Type::kVector_Kind) {
657 // x + vec4(0) -> vec4(x)
658 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
659 } else {
660 // x + 0 -> x
661 // vec4(x) + 0 -> vec4(x)
662 // vec4(x) + vec4(0) -> vec4(x)
663 delete_right(&b, iter, outUpdated, outNeedsRescan);
664 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400665 }
666 break;
667 case Token::MINUS:
668 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400669 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
670 bin->fRight->fType.kind() == Type::kVector_Kind) {
671 // x - vec4(0) -> vec4(x)
672 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
673 } else {
674 // x - 0 -> x
675 // vec4(x) - 0 -> vec4(x)
676 // vec4(x) - vec4(0) -> vec4(x)
677 delete_right(&b, iter, outUpdated, outNeedsRescan);
678 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400679 }
680 break;
681 case Token::SLASH:
682 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400683 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
684 bin->fRight->fType.kind() == Type::kVector_Kind) {
685 // x / vec4(1) -> vec4(x)
686 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
687 } else {
688 // x / 1 -> x
689 // vec4(x) / 1 -> vec4(x)
690 // vec4(x) / vec4(1) -> vec4(x)
691 delete_right(&b, iter, outUpdated, outNeedsRescan);
692 }
693 } else if (is_constant(*bin->fLeft, 0)) {
694 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
695 bin->fRight->fType.kind() == Type::kVector_Kind) {
696 // 0 / vec4(x) -> vec4(0)
697 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
698 } else {
699 // 0 / x -> 0
700 // vec4(0) / x -> vec4(0)
701 // vec4(0) / vec4(x) -> vec4(0)
702 delete_right(&b, iter, outUpdated, outNeedsRescan);
703 }
704 }
705 break;
706 case Token::PLUSEQ:
707 if (is_constant(*bin->fRight, 0)) {
708 clear_write(*bin->fLeft);
709 delete_right(&b, iter, outUpdated, outNeedsRescan);
710 }
711 break;
712 case Token::MINUSEQ:
713 if (is_constant(*bin->fRight, 0)) {
714 clear_write(*bin->fLeft);
715 delete_right(&b, iter, outUpdated, outNeedsRescan);
716 }
717 break;
718 case Token::STAREQ:
719 if (is_constant(*bin->fRight, 1)) {
720 clear_write(*bin->fLeft);
721 delete_right(&b, iter, outUpdated, outNeedsRescan);
722 }
723 break;
724 case Token::SLASHEQ:
725 if (is_constant(*bin->fRight, 1)) {
726 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400727 delete_right(&b, iter, outUpdated, outNeedsRescan);
728 }
729 break;
730 default:
731 break;
732 }
733 }
734 default:
735 break;
736 }
737}
738
739void Compiler::simplifyStatement(DefinitionMap& definitions,
740 BasicBlock& b,
741 std::vector<BasicBlock::Node>::iterator* iter,
742 std::unordered_set<const Variable*>* undefinedVariables,
743 bool* outUpdated,
744 bool* outNeedsRescan) {
745 Statement* stmt = (*iter)->statement()->get();
746 switch (stmt->fKind) {
747 case Statement::kVarDeclarations_Kind: {
748 VarDeclarations& vd = *((VarDeclarationsStatement&) *stmt).fDeclaration;
749 for (auto varIter = vd.fVars.begin(); varIter != vd.fVars.end(); ) {
750 const auto& varDecl = **varIter;
751 if (varDecl.fVar->dead() &&
752 (!varDecl.fValue ||
753 !varDecl.fValue->hasSideEffects())) {
754 if (varDecl.fValue) {
755 ASSERT((*iter)->statement()->get() == stmt);
756 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
757 *outNeedsRescan = true;
758 }
759 }
760 varIter = vd.fVars.erase(varIter);
761 *outUpdated = true;
762 } else {
763 ++varIter;
764 }
765 }
766 if (vd.fVars.size() == 0) {
767 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
768 }
769 break;
770 }
771 case Statement::kIf_Kind: {
772 IfStatement& i = (IfStatement&) *stmt;
773 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
774 // else block doesn't do anything, remove it
775 i.fIfFalse.reset();
776 *outUpdated = true;
777 *outNeedsRescan = true;
778 }
779 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
780 // if block doesn't do anything, no else block
781 if (i.fTest->hasSideEffects()) {
782 // test has side effects, keep it
783 (*iter)->setStatement(std::unique_ptr<Statement>(
784 new ExpressionStatement(std::move(i.fTest))));
785 } else {
786 // no if, no else, no test side effects, kill the whole if
787 // statement
788 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
789 }
790 *outUpdated = true;
791 *outNeedsRescan = true;
792 }
793 break;
794 }
795 case Statement::kExpression_Kind: {
796 ExpressionStatement& e = (ExpressionStatement&) *stmt;
797 ASSERT((*iter)->statement()->get() == &e);
798 if (e.fExpression->fKind == Expression::kBinary_Kind) {
799 BinaryExpression& bin = (BinaryExpression&) *e.fExpression;
800 if (dead_assignment(bin)) {
801 if (!b.tryRemoveExpressionBefore(iter, &bin)) {
802 *outNeedsRescan = true;
803 }
804 if (bin.fRight->hasSideEffects()) {
805 // still have to evaluate the right due to side effects,
806 // replace the binary expression with just the right side
807 e.fExpression = std::move(bin.fRight);
808 if (!b.tryInsertExpression(iter, &e.fExpression)) {
809 *outNeedsRescan = true;
810 }
811 } else {
812 // no side effects, kill the whole statement
813 ASSERT((*iter)->statement()->get() == stmt);
814 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
815 }
816 *outUpdated = true;
817 break;
818 }
819 }
820 if (!e.fExpression->hasSideEffects()) {
821 // Expression statement with no side effects, kill it
822 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
823 *outNeedsRescan = true;
824 }
825 ASSERT((*iter)->statement()->get() == stmt);
826 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
827 *outUpdated = true;
828 }
829 break;
830 }
831 default:
832 break;
833 }
834}
835
836void Compiler::scanCFG(FunctionDefinition& f) {
837 CFG cfg = CFGGenerator().getCFG(f);
838 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700839
840 // check for unreachable code
841 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -0400842 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -0700843 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500844 Position p;
845 switch (cfg.fBlocks[i].fNodes[0].fKind) {
846 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholascb670962017-04-20 19:31:52 -0400847 p = (*cfg.fBlocks[i].fNodes[0].statement())->fPosition;
Ethan Nicholas86a43402017-01-19 13:32:00 -0500848 break;
849 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholascb670962017-04-20 19:31:52 -0400850 p = (*cfg.fBlocks[i].fNodes[0].expression())->fPosition;
Ethan Nicholas86a43402017-01-19 13:32:00 -0500851 break;
852 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400853 this->error(p, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -0700854 }
855 }
856 if (fErrorCount) {
857 return;
858 }
859
Ethan Nicholascb670962017-04-20 19:31:52 -0400860 // check for dead code & undefined variables, perform constant propagation
861 std::unordered_set<const Variable*> undefinedVariables;
862 bool updated;
863 bool needsRescan = false;
864 do {
865 if (needsRescan) {
866 cfg = CFGGenerator().getCFG(f);
867 this->computeDataFlow(&cfg);
868 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -0500869 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400870
871 updated = false;
872 for (BasicBlock& b : cfg.fBlocks) {
873 DefinitionMap definitions = b.fBefore;
874
875 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
876 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
877 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
878 &needsRescan);
879 } else {
880 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
881 &needsRescan);
882 }
883 this->addDefinitions(*iter, &definitions);
884 }
885 }
886 } while (updated);
887 ASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -0700888
889 // check for missing return
890 if (f.fDeclaration.fReturnType != *fContext.fVoid_Type) {
891 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400892 this->error(f.fPosition, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -0700893 }
894 }
895}
896
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400897void Compiler::internalConvertProgram(String text,
ethannicholas5961bc92016-10-12 06:39:56 -0700898 Modifiers::Flag* defaultPrecision,
ethannicholasb3058bd2016-07-01 08:22:01 -0700899 std::vector<std::unique_ptr<ProgramElement>>* result) {
900 Parser parser(text, *fTypes, *this);
901 std::vector<std::unique_ptr<ASTDeclaration>> parsed = parser.file();
902 if (fErrorCount) {
903 return;
904 }
ethannicholas5961bc92016-10-12 06:39:56 -0700905 *defaultPrecision = Modifiers::kHighp_Flag;
ethannicholasb3058bd2016-07-01 08:22:01 -0700906 for (size_t i = 0; i < parsed.size(); i++) {
907 ASTDeclaration& decl = *parsed[i];
908 switch (decl.fKind) {
909 case ASTDeclaration::kVar_Kind: {
ethannicholas14fe8cc2016-09-07 13:37:16 -0700910 std::unique_ptr<VarDeclarations> s = fIRGenerator->convertVarDeclarations(
Mike Klein6ad99092016-10-26 10:35:22 -0400911 (ASTVarDeclarations&) decl,
ethannicholasb3058bd2016-07-01 08:22:01 -0700912 Variable::kGlobal_Storage);
913 if (s) {
914 result->push_back(std::move(s));
915 }
916 break;
917 }
918 case ASTDeclaration::kFunction_Kind: {
919 std::unique_ptr<FunctionDefinition> f = fIRGenerator->convertFunction(
920 (ASTFunction&) decl);
ethannicholas22f939e2016-10-13 13:25:34 -0700921 if (!fErrorCount && f) {
922 this->scanCFG(*f);
ethannicholasb3058bd2016-07-01 08:22:01 -0700923 result->push_back(std::move(f));
924 }
925 break;
926 }
ethannicholas5961bc92016-10-12 06:39:56 -0700927 case ASTDeclaration::kModifiers_Kind: {
928 std::unique_ptr<ModifiersDeclaration> f = fIRGenerator->convertModifiersDeclaration(
929 (ASTModifiersDeclaration&) decl);
930 if (f) {
931 result->push_back(std::move(f));
932 }
933 break;
934 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700935 case ASTDeclaration::kInterfaceBlock_Kind: {
936 std::unique_ptr<InterfaceBlock> i = fIRGenerator->convertInterfaceBlock(
937 (ASTInterfaceBlock&) decl);
938 if (i) {
939 result->push_back(std::move(i));
940 }
941 break;
942 }
943 case ASTDeclaration::kExtension_Kind: {
944 std::unique_ptr<Extension> e = fIRGenerator->convertExtension((ASTExtension&) decl);
945 if (e) {
946 result->push_back(std::move(e));
947 }
948 break;
949 }
ethannicholas5961bc92016-10-12 06:39:56 -0700950 case ASTDeclaration::kPrecision_Kind: {
951 *defaultPrecision = ((ASTPrecision&) decl).fPrecision;
952 break;
953 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700954 default:
955 ABORT("unsupported declaration: %s\n", decl.description().c_str());
956 }
957 }
958}
959
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400960std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500961 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700962 fErrorText = "";
963 fErrorCount = 0;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500964 fIRGenerator->start(&settings);
ethannicholasd598f792016-07-25 10:08:54 -0700965 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholas5961bc92016-10-12 06:39:56 -0700966 Modifiers::Flag ignored;
ethannicholasb3058bd2016-07-01 08:22:01 -0700967 switch (kind) {
968 case Program::kVertex_Kind:
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400969 this->internalConvertProgram(String(SKSL_VERT_INCLUDE), &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -0700970 break;
971 case Program::kFragment_Kind:
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400972 this->internalConvertProgram(String(SKSL_FRAG_INCLUDE), &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -0700973 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -0500974 case Program::kGeometry_Kind:
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400975 this->internalConvertProgram(String(SKSL_GEOM_INCLUDE), &ignored, &elements);
Ethan Nicholas52cad152017-02-16 16:37:32 -0500976 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700977 }
ethannicholasddb37d62016-10-20 09:54:00 -0700978 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
ethannicholas5961bc92016-10-12 06:39:56 -0700979 Modifiers::Flag defaultPrecision;
980 this->internalConvertProgram(text, &defaultPrecision, &elements);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500981 auto result = std::unique_ptr<Program>(new Program(kind, settings, defaultPrecision, &fContext,
982 std::move(elements),
983 fIRGenerator->fSymbolTable,
984 fIRGenerator->fInputs));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500985 fIRGenerator->finish();
ethannicholasb3058bd2016-07-01 08:22:01 -0700986 this->writeErrorCount();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500987 if (fErrorCount) {
988 return nullptr;
989 }
990 return result;
991}
992
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400993bool Compiler::toSPIRV(const Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400994#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400995 StringStream buffer;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400996 SPIRVCodeGenerator cg(&fContext, &program, this, &buffer);
997 bool result = cg.generateCode();
998 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400999 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001000 ASSERT(0 == buffer.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001001 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1002 SkDebugf("SPIR-V validation error: %s\n", m);
1003 };
1004 tools.SetMessageConsumer(dumpmsg);
1005 // Verify that the SPIR-V we produced is valid. If this assert fails, check the logs prior
1006 // to the failure to see the validation errors.
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001007 ASSERT_RESULT(tools.Validate((const uint32_t*) buffer.data(), buffer.size() / 4));
1008 out.write(buffer.data(), buffer.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001009 }
1010#else
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001011 SPIRVCodeGenerator cg(&fContext, &program, this, &out);
1012 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001013#endif
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001014 this->writeErrorCount();
Ethan Nicholasce33f102016-12-09 17:22:59 -05001015 return result;
1016}
1017
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001018bool Compiler::toSPIRV(const Program& program, String* out) {
1019 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001020 bool result = this->toSPIRV(program, buffer);
1021 if (result) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001022 *out = String(buffer.data(), buffer.size());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001023 }
1024 return result;
1025}
1026
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001027bool Compiler::toGLSL(const Program& program, OutputStream& out) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001028 GLSLCodeGenerator cg(&fContext, &program, this, &out);
1029 bool result = cg.generateCode();
1030 this->writeErrorCount();
1031 return result;
1032}
1033
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001034bool Compiler::toGLSL(const Program& program, String* out) {
1035 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001036 bool result = this->toGLSL(program, buffer);
1037 if (result) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001038 *out = String(buffer.data(), buffer.size());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001039 }
1040 return result;
1041}
1042
1043
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001044void Compiler::error(Position position, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001045 fErrorCount++;
1046 fErrorText += "error: " + position.description() + ": " + msg.c_str() + "\n";
1047}
1048
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001049String Compiler::errorText() {
1050 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001051 return result;
1052}
1053
1054void Compiler::writeErrorCount() {
1055 if (fErrorCount) {
1056 fErrorText += to_string(fErrorCount) + " error";
1057 if (fErrorCount > 1) {
1058 fErrorText += "s";
1059 }
1060 fErrorText += "\n";
1061 }
1062}
1063
ethannicholasb3058bd2016-07-01 08:22:01 -07001064} // namespace