1 /*
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 */
7
8 #include "SkSLIRGenerator.h"
9
10 #include "limits.h"
11 #include <unordered_set>
12
13 #include "SkSLCompiler.h"
14 #include "SkSLParser.h"
15 #include "ast/SkSLASTBoolLiteral.h"
16 #include "ast/SkSLASTFieldSuffix.h"
17 #include "ast/SkSLASTFloatLiteral.h"
18 #include "ast/SkSLASTIndexSuffix.h"
19 #include "ast/SkSLASTIntLiteral.h"
20 #include "ir/SkSLBinaryExpression.h"
21 #include "ir/SkSLBoolLiteral.h"
22 #include "ir/SkSLBreakStatement.h"
23 #include "ir/SkSLConstructor.h"
24 #include "ir/SkSLContinueStatement.h"
25 #include "ir/SkSLDiscardStatement.h"
26 #include "ir/SkSLDoStatement.h"
27 #include "ir/SkSLEnum.h"
28 #include "ir/SkSLExpressionStatement.h"
29 #include "ir/SkSLField.h"
30 #include "ir/SkSLFieldAccess.h"
31 #include "ir/SkSLFloatLiteral.h"
32 #include "ir/SkSLForStatement.h"
33 #include "ir/SkSLFunctionCall.h"
34 #include "ir/SkSLFunctionDeclaration.h"
35 #include "ir/SkSLFunctionDefinition.h"
36 #include "ir/SkSLFunctionReference.h"
37 #include "ir/SkSLIfStatement.h"
38 #include "ir/SkSLIndexExpression.h"
39 #include "ir/SkSLInterfaceBlock.h"
40 #include "ir/SkSLIntLiteral.h"
41 #include "ir/SkSLLayout.h"
42 #include "ir/SkSLPostfixExpression.h"
43 #include "ir/SkSLPrefixExpression.h"
44 #include "ir/SkSLReturnStatement.h"
45 #include "ir/SkSLSetting.h"
46 #include "ir/SkSLSwitchCase.h"
47 #include "ir/SkSLSwitchStatement.h"
48 #include "ir/SkSLSwizzle.h"
49 #include "ir/SkSLTernaryExpression.h"
50 #include "ir/SkSLUnresolvedFunction.h"
51 #include "ir/SkSLVariable.h"
52 #include "ir/SkSLVarDeclarations.h"
53 #include "ir/SkSLVarDeclarationsStatement.h"
54 #include "ir/SkSLVariableReference.h"
55 #include "ir/SkSLWhileStatement.h"
56
57 namespace SkSL {
58
59 class AutoSymbolTable {
60 public:
AutoSymbolTable(IRGenerator * ir)61 AutoSymbolTable(IRGenerator* ir)
62 : fIR(ir)
63 , fPrevious(fIR->fSymbolTable) {
64 fIR->pushSymbolTable();
65 }
66
~AutoSymbolTable()67 ~AutoSymbolTable() {
68 fIR->popSymbolTable();
69 ASSERT(fPrevious == fIR->fSymbolTable);
70 }
71
72 IRGenerator* fIR;
73 std::shared_ptr<SymbolTable> fPrevious;
74 };
75
76 class AutoLoopLevel {
77 public:
AutoLoopLevel(IRGenerator * ir)78 AutoLoopLevel(IRGenerator* ir)
79 : fIR(ir) {
80 fIR->fLoopLevel++;
81 }
82
~AutoLoopLevel()83 ~AutoLoopLevel() {
84 fIR->fLoopLevel--;
85 }
86
87 IRGenerator* fIR;
88 };
89
90 class AutoSwitchLevel {
91 public:
AutoSwitchLevel(IRGenerator * ir)92 AutoSwitchLevel(IRGenerator* ir)
93 : fIR(ir) {
94 fIR->fSwitchLevel++;
95 }
96
~AutoSwitchLevel()97 ~AutoSwitchLevel() {
98 fIR->fSwitchLevel--;
99 }
100
101 IRGenerator* fIR;
102 };
103
IRGenerator(const Context * context,std::shared_ptr<SymbolTable> symbolTable,ErrorReporter & errorReporter)104 IRGenerator::IRGenerator(const Context* context, std::shared_ptr<SymbolTable> symbolTable,
105 ErrorReporter& errorReporter)
106 : fContext(*context)
107 , fCurrentFunction(nullptr)
108 , fRootSymbolTable(symbolTable)
109 , fSymbolTable(symbolTable)
110 , fLoopLevel(0)
111 , fSwitchLevel(0)
112 , fTmpCount(0)
113 , fErrors(errorReporter) {}
114
pushSymbolTable()115 void IRGenerator::pushSymbolTable() {
116 fSymbolTable.reset(new SymbolTable(std::move(fSymbolTable), &fErrors));
117 }
118
popSymbolTable()119 void IRGenerator::popSymbolTable() {
120 fSymbolTable = fSymbolTable->fParent;
121 }
122
fill_caps(const SKSL_CAPS_CLASS & caps,std::unordered_map<String,Program::Settings::Value> * capsMap)123 static void fill_caps(const SKSL_CAPS_CLASS& caps,
124 std::unordered_map<String, Program::Settings::Value>* capsMap) {
125 #define CAP(name) capsMap->insert(std::make_pair(String(#name), \
126 Program::Settings::Value(caps.name())));
127 CAP(fbFetchSupport);
128 CAP(fbFetchNeedsCustomOutput);
129 CAP(dropsTileOnZeroDivide);
130 CAP(flatInterpolationSupport);
131 CAP(noperspectiveInterpolationSupport);
132 CAP(externalTextureSupport);
133 CAP(texelFetchSupport);
134 CAP(imageLoadStoreSupport);
135 CAP(mustEnableAdvBlendEqs);
136 CAP(mustEnableSpecificAdvBlendEqs);
137 CAP(mustDeclareFragmentShaderOutput);
138 CAP(canUseAnyFunctionInShader);
139 CAP(floatIs32Bits);
140 CAP(integerSupport);
141 #undef CAP
142 }
143
start(const Program::Settings * settings)144 void IRGenerator::start(const Program::Settings* settings) {
145 fSettings = settings;
146 fCapsMap.clear();
147 if (settings->fCaps) {
148 fill_caps(*settings->fCaps, &fCapsMap);
149 }
150 this->pushSymbolTable();
151 fInvocations = -1;
152 fInputs.reset();
153 fSkPerVertex = nullptr;
154 fRTAdjust = nullptr;
155 fRTAdjustInterfaceBlock = nullptr;
156 }
157
finish()158 void IRGenerator::finish() {
159 this->popSymbolTable();
160 fSettings = nullptr;
161 }
162
convertExtension(const ASTExtension & extension)163 std::unique_ptr<Extension> IRGenerator::convertExtension(const ASTExtension& extension) {
164 return std::unique_ptr<Extension>(new Extension(extension.fOffset, extension.fName));
165 }
166
convertStatement(const ASTStatement & statement)167 std::unique_ptr<Statement> IRGenerator::convertStatement(const ASTStatement& statement) {
168 switch (statement.fKind) {
169 case ASTStatement::kBlock_Kind:
170 return this->convertBlock((ASTBlock&) statement);
171 case ASTStatement::kVarDeclaration_Kind:
172 return this->convertVarDeclarationStatement((ASTVarDeclarationStatement&) statement);
173 case ASTStatement::kExpression_Kind: {
174 std::unique_ptr<Statement> result =
175 this->convertExpressionStatement((ASTExpressionStatement&) statement);
176 if (fRTAdjust && Program::kGeometry_Kind == fKind) {
177 ASSERT(result->fKind == Statement::kExpression_Kind);
178 Expression& expr = *((ExpressionStatement&) *result).fExpression;
179 if (expr.fKind == Expression::kFunctionCall_Kind) {
180 FunctionCall& fc = (FunctionCall&) expr;
181 if (fc.fFunction.fBuiltin && fc.fFunction.fName == "EmitVertex") {
182 std::vector<std::unique_ptr<Statement>> statements;
183 statements.push_back(getNormalizeSkPositionCode());
184 statements.push_back(std::move(result));
185 return std::unique_ptr<Block>(new Block(statement.fOffset,
186 std::move(statements),
187 fSymbolTable));
188 }
189 }
190 }
191 return result;
192 }
193 case ASTStatement::kIf_Kind:
194 return this->convertIf((ASTIfStatement&) statement);
195 case ASTStatement::kFor_Kind:
196 return this->convertFor((ASTForStatement&) statement);
197 case ASTStatement::kWhile_Kind:
198 return this->convertWhile((ASTWhileStatement&) statement);
199 case ASTStatement::kDo_Kind:
200 return this->convertDo((ASTDoStatement&) statement);
201 case ASTStatement::kSwitch_Kind:
202 return this->convertSwitch((ASTSwitchStatement&) statement);
203 case ASTStatement::kReturn_Kind:
204 return this->convertReturn((ASTReturnStatement&) statement);
205 case ASTStatement::kBreak_Kind:
206 return this->convertBreak((ASTBreakStatement&) statement);
207 case ASTStatement::kContinue_Kind:
208 return this->convertContinue((ASTContinueStatement&) statement);
209 case ASTStatement::kDiscard_Kind:
210 return this->convertDiscard((ASTDiscardStatement&) statement);
211 default:
212 ABORT("unsupported statement type: %d\n", statement.fKind);
213 }
214 }
215
convertBlock(const ASTBlock & block)216 std::unique_ptr<Block> IRGenerator::convertBlock(const ASTBlock& block) {
217 AutoSymbolTable table(this);
218 std::vector<std::unique_ptr<Statement>> statements;
219 for (size_t i = 0; i < block.fStatements.size(); i++) {
220 std::unique_ptr<Statement> statement = this->convertStatement(*block.fStatements[i]);
221 if (!statement) {
222 return nullptr;
223 }
224 statements.push_back(std::move(statement));
225 }
226 return std::unique_ptr<Block>(new Block(block.fOffset, std::move(statements), fSymbolTable));
227 }
228
convertVarDeclarationStatement(const ASTVarDeclarationStatement & s)229 std::unique_ptr<Statement> IRGenerator::convertVarDeclarationStatement(
230 const ASTVarDeclarationStatement& s) {
231 auto decl = this->convertVarDeclarations(*s.fDeclarations, Variable::kLocal_Storage);
232 if (!decl) {
233 return nullptr;
234 }
235 return std::unique_ptr<Statement>(new VarDeclarationsStatement(std::move(decl)));
236 }
237
convertVarDeclarations(const ASTVarDeclarations & decl,Variable::Storage storage)238 std::unique_ptr<VarDeclarations> IRGenerator::convertVarDeclarations(const ASTVarDeclarations& decl,
239 Variable::Storage storage) {
240 std::vector<std::unique_ptr<VarDeclaration>> variables;
241 const Type* baseType = this->convertType(*decl.fType);
242 if (!baseType) {
243 return nullptr;
244 }
245 for (const auto& varDecl : decl.fVars) {
246 const Type* type = baseType;
247 std::vector<std::unique_ptr<Expression>> sizes;
248 for (const auto& rawSize : varDecl.fSizes) {
249 if (rawSize) {
250 auto size = this->coerce(this->convertExpression(*rawSize), *fContext.fInt_Type);
251 if (!size) {
252 return nullptr;
253 }
254 String name(type->fName);
255 int64_t count;
256 if (size->fKind == Expression::kIntLiteral_Kind) {
257 count = ((IntLiteral&) *size).fValue;
258 if (count <= 0) {
259 fErrors.error(size->fOffset, "array size must be positive");
260 }
261 name += "[" + to_string(count) + "]";
262 } else {
263 count = -1;
264 name += "[]";
265 }
266 type = new Type(name, Type::kArray_Kind, *type, (int) count);
267 fSymbolTable->takeOwnership((Type*) type);
268 sizes.push_back(std::move(size));
269 } else {
270 type = new Type(type->name() + "[]", Type::kArray_Kind, *type, -1);
271 fSymbolTable->takeOwnership((Type*) type);
272 sizes.push_back(nullptr);
273 }
274 }
275 auto var = std::unique_ptr<Variable>(new Variable(decl.fOffset, decl.fModifiers,
276 varDecl.fName, *type, storage));
277 if (var->fName == Compiler::RTADJUST_NAME) {
278 ASSERT(!fRTAdjust);
279 ASSERT(var->fType == *fContext.fFloat4_Type);
280 fRTAdjust = var.get();
281 }
282 std::unique_ptr<Expression> value;
283 if (varDecl.fValue) {
284 value = this->convertExpression(*varDecl.fValue);
285 if (!value) {
286 return nullptr;
287 }
288 value = this->coerce(std::move(value), *type);
289 if (!value) {
290 return nullptr;
291 }
292 var->fWriteCount = 1;
293 var->fInitialValue = value.get();
294 }
295 if (storage == Variable::kGlobal_Storage && varDecl.fName == "sk_FragColor" &&
296 (*fSymbolTable)[varDecl.fName]) {
297 // already defined, ignore
298 } else if (storage == Variable::kGlobal_Storage && (*fSymbolTable)[varDecl.fName] &&
299 (*fSymbolTable)[varDecl.fName]->fKind == Symbol::kVariable_Kind &&
300 ((Variable*) (*fSymbolTable)[varDecl.fName])->fModifiers.fLayout.fBuiltin >= 0) {
301 // already defined, just update the modifiers
302 Variable* old = (Variable*) (*fSymbolTable)[varDecl.fName];
303 old->fModifiers = var->fModifiers;
304 } else {
305 variables.emplace_back(new VarDeclaration(var.get(), std::move(sizes),
306 std::move(value)));
307 fSymbolTable->add(varDecl.fName, std::move(var));
308 }
309 }
310 return std::unique_ptr<VarDeclarations>(new VarDeclarations(decl.fOffset,
311 baseType,
312 std::move(variables)));
313 }
314
convertModifiersDeclaration(const ASTModifiersDeclaration & m)315 std::unique_ptr<ModifiersDeclaration> IRGenerator::convertModifiersDeclaration(
316 const ASTModifiersDeclaration& m) {
317 Modifiers modifiers = m.fModifiers;
318 if (modifiers.fLayout.fInvocations != -1) {
319 fInvocations = modifiers.fLayout.fInvocations;
320 if (fSettings->fCaps && !fSettings->fCaps->gsInvocationsSupport()) {
321 modifiers.fLayout.fInvocations = -1;
322 Variable* invocationId = (Variable*) (*fSymbolTable)["sk_InvocationID"];
323 ASSERT(invocationId);
324 invocationId->fModifiers.fLayout.fBuiltin = -1;
325 if (modifiers.fLayout.description() == "") {
326 return nullptr;
327 }
328 }
329 }
330 if (modifiers.fLayout.fMaxVertices != -1 && fInvocations > 0 && fSettings->fCaps &&
331 !fSettings->fCaps->gsInvocationsSupport()) {
332 modifiers.fLayout.fMaxVertices *= fInvocations;
333 }
334 return std::unique_ptr<ModifiersDeclaration>(new ModifiersDeclaration(modifiers));
335 }
336
convertIf(const ASTIfStatement & s)337 std::unique_ptr<Statement> IRGenerator::convertIf(const ASTIfStatement& s) {
338 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*s.fTest),
339 *fContext.fBool_Type);
340 if (!test) {
341 return nullptr;
342 }
343 std::unique_ptr<Statement> ifTrue = this->convertStatement(*s.fIfTrue);
344 if (!ifTrue) {
345 return nullptr;
346 }
347 std::unique_ptr<Statement> ifFalse;
348 if (s.fIfFalse) {
349 ifFalse = this->convertStatement(*s.fIfFalse);
350 if (!ifFalse) {
351 return nullptr;
352 }
353 }
354 if (test->fKind == Expression::kBoolLiteral_Kind) {
355 // static boolean value, fold down to a single branch
356 if (((BoolLiteral&) *test).fValue) {
357 return ifTrue;
358 } else if (s.fIfFalse) {
359 return ifFalse;
360 } else {
361 // False & no else clause. Not an error, so don't return null!
362 std::vector<std::unique_ptr<Statement>> empty;
363 return std::unique_ptr<Statement>(new Block(s.fOffset, std::move(empty),
364 fSymbolTable));
365 }
366 }
367 return std::unique_ptr<Statement>(new IfStatement(s.fOffset, s.fIsStatic, std::move(test),
368 std::move(ifTrue), std::move(ifFalse)));
369 }
370
convertFor(const ASTForStatement & f)371 std::unique_ptr<Statement> IRGenerator::convertFor(const ASTForStatement& f) {
372 AutoLoopLevel level(this);
373 AutoSymbolTable table(this);
374 std::unique_ptr<Statement> initializer;
375 if (f.fInitializer) {
376 initializer = this->convertStatement(*f.fInitializer);
377 if (!initializer) {
378 return nullptr;
379 }
380 }
381 std::unique_ptr<Expression> test;
382 if (f.fTest) {
383 test = this->coerce(this->convertExpression(*f.fTest), *fContext.fBool_Type);
384 if (!test) {
385 return nullptr;
386 }
387 }
388 std::unique_ptr<Expression> next;
389 if (f.fNext) {
390 next = this->convertExpression(*f.fNext);
391 if (!next) {
392 return nullptr;
393 }
394 this->checkValid(*next);
395 }
396 std::unique_ptr<Statement> statement = this->convertStatement(*f.fStatement);
397 if (!statement) {
398 return nullptr;
399 }
400 return std::unique_ptr<Statement>(new ForStatement(f.fOffset, std::move(initializer),
401 std::move(test), std::move(next),
402 std::move(statement), fSymbolTable));
403 }
404
convertWhile(const ASTWhileStatement & w)405 std::unique_ptr<Statement> IRGenerator::convertWhile(const ASTWhileStatement& w) {
406 AutoLoopLevel level(this);
407 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*w.fTest),
408 *fContext.fBool_Type);
409 if (!test) {
410 return nullptr;
411 }
412 std::unique_ptr<Statement> statement = this->convertStatement(*w.fStatement);
413 if (!statement) {
414 return nullptr;
415 }
416 return std::unique_ptr<Statement>(new WhileStatement(w.fOffset, std::move(test),
417 std::move(statement)));
418 }
419
convertDo(const ASTDoStatement & d)420 std::unique_ptr<Statement> IRGenerator::convertDo(const ASTDoStatement& d) {
421 AutoLoopLevel level(this);
422 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*d.fTest),
423 *fContext.fBool_Type);
424 if (!test) {
425 return nullptr;
426 }
427 std::unique_ptr<Statement> statement = this->convertStatement(*d.fStatement);
428 if (!statement) {
429 return nullptr;
430 }
431 return std::unique_ptr<Statement>(new DoStatement(d.fOffset, std::move(statement),
432 std::move(test)));
433 }
434
convertSwitch(const ASTSwitchStatement & s)435 std::unique_ptr<Statement> IRGenerator::convertSwitch(const ASTSwitchStatement& s) {
436 AutoSwitchLevel level(this);
437 std::unique_ptr<Expression> value = this->convertExpression(*s.fValue);
438 if (!value) {
439 return nullptr;
440 }
441 if (value->fType != *fContext.fUInt_Type && value->fType.kind() != Type::kEnum_Kind) {
442 value = this->coerce(std::move(value), *fContext.fInt_Type);
443 if (!value) {
444 return nullptr;
445 }
446 }
447 AutoSymbolTable table(this);
448 std::unordered_set<int> caseValues;
449 std::vector<std::unique_ptr<SwitchCase>> cases;
450 for (const auto& c : s.fCases) {
451 std::unique_ptr<Expression> caseValue;
452 if (c->fValue) {
453 caseValue = this->convertExpression(*c->fValue);
454 if (!caseValue) {
455 return nullptr;
456 }
457 caseValue = this->coerce(std::move(caseValue), value->fType);
458 if (!caseValue) {
459 return nullptr;
460 }
461 if (!caseValue->isConstant()) {
462 fErrors.error(caseValue->fOffset, "case value must be a constant");
463 return nullptr;
464 }
465 int64_t v;
466 this->getConstantInt(*caseValue, &v);
467 if (caseValues.find(v) != caseValues.end()) {
468 fErrors.error(caseValue->fOffset, "duplicate case value");
469 }
470 caseValues.insert(v);
471 }
472 std::vector<std::unique_ptr<Statement>> statements;
473 for (const auto& s : c->fStatements) {
474 std::unique_ptr<Statement> converted = this->convertStatement(*s);
475 if (!converted) {
476 return nullptr;
477 }
478 statements.push_back(std::move(converted));
479 }
480 cases.emplace_back(new SwitchCase(c->fOffset, std::move(caseValue),
481 std::move(statements)));
482 }
483 return std::unique_ptr<Statement>(new SwitchStatement(s.fOffset, s.fIsStatic,
484 std::move(value), std::move(cases),
485 fSymbolTable));
486 }
487
convertExpressionStatement(const ASTExpressionStatement & s)488 std::unique_ptr<Statement> IRGenerator::convertExpressionStatement(
489 const ASTExpressionStatement& s) {
490 std::unique_ptr<Expression> e = this->convertExpression(*s.fExpression);
491 if (!e) {
492 return nullptr;
493 }
494 this->checkValid(*e);
495 return std::unique_ptr<Statement>(new ExpressionStatement(std::move(e)));
496 }
497
convertReturn(const ASTReturnStatement & r)498 std::unique_ptr<Statement> IRGenerator::convertReturn(const ASTReturnStatement& r) {
499 ASSERT(fCurrentFunction);
500 // early returns from a vertex main function will bypass the sk_Position normalization, so
501 // assert that we aren't doing that. It is of course possible to fix this by adding a
502 // normalization before each return, but it will probably never actually be necessary.
503 ASSERT(Program::kVertex_Kind != fKind || !fRTAdjust || "main" != fCurrentFunction->fName);
504 if (r.fExpression) {
505 std::unique_ptr<Expression> result = this->convertExpression(*r.fExpression);
506 if (!result) {
507 return nullptr;
508 }
509 if (fCurrentFunction->fReturnType == *fContext.fVoid_Type) {
510 fErrors.error(result->fOffset, "may not return a value from a void function");
511 } else {
512 result = this->coerce(std::move(result), fCurrentFunction->fReturnType);
513 if (!result) {
514 return nullptr;
515 }
516 }
517 return std::unique_ptr<Statement>(new ReturnStatement(std::move(result)));
518 } else {
519 if (fCurrentFunction->fReturnType != *fContext.fVoid_Type) {
520 fErrors.error(r.fOffset, "expected function to return '" +
521 fCurrentFunction->fReturnType.description() + "'");
522 }
523 return std::unique_ptr<Statement>(new ReturnStatement(r.fOffset));
524 }
525 }
526
convertBreak(const ASTBreakStatement & b)527 std::unique_ptr<Statement> IRGenerator::convertBreak(const ASTBreakStatement& b) {
528 if (fLoopLevel > 0 || fSwitchLevel > 0) {
529 return std::unique_ptr<Statement>(new BreakStatement(b.fOffset));
530 } else {
531 fErrors.error(b.fOffset, "break statement must be inside a loop or switch");
532 return nullptr;
533 }
534 }
535
convertContinue(const ASTContinueStatement & c)536 std::unique_ptr<Statement> IRGenerator::convertContinue(const ASTContinueStatement& c) {
537 if (fLoopLevel > 0) {
538 return std::unique_ptr<Statement>(new ContinueStatement(c.fOffset));
539 } else {
540 fErrors.error(c.fOffset, "continue statement must be inside a loop");
541 return nullptr;
542 }
543 }
544
convertDiscard(const ASTDiscardStatement & d)545 std::unique_ptr<Statement> IRGenerator::convertDiscard(const ASTDiscardStatement& d) {
546 return std::unique_ptr<Statement>(new DiscardStatement(d.fOffset));
547 }
548
applyInvocationIDWorkaround(std::unique_ptr<Block> main)549 std::unique_ptr<Block> IRGenerator::applyInvocationIDWorkaround(std::unique_ptr<Block> main) {
550 Layout invokeLayout;
551 Modifiers invokeModifiers(invokeLayout, Modifiers::kHasSideEffects_Flag);
552 FunctionDeclaration* invokeDecl = new FunctionDeclaration(-1,
553 invokeModifiers,
554 "_invoke",
555 std::vector<const Variable*>(),
556 *fContext.fVoid_Type);
557 fProgramElements->push_back(std::unique_ptr<ProgramElement>(
558 new FunctionDefinition(-1, *invokeDecl, std::move(main))));
559 fSymbolTable->add(invokeDecl->fName, std::unique_ptr<FunctionDeclaration>(invokeDecl));
560
561 std::vector<std::unique_ptr<VarDeclaration>> variables;
562 Variable* loopIdx = (Variable*) (*fSymbolTable)["sk_InvocationID"];
563 ASSERT(loopIdx);
564 std::unique_ptr<Expression> test(new BinaryExpression(-1,
565 std::unique_ptr<Expression>(new VariableReference(-1, *loopIdx)),
566 Token::LT,
567 std::unique_ptr<IntLiteral>(new IntLiteral(fContext, -1, fInvocations)),
568 *fContext.fBool_Type));
569 std::unique_ptr<Expression> next(new PostfixExpression(
570 std::unique_ptr<Expression>(
571 new VariableReference(-1,
572 *loopIdx,
573 VariableReference::kReadWrite_RefKind)),
574 Token::PLUSPLUS));
575 ASTIdentifier endPrimitiveID = ASTIdentifier(-1, "EndPrimitive");
576 std::unique_ptr<Expression> endPrimitive = this->convertExpression(endPrimitiveID);
577 ASSERT(endPrimitive);
578
579 std::vector<std::unique_ptr<Statement>> loopBody;
580 std::vector<std::unique_ptr<Expression>> invokeArgs;
581 loopBody.push_back(std::unique_ptr<Statement>(new ExpressionStatement(
582 this->call(-1,
583 *invokeDecl,
584 std::vector<std::unique_ptr<Expression>>()))));
585 loopBody.push_back(std::unique_ptr<Statement>(new ExpressionStatement(
586 this->call(-1,
587 std::move(endPrimitive),
588 std::vector<std::unique_ptr<Expression>>()))));
589 std::unique_ptr<Expression> assignment(new BinaryExpression(-1,
590 std::unique_ptr<Expression>(new VariableReference(-1, *loopIdx)),
591 Token::EQ,
592 std::unique_ptr<IntLiteral>(new IntLiteral(fContext, -1, 0)),
593 *fContext.fInt_Type));
594 std::unique_ptr<Statement> initializer(new ExpressionStatement(std::move(assignment)));
595 std::unique_ptr<Statement> loop = std::unique_ptr<Statement>(
596 new ForStatement(-1,
597 std::move(initializer),
598 std::move(test),
599 std::move(next),
600 std::unique_ptr<Block>(new Block(-1, std::move(loopBody))),
601 fSymbolTable));
602 std::vector<std::unique_ptr<Statement>> children;
603 children.push_back(std::move(loop));
604 return std::unique_ptr<Block>(new Block(-1, std::move(children)));
605 }
606
getNormalizeSkPositionCode()607 std::unique_ptr<Statement> IRGenerator::getNormalizeSkPositionCode() {
608 // sk_Position = float4(sk_Position.x * rtAdjust.x + sk_Position.w * rtAdjust.y,
609 // sk_Position.y * rtAdjust.z + sk_Position.w * rtAdjust.w,
610 // 0,
611 // sk_Position.w);
612 ASSERT(fSkPerVertex && fRTAdjust);
613 #define REF(var) std::unique_ptr<Expression>(\
614 new VariableReference(-1, *var, VariableReference::kRead_RefKind))
615 #define FIELD(var, idx) std::unique_ptr<Expression>(\
616 new FieldAccess(REF(var), idx, FieldAccess::kAnonymousInterfaceBlock_OwnerKind))
617 #define POS std::unique_ptr<Expression>(new FieldAccess(REF(fSkPerVertex), 0, \
618 FieldAccess::kAnonymousInterfaceBlock_OwnerKind))
619 #define ADJUST (fRTAdjustInterfaceBlock ? \
620 FIELD(fRTAdjustInterfaceBlock, fRTAdjustFieldIndex) : \
621 REF(fRTAdjust))
622 #define SWIZZLE(expr, field) std::unique_ptr<Expression>(new Swizzle(fContext, expr, { field }))
623 #define OP(left, op, right) std::unique_ptr<Expression>(\
624 new BinaryExpression(-1, left, op, right, *fContext.fFloat_Type))
625 std::vector<std::unique_ptr<Expression>> children;
626 children.push_back(OP(OP(SWIZZLE(POS, 0), Token::STAR, SWIZZLE(ADJUST, 0)),
627 Token::PLUS,
628 OP(SWIZZLE(POS, 3), Token::STAR, SWIZZLE(ADJUST, 1))));
629 children.push_back(OP(OP(SWIZZLE(POS, 1), Token::STAR, SWIZZLE(ADJUST, 2)),
630 Token::PLUS,
631 OP(SWIZZLE(POS, 3), Token::STAR, SWIZZLE(ADJUST, 3))));
632 children.push_back(std::unique_ptr<Expression>(new FloatLiteral(fContext, -1, 0.0)));
633 children.push_back(SWIZZLE(POS, 3));
634 std::unique_ptr<Expression> result = OP(POS, Token::EQ,
635 std::unique_ptr<Expression>(new Constructor(-1,
636 *fContext.fFloat4_Type,
637 std::move(children))));
638 return std::unique_ptr<Statement>(new ExpressionStatement(std::move(result)));
639 }
640
convertFunction(const ASTFunction & f)641 void IRGenerator::convertFunction(const ASTFunction& f) {
642 const Type* returnType = this->convertType(*f.fReturnType);
643 if (!returnType) {
644 return;
645 }
646 std::vector<const Variable*> parameters;
647 for (const auto& param : f.fParameters) {
648 const Type* type = this->convertType(*param->fType);
649 if (!type) {
650 return;
651 }
652 for (int j = (int) param->fSizes.size() - 1; j >= 0; j--) {
653 int size = param->fSizes[j];
654 String name = type->name() + "[" + to_string(size) + "]";
655 Type* newType = new Type(std::move(name), Type::kArray_Kind, *type, size);
656 fSymbolTable->takeOwnership(newType);
657 type = newType;
658 }
659 StringFragment name = param->fName;
660 Variable* var = new Variable(param->fOffset, param->fModifiers, name, *type,
661 Variable::kParameter_Storage);
662 fSymbolTable->takeOwnership(var);
663 parameters.push_back(var);
664 }
665
666 // find existing declaration
667 const FunctionDeclaration* decl = nullptr;
668 auto entry = (*fSymbolTable)[f.fName];
669 if (entry) {
670 std::vector<const FunctionDeclaration*> functions;
671 switch (entry->fKind) {
672 case Symbol::kUnresolvedFunction_Kind:
673 functions = ((UnresolvedFunction*) entry)->fFunctions;
674 break;
675 case Symbol::kFunctionDeclaration_Kind:
676 functions.push_back((FunctionDeclaration*) entry);
677 break;
678 default:
679 fErrors.error(f.fOffset, "symbol '" + f.fName + "' was already defined");
680 return;
681 }
682 for (const auto& other : functions) {
683 ASSERT(other->fName == f.fName);
684 if (parameters.size() == other->fParameters.size()) {
685 bool match = true;
686 for (size_t i = 0; i < parameters.size(); i++) {
687 if (parameters[i]->fType != other->fParameters[i]->fType) {
688 match = false;
689 break;
690 }
691 }
692 if (match) {
693 if (*returnType != other->fReturnType) {
694 FunctionDeclaration newDecl(f.fOffset, f.fModifiers, f.fName, parameters,
695 *returnType);
696 fErrors.error(f.fOffset, "functions '" + newDecl.description() +
697 "' and '" + other->description() +
698 "' differ only in return type");
699 return;
700 }
701 decl = other;
702 for (size_t i = 0; i < parameters.size(); i++) {
703 if (parameters[i]->fModifiers != other->fParameters[i]->fModifiers) {
704 fErrors.error(f.fOffset, "modifiers on parameter " +
705 to_string((uint64_t) i + 1) +
706 " differ between declaration and "
707 "definition");
708 return;
709 }
710 }
711 if (other->fDefined) {
712 fErrors.error(f.fOffset, "duplicate definition of " +
713 other->description());
714 }
715 break;
716 }
717 }
718 }
719 }
720 if (!decl) {
721 // couldn't find an existing declaration
722 auto newDecl = std::unique_ptr<FunctionDeclaration>(new FunctionDeclaration(f.fOffset,
723 f.fModifiers,
724 f.fName,
725 parameters,
726 *returnType));
727 decl = newDecl.get();
728 fSymbolTable->add(decl->fName, std::move(newDecl));
729 }
730 if (f.fBody) {
731 ASSERT(!fCurrentFunction);
732 fCurrentFunction = decl;
733 decl->fDefined = true;
734 std::shared_ptr<SymbolTable> old = fSymbolTable;
735 AutoSymbolTable table(this);
736 for (size_t i = 0; i < parameters.size(); i++) {
737 fSymbolTable->addWithoutOwnership(parameters[i]->fName, decl->fParameters[i]);
738 }
739 bool needInvocationIDWorkaround = fInvocations != -1 && f.fName == "main" &&
740 fSettings->fCaps &&
741 !fSettings->fCaps->gsInvocationsSupport();
742 ASSERT(!fExtraVars.size());
743 std::unique_ptr<Block> body = this->convertBlock(*f.fBody);
744 for (auto& v : fExtraVars) {
745 body->fStatements.insert(body->fStatements.begin(), std::move(v));
746 }
747 fExtraVars.clear();
748 fCurrentFunction = nullptr;
749 if (!body) {
750 return;
751 }
752 if (needInvocationIDWorkaround) {
753 body = this->applyInvocationIDWorkaround(std::move(body));
754 }
755 // conservatively assume all user-defined functions have side effects
756 ((Modifiers&) decl->fModifiers).fFlags |= Modifiers::kHasSideEffects_Flag;
757 if (Program::kVertex_Kind == fKind && f.fName == "main" && fRTAdjust) {
758 body->fStatements.insert(body->fStatements.end(), this->getNormalizeSkPositionCode());
759 }
760 fProgramElements->push_back(std::unique_ptr<FunctionDefinition>(
761 new FunctionDefinition(f.fOffset, *decl, std::move(body))));
762 }
763 }
764
convertInterfaceBlock(const ASTInterfaceBlock & intf)765 std::unique_ptr<InterfaceBlock> IRGenerator::convertInterfaceBlock(const ASTInterfaceBlock& intf) {
766 std::shared_ptr<SymbolTable> old = fSymbolTable;
767 this->pushSymbolTable();
768 std::shared_ptr<SymbolTable> symbols = fSymbolTable;
769 std::vector<Type::Field> fields;
770 bool haveRuntimeArray = false;
771 bool foundRTAdjust = false;
772 for (size_t i = 0; i < intf.fDeclarations.size(); i++) {
773 std::unique_ptr<VarDeclarations> decl = this->convertVarDeclarations(
774 *intf.fDeclarations[i],
775 Variable::kGlobal_Storage);
776 if (!decl) {
777 return nullptr;
778 }
779 for (const auto& stmt : decl->fVars) {
780 VarDeclaration& vd = (VarDeclaration&) *stmt;
781 if (haveRuntimeArray) {
782 fErrors.error(decl->fOffset,
783 "only the last entry in an interface block may be a runtime-sized "
784 "array");
785 }
786 if (vd.fVar == fRTAdjust) {
787 foundRTAdjust = true;
788 ASSERT(vd.fVar->fType == *fContext.fFloat4_Type);
789 fRTAdjustFieldIndex = fields.size();
790 }
791 fields.push_back(Type::Field(vd.fVar->fModifiers, vd.fVar->fName,
792 &vd.fVar->fType));
793 if (vd.fValue) {
794 fErrors.error(decl->fOffset,
795 "initializers are not permitted on interface block fields");
796 }
797 if (vd.fVar->fModifiers.fFlags & (Modifiers::kIn_Flag |
798 Modifiers::kOut_Flag |
799 Modifiers::kUniform_Flag |
800 Modifiers::kBuffer_Flag |
801 Modifiers::kConst_Flag)) {
802 fErrors.error(decl->fOffset,
803 "interface block fields may not have storage qualifiers");
804 }
805 if (vd.fVar->fType.kind() == Type::kArray_Kind &&
806 vd.fVar->fType.columns() == -1) {
807 haveRuntimeArray = true;
808 }
809 }
810 }
811 this->popSymbolTable();
812 Type* type = new Type(intf.fOffset, intf.fTypeName, fields);
813 old->takeOwnership(type);
814 std::vector<std::unique_ptr<Expression>> sizes;
815 for (const auto& size : intf.fSizes) {
816 if (size) {
817 std::unique_ptr<Expression> converted = this->convertExpression(*size);
818 if (!converted) {
819 return nullptr;
820 }
821 String name = type->fName;
822 int64_t count;
823 if (converted->fKind == Expression::kIntLiteral_Kind) {
824 count = ((IntLiteral&) *converted).fValue;
825 if (count <= 0) {
826 fErrors.error(converted->fOffset, "array size must be positive");
827 }
828 name += "[" + to_string(count) + "]";
829 } else {
830 count = -1;
831 name += "[]";
832 }
833 type = new Type(name, Type::kArray_Kind, *type, (int) count);
834 symbols->takeOwnership((Type*) type);
835 sizes.push_back(std::move(converted));
836 } else {
837 type = new Type(type->name() + "[]", Type::kArray_Kind, *type, -1);
838 symbols->takeOwnership((Type*) type);
839 sizes.push_back(nullptr);
840 }
841 }
842 Variable* var = new Variable(intf.fOffset, intf.fModifiers,
843 intf.fInstanceName.fLength ? intf.fInstanceName : intf.fTypeName,
844 *type, Variable::kGlobal_Storage);
845 if (foundRTAdjust) {
846 fRTAdjustInterfaceBlock = var;
847 }
848 old->takeOwnership(var);
849 if (intf.fInstanceName.fLength) {
850 old->addWithoutOwnership(intf.fInstanceName, var);
851 } else {
852 for (size_t i = 0; i < fields.size(); i++) {
853 old->add(fields[i].fName, std::unique_ptr<Field>(new Field(intf.fOffset, *var,
854 (int) i)));
855 }
856 }
857 if (var->fName == Compiler::PERVERTEX_NAME) {
858 ASSERT(!fSkPerVertex);
859 fSkPerVertex = var;
860 }
861 return std::unique_ptr<InterfaceBlock>(new InterfaceBlock(intf.fOffset,
862 var,
863 intf.fTypeName,
864 intf.fInstanceName,
865 std::move(sizes),
866 symbols));
867 }
868
getConstantInt(const Expression & value,int64_t * out)869 void IRGenerator::getConstantInt(const Expression& value, int64_t* out) {
870 switch (value.fKind) {
871 case Expression::kIntLiteral_Kind:
872 *out = ((const IntLiteral&) value).fValue;
873 break;
874 case Expression::kVariableReference_Kind: {
875 const Variable& var = ((VariableReference&) value).fVariable;
876 if ((var.fModifiers.fFlags & Modifiers::kConst_Flag) &&
877 var.fInitialValue) {
878 this->getConstantInt(*var.fInitialValue, out);
879 }
880 break;
881 }
882 default:
883 fErrors.error(value.fOffset, "expected a constant int");
884 }
885 }
886
convertEnum(const ASTEnum & e)887 void IRGenerator::convertEnum(const ASTEnum& e) {
888 std::vector<Variable*> variables;
889 int64_t currentValue = 0;
890 Layout layout;
891 ASTType enumType(e.fOffset, e.fTypeName, ASTType::kIdentifier_Kind, {});
892 const Type* type = this->convertType(enumType);
893 Modifiers modifiers(layout, Modifiers::kConst_Flag);
894 std::shared_ptr<SymbolTable> symbols(new SymbolTable(fSymbolTable, &fErrors));
895 fSymbolTable = symbols;
896 for (size_t i = 0; i < e.fNames.size(); i++) {
897 std::unique_ptr<Expression> value;
898 if (e.fValues[i]) {
899 value = this->convertExpression(*e.fValues[i]);
900 if (!value) {
901 fSymbolTable = symbols->fParent;
902 return;
903 }
904 this->getConstantInt(*value, ¤tValue);
905 }
906 value = std::unique_ptr<Expression>(new IntLiteral(fContext, e.fOffset, currentValue));
907 ++currentValue;
908 auto var = std::unique_ptr<Variable>(new Variable(e.fOffset, modifiers, e.fNames[i],
909 *type, Variable::kGlobal_Storage,
910 value.get()));
911 variables.push_back(var.get());
912 symbols->add(e.fNames[i], std::move(var));
913 symbols->takeOwnership(value.release());
914 }
915 fProgramElements->push_back(std::unique_ptr<ProgramElement>(new Enum(e.fOffset, e.fTypeName,
916 symbols)));
917 fSymbolTable = symbols->fParent;
918 }
919
convertType(const ASTType & type)920 const Type* IRGenerator::convertType(const ASTType& type) {
921 const Symbol* result = (*fSymbolTable)[type.fName];
922 if (result && result->fKind == Symbol::kType_Kind) {
923 for (int size : type.fSizes) {
924 String name(result->fName);
925 name += "[";
926 if (size != -1) {
927 name += to_string(size);
928 }
929 name += "]";
930 result = new Type(name, Type::kArray_Kind, (const Type&) *result, size);
931 fSymbolTable->takeOwnership((Type*) result);
932 }
933 return (const Type*) result;
934 }
935 fErrors.error(type.fOffset, "unknown type '" + type.fName + "'");
936 return nullptr;
937 }
938
convertExpression(const ASTExpression & expr)939 std::unique_ptr<Expression> IRGenerator::convertExpression(const ASTExpression& expr) {
940 switch (expr.fKind) {
941 case ASTExpression::kIdentifier_Kind:
942 return this->convertIdentifier((ASTIdentifier&) expr);
943 case ASTExpression::kBool_Kind:
944 return std::unique_ptr<Expression>(new BoolLiteral(fContext, expr.fOffset,
945 ((ASTBoolLiteral&) expr).fValue));
946 case ASTExpression::kInt_Kind:
947 return std::unique_ptr<Expression>(new IntLiteral(fContext, expr.fOffset,
948 ((ASTIntLiteral&) expr).fValue));
949 case ASTExpression::kFloat_Kind:
950 return std::unique_ptr<Expression>(new FloatLiteral(fContext, expr.fOffset,
951 ((ASTFloatLiteral&) expr).fValue));
952 case ASTExpression::kBinary_Kind:
953 return this->convertBinaryExpression((ASTBinaryExpression&) expr);
954 case ASTExpression::kPrefix_Kind:
955 return this->convertPrefixExpression((ASTPrefixExpression&) expr);
956 case ASTExpression::kSuffix_Kind:
957 return this->convertSuffixExpression((ASTSuffixExpression&) expr);
958 case ASTExpression::kTernary_Kind:
959 return this->convertTernaryExpression((ASTTernaryExpression&) expr);
960 default:
961 ABORT("unsupported expression type: %d\n", expr.fKind);
962 }
963 }
964
convertIdentifier(const ASTIdentifier & identifier)965 std::unique_ptr<Expression> IRGenerator::convertIdentifier(const ASTIdentifier& identifier) {
966 const Symbol* result = (*fSymbolTable)[identifier.fText];
967 if (!result) {
968 fErrors.error(identifier.fOffset, "unknown identifier '" + identifier.fText + "'");
969 return nullptr;
970 }
971 switch (result->fKind) {
972 case Symbol::kFunctionDeclaration_Kind: {
973 std::vector<const FunctionDeclaration*> f = {
974 (const FunctionDeclaration*) result
975 };
976 return std::unique_ptr<FunctionReference>(new FunctionReference(fContext,
977 identifier.fOffset,
978 f));
979 }
980 case Symbol::kUnresolvedFunction_Kind: {
981 const UnresolvedFunction* f = (const UnresolvedFunction*) result;
982 return std::unique_ptr<FunctionReference>(new FunctionReference(fContext,
983 identifier.fOffset,
984 f->fFunctions));
985 }
986 case Symbol::kVariable_Kind: {
987 const Variable* var = (const Variable*) result;
988 #ifndef SKSL_STANDALONE
989 if (var->fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
990 fInputs.fFlipY = true;
991 if (fSettings->fFlipY &&
992 (!fSettings->fCaps ||
993 !fSettings->fCaps->fragCoordConventionsExtensionString())) {
994 fInputs.fRTHeight = true;
995 }
996 }
997 #endif
998 // default to kRead_RefKind; this will be corrected later if the variable is written to
999 return std::unique_ptr<VariableReference>(new VariableReference(
1000 identifier.fOffset,
1001 *var,
1002 VariableReference::kRead_RefKind));
1003 }
1004 case Symbol::kField_Kind: {
1005 const Field* field = (const Field*) result;
1006 VariableReference* base = new VariableReference(identifier.fOffset, field->fOwner,
1007 VariableReference::kRead_RefKind);
1008 return std::unique_ptr<Expression>(new FieldAccess(
1009 std::unique_ptr<Expression>(base),
1010 field->fFieldIndex,
1011 FieldAccess::kAnonymousInterfaceBlock_OwnerKind));
1012 }
1013 case Symbol::kType_Kind: {
1014 const Type* t = (const Type*) result;
1015 return std::unique_ptr<TypeReference>(new TypeReference(fContext, identifier.fOffset,
1016 *t));
1017 }
1018 default:
1019 ABORT("unsupported symbol type %d\n", result->fKind);
1020 }
1021 }
1022
convertSection(const ASTSection & s)1023 std::unique_ptr<Section> IRGenerator::convertSection(const ASTSection& s) {
1024 return std::unique_ptr<Section>(new Section(s.fOffset, s.fName, s.fArgument, s.fText));
1025 }
1026
1027
coerce(std::unique_ptr<Expression> expr,const Type & type)1028 std::unique_ptr<Expression> IRGenerator::coerce(std::unique_ptr<Expression> expr,
1029 const Type& type) {
1030 if (!expr) {
1031 return nullptr;
1032 }
1033 if (expr->fType == type) {
1034 return expr;
1035 }
1036 this->checkValid(*expr);
1037 if (expr->fType == *fContext.fInvalid_Type) {
1038 return nullptr;
1039 }
1040 if (expr->coercionCost(type) == INT_MAX) {
1041 fErrors.error(expr->fOffset, "expected '" + type.description() + "', but found '" +
1042 expr->fType.description() + "'");
1043 return nullptr;
1044 }
1045 if (type.kind() == Type::kScalar_Kind) {
1046 std::vector<std::unique_ptr<Expression>> args;
1047 args.push_back(std::move(expr));
1048 ASTIdentifier id(-1, type.fName);
1049 std::unique_ptr<Expression> ctor = this->convertIdentifier(id);
1050 ASSERT(ctor);
1051 return this->call(-1, std::move(ctor), std::move(args));
1052 }
1053 std::vector<std::unique_ptr<Expression>> args;
1054 args.push_back(std::move(expr));
1055 return std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
1056 }
1057
is_matrix_multiply(const Type & left,const Type & right)1058 static bool is_matrix_multiply(const Type& left, const Type& right) {
1059 if (left.kind() == Type::kMatrix_Kind) {
1060 return right.kind() == Type::kMatrix_Kind || right.kind() == Type::kVector_Kind;
1061 }
1062 return left.kind() == Type::kVector_Kind && right.kind() == Type::kMatrix_Kind;
1063 }
1064
1065 /**
1066 * Determines the operand and result types of a binary expression. Returns true if the expression is
1067 * legal, false otherwise. If false, the values of the out parameters are undefined.
1068 */
determine_binary_type(const Context & context,Token::Kind op,const Type & left,const Type & right,const Type ** outLeftType,const Type ** outRightType,const Type ** outResultType,bool tryFlipped)1069 static bool determine_binary_type(const Context& context,
1070 Token::Kind op,
1071 const Type& left,
1072 const Type& right,
1073 const Type** outLeftType,
1074 const Type** outRightType,
1075 const Type** outResultType,
1076 bool tryFlipped) {
1077 bool isLogical;
1078 bool validMatrixOrVectorOp;
1079 switch (op) {
1080 case Token::EQ:
1081 *outLeftType = &left;
1082 *outRightType = &left;
1083 *outResultType = &left;
1084 return right.canCoerceTo(left);
1085 case Token::EQEQ: // fall through
1086 case Token::NEQ:
1087 if (left == right) {
1088 *outLeftType = &left;
1089 *outRightType = &right;
1090 *outResultType = context.fBool_Type.get();
1091 return true;
1092 }
1093 isLogical = true;
1094 validMatrixOrVectorOp = true;
1095 break;
1096 case Token::LT: // fall through
1097 case Token::GT: // fall through
1098 case Token::LTEQ: // fall through
1099 case Token::GTEQ:
1100 isLogical = true;
1101 validMatrixOrVectorOp = false;
1102 break;
1103 case Token::LOGICALOR: // fall through
1104 case Token::LOGICALAND: // fall through
1105 case Token::LOGICALXOR: // fall through
1106 case Token::LOGICALOREQ: // fall through
1107 case Token::LOGICALANDEQ: // fall through
1108 case Token::LOGICALXOREQ:
1109 *outLeftType = context.fBool_Type.get();
1110 *outRightType = context.fBool_Type.get();
1111 *outResultType = context.fBool_Type.get();
1112 return left.canCoerceTo(*context.fBool_Type) &&
1113 right.canCoerceTo(*context.fBool_Type);
1114 case Token::STAREQ:
1115 if (left.kind() == Type::kScalar_Kind) {
1116 *outLeftType = &left;
1117 *outRightType = &left;
1118 *outResultType = &left;
1119 return right.canCoerceTo(left);
1120 }
1121 // fall through
1122 case Token::STAR:
1123 if (is_matrix_multiply(left, right)) {
1124 // determine final component type
1125 if (determine_binary_type(context, Token::STAR, left.componentType(),
1126 right.componentType(), outLeftType, outRightType,
1127 outResultType, false)) {
1128 *outLeftType = &(*outResultType)->toCompound(context, left.columns(),
1129 left.rows());;
1130 *outRightType = &(*outResultType)->toCompound(context, right.columns(),
1131 right.rows());;
1132 int leftColumns = left.columns();
1133 int leftRows = left.rows();
1134 int rightColumns;
1135 int rightRows;
1136 if (right.kind() == Type::kVector_Kind) {
1137 // matrix * vector treats the vector as a column vector, so we need to
1138 // transpose it
1139 rightColumns = right.rows();
1140 rightRows = right.columns();
1141 ASSERT(rightColumns == 1);
1142 } else {
1143 rightColumns = right.columns();
1144 rightRows = right.rows();
1145 }
1146 if (rightColumns > 1) {
1147 *outResultType = &(*outResultType)->toCompound(context, rightColumns,
1148 leftRows);
1149 } else {
1150 // result was a column vector, transpose it back to a row
1151 *outResultType = &(*outResultType)->toCompound(context, leftRows,
1152 rightColumns);
1153 }
1154 return leftColumns == rightRows;
1155 } else {
1156 return false;
1157 }
1158 }
1159 isLogical = false;
1160 validMatrixOrVectorOp = true;
1161 break;
1162 case Token::PLUSEQ:
1163 case Token::MINUSEQ:
1164 case Token::SLASHEQ:
1165 case Token::PERCENTEQ:
1166 case Token::SHLEQ:
1167 case Token::SHREQ:
1168 if (left.kind() == Type::kScalar_Kind) {
1169 *outLeftType = &left;
1170 *outRightType = &left;
1171 *outResultType = &left;
1172 return right.canCoerceTo(left);
1173 }
1174 // fall through
1175 case Token::PLUS: // fall through
1176 case Token::MINUS: // fall through
1177 case Token::SLASH: // fall through
1178 isLogical = false;
1179 validMatrixOrVectorOp = true;
1180 break;
1181 case Token::COMMA:
1182 *outLeftType = &left;
1183 *outRightType = &right;
1184 *outResultType = &right;
1185 return true;
1186 default:
1187 isLogical = false;
1188 validMatrixOrVectorOp = false;
1189 }
1190 bool isVectorOrMatrix = left.kind() == Type::kVector_Kind || left.kind() == Type::kMatrix_Kind;
1191 if (left.kind() == Type::kScalar_Kind && right.kind() == Type::kScalar_Kind &&
1192 right.canCoerceTo(left)) {
1193 if (left.priority() > right.priority()) {
1194 *outLeftType = &left;
1195 *outRightType = &left;
1196 } else {
1197 *outLeftType = &right;
1198 *outRightType = &right;
1199 }
1200 if (isLogical) {
1201 *outResultType = context.fBool_Type.get();
1202 } else {
1203 *outResultType = &left;
1204 }
1205 return true;
1206 }
1207 if (right.canCoerceTo(left) && isVectorOrMatrix && validMatrixOrVectorOp) {
1208 *outLeftType = &left;
1209 *outRightType = &left;
1210 if (isLogical) {
1211 *outResultType = context.fBool_Type.get();
1212 } else {
1213 *outResultType = &left;
1214 }
1215 return true;
1216 }
1217 if ((left.kind() == Type::kVector_Kind || left.kind() == Type::kMatrix_Kind) &&
1218 (right.kind() == Type::kScalar_Kind)) {
1219 if (determine_binary_type(context, op, left.componentType(), right, outLeftType,
1220 outRightType, outResultType, false)) {
1221 *outLeftType = &(*outLeftType)->toCompound(context, left.columns(), left.rows());
1222 if (!isLogical) {
1223 *outResultType = &(*outResultType)->toCompound(context, left.columns(),
1224 left.rows());
1225 }
1226 return true;
1227 }
1228 return false;
1229 }
1230 if (tryFlipped) {
1231 return determine_binary_type(context, op, right, left, outRightType, outLeftType,
1232 outResultType, false);
1233 }
1234 return false;
1235 }
1236
constantFold(const Expression & left,Token::Kind op,const Expression & right) const1237 std::unique_ptr<Expression> IRGenerator::constantFold(const Expression& left,
1238 Token::Kind op,
1239 const Expression& right) const {
1240 if (!left.isConstant() || !right.isConstant()) {
1241 return nullptr;
1242 }
1243 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
1244 // precision to calculate the results and hope the result makes sense. The plan is to move the
1245 // Skia caps into SkSL, so we have access to all of them including the precisions of the various
1246 // types, which will let us be more intelligent about this.
1247 if (left.fKind == Expression::kBoolLiteral_Kind &&
1248 right.fKind == Expression::kBoolLiteral_Kind) {
1249 bool leftVal = ((BoolLiteral&) left).fValue;
1250 bool rightVal = ((BoolLiteral&) right).fValue;
1251 bool result;
1252 switch (op) {
1253 case Token::LOGICALAND: result = leftVal && rightVal; break;
1254 case Token::LOGICALOR: result = leftVal || rightVal; break;
1255 case Token::LOGICALXOR: result = leftVal ^ rightVal; break;
1256 default: return nullptr;
1257 }
1258 return std::unique_ptr<Expression>(new BoolLiteral(fContext, left.fOffset, result));
1259 }
1260 #define RESULT(t, op) std::unique_ptr<Expression>(new t ## Literal(fContext, left.fOffset, \
1261 leftVal op rightVal))
1262 if (left.fKind == Expression::kIntLiteral_Kind && right.fKind == Expression::kIntLiteral_Kind) {
1263 int64_t leftVal = ((IntLiteral&) left).fValue;
1264 int64_t rightVal = ((IntLiteral&) right).fValue;
1265 switch (op) {
1266 case Token::PLUS: return RESULT(Int, +);
1267 case Token::MINUS: return RESULT(Int, -);
1268 case Token::STAR: return RESULT(Int, *);
1269 case Token::SLASH:
1270 if (rightVal) {
1271 return RESULT(Int, /);
1272 }
1273 fErrors.error(right.fOffset, "division by zero");
1274 return nullptr;
1275 case Token::PERCENT:
1276 if (rightVal) {
1277 return RESULT(Int, %);
1278 }
1279 fErrors.error(right.fOffset, "division by zero");
1280 return nullptr;
1281 case Token::BITWISEAND: return RESULT(Int, &);
1282 case Token::BITWISEOR: return RESULT(Int, |);
1283 case Token::BITWISEXOR: return RESULT(Int, ^);
1284 case Token::SHL: return RESULT(Int, <<);
1285 case Token::SHR: return RESULT(Int, >>);
1286 case Token::EQEQ: return RESULT(Bool, ==);
1287 case Token::NEQ: return RESULT(Bool, !=);
1288 case Token::GT: return RESULT(Bool, >);
1289 case Token::GTEQ: return RESULT(Bool, >=);
1290 case Token::LT: return RESULT(Bool, <);
1291 case Token::LTEQ: return RESULT(Bool, <=);
1292 default: return nullptr;
1293 }
1294 }
1295 if (left.fKind == Expression::kFloatLiteral_Kind &&
1296 right.fKind == Expression::kFloatLiteral_Kind) {
1297 double leftVal = ((FloatLiteral&) left).fValue;
1298 double rightVal = ((FloatLiteral&) right).fValue;
1299 switch (op) {
1300 case Token::PLUS: return RESULT(Float, +);
1301 case Token::MINUS: return RESULT(Float, -);
1302 case Token::STAR: return RESULT(Float, *);
1303 case Token::SLASH:
1304 if (rightVal) {
1305 return RESULT(Float, /);
1306 }
1307 fErrors.error(right.fOffset, "division by zero");
1308 return nullptr;
1309 case Token::EQEQ: return RESULT(Bool, ==);
1310 case Token::NEQ: return RESULT(Bool, !=);
1311 case Token::GT: return RESULT(Bool, >);
1312 case Token::GTEQ: return RESULT(Bool, >=);
1313 case Token::LT: return RESULT(Bool, <);
1314 case Token::LTEQ: return RESULT(Bool, <=);
1315 default: return nullptr;
1316 }
1317 }
1318 if (left.fType.kind() == Type::kVector_Kind &&
1319 left.fType.componentType() == *fContext.fFloat_Type &&
1320 left.fType == right.fType) {
1321 ASSERT(left.fKind == Expression::kConstructor_Kind);
1322 ASSERT(right.fKind == Expression::kConstructor_Kind);
1323 std::vector<std::unique_ptr<Expression>> args;
1324 #define RETURN_VEC_COMPONENTWISE_RESULT(op) \
1325 for (int i = 0; i < left.fType.columns(); i++) { \
1326 float value = ((Constructor&) left).getFVecComponent(i) op \
1327 ((Constructor&) right).getFVecComponent(i); \
1328 args.emplace_back(new FloatLiteral(fContext, -1, value)); \
1329 } \
1330 return std::unique_ptr<Expression>(new Constructor(-1, left.fType, \
1331 std::move(args)));
1332 switch (op) {
1333 case Token::EQEQ:
1334 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
1335 left.compareConstant(fContext, right)));
1336 case Token::NEQ:
1337 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
1338 !left.compareConstant(fContext, right)));
1339 case Token::PLUS: RETURN_VEC_COMPONENTWISE_RESULT(+);
1340 case Token::MINUS: RETURN_VEC_COMPONENTWISE_RESULT(-);
1341 case Token::STAR: RETURN_VEC_COMPONENTWISE_RESULT(*);
1342 case Token::SLASH: RETURN_VEC_COMPONENTWISE_RESULT(/);
1343 default: return nullptr;
1344 }
1345 }
1346 if (left.fType.kind() == Type::kMatrix_Kind &&
1347 right.fType.kind() == Type::kMatrix_Kind &&
1348 left.fKind == right.fKind) {
1349 switch (op) {
1350 case Token::EQEQ:
1351 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
1352 left.compareConstant(fContext, right)));
1353 case Token::NEQ:
1354 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
1355 !left.compareConstant(fContext, right)));
1356 default:
1357 return nullptr;
1358 }
1359 }
1360 #undef RESULT
1361 return nullptr;
1362 }
1363
convertBinaryExpression(const ASTBinaryExpression & expression)1364 std::unique_ptr<Expression> IRGenerator::convertBinaryExpression(
1365 const ASTBinaryExpression& expression) {
1366 std::unique_ptr<Expression> left = this->convertExpression(*expression.fLeft);
1367 if (!left) {
1368 return nullptr;
1369 }
1370 std::unique_ptr<Expression> right = this->convertExpression(*expression.fRight);
1371 if (!right) {
1372 return nullptr;
1373 }
1374 const Type* leftType;
1375 const Type* rightType;
1376 const Type* resultType;
1377 const Type* rawLeftType;
1378 if (left->fKind == Expression::kIntLiteral_Kind && right->fType.isInteger()) {
1379 rawLeftType = &right->fType;
1380 } else {
1381 rawLeftType = &left->fType;
1382 }
1383 const Type* rawRightType;
1384 if (right->fKind == Expression::kIntLiteral_Kind && left->fType.isInteger()) {
1385 rawRightType = &left->fType;
1386 } else {
1387 rawRightType = &right->fType;
1388 }
1389 if (!determine_binary_type(fContext, expression.fOperator, *rawLeftType, *rawRightType,
1390 &leftType, &rightType, &resultType,
1391 !Compiler::IsAssignment(expression.fOperator))) {
1392 fErrors.error(expression.fOffset, String("type mismatch: '") +
1393 Compiler::OperatorName(expression.fOperator) +
1394 "' cannot operate on '" + left->fType.fName +
1395 "', '" + right->fType.fName + "'");
1396 return nullptr;
1397 }
1398 if (Compiler::IsAssignment(expression.fOperator)) {
1399 this->markWrittenTo(*left, expression.fOperator != Token::EQ);
1400 }
1401 left = this->coerce(std::move(left), *leftType);
1402 right = this->coerce(std::move(right), *rightType);
1403 if (!left || !right) {
1404 return nullptr;
1405 }
1406 std::unique_ptr<Expression> result = this->constantFold(*left.get(), expression.fOperator,
1407 *right.get());
1408 if (!result) {
1409 result = std::unique_ptr<Expression>(new BinaryExpression(expression.fOffset,
1410 std::move(left),
1411 expression.fOperator,
1412 std::move(right),
1413 *resultType));
1414 }
1415 return result;
1416 }
1417
convertTernaryExpression(const ASTTernaryExpression & expression)1418 std::unique_ptr<Expression> IRGenerator::convertTernaryExpression(
1419 const ASTTernaryExpression& expression) {
1420 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*expression.fTest),
1421 *fContext.fBool_Type);
1422 if (!test) {
1423 return nullptr;
1424 }
1425 std::unique_ptr<Expression> ifTrue = this->convertExpression(*expression.fIfTrue);
1426 if (!ifTrue) {
1427 return nullptr;
1428 }
1429 std::unique_ptr<Expression> ifFalse = this->convertExpression(*expression.fIfFalse);
1430 if (!ifFalse) {
1431 return nullptr;
1432 }
1433 const Type* trueType;
1434 const Type* falseType;
1435 const Type* resultType;
1436 if (!determine_binary_type(fContext, Token::EQEQ, ifTrue->fType, ifFalse->fType, &trueType,
1437 &falseType, &resultType, true) || trueType != falseType) {
1438 fErrors.error(expression.fOffset, "ternary operator result mismatch: '" +
1439 ifTrue->fType.fName + "', '" +
1440 ifFalse->fType.fName + "'");
1441 return nullptr;
1442 }
1443 ifTrue = this->coerce(std::move(ifTrue), *trueType);
1444 if (!ifTrue) {
1445 return nullptr;
1446 }
1447 ifFalse = this->coerce(std::move(ifFalse), *falseType);
1448 if (!ifFalse) {
1449 return nullptr;
1450 }
1451 if (test->fKind == Expression::kBoolLiteral_Kind) {
1452 // static boolean test, just return one of the branches
1453 if (((BoolLiteral&) *test).fValue) {
1454 return ifTrue;
1455 } else {
1456 return ifFalse;
1457 }
1458 }
1459 return std::unique_ptr<Expression>(new TernaryExpression(expression.fOffset,
1460 std::move(test),
1461 std::move(ifTrue),
1462 std::move(ifFalse)));
1463 }
1464
1465 // scales the texture coordinates by the texture size for sampling rectangle textures.
1466 // For float2coordinates, implements the transformation:
1467 // texture(sampler, coord) -> texture(sampler, textureSize(sampler) * coord)
1468 // For float3coordinates, implements the transformation:
1469 // texture(sampler, coord) -> texture(sampler, float3textureSize(sampler), 1.0) * coord))
fixRectSampling(std::vector<std::unique_ptr<Expression>> & arguments)1470 void IRGenerator::fixRectSampling(std::vector<std::unique_ptr<Expression>>& arguments) {
1471 ASSERT(arguments.size() == 2);
1472 ASSERT(arguments[0]->fType == *fContext.fSampler2DRect_Type);
1473 ASSERT(arguments[0]->fKind == Expression::kVariableReference_Kind);
1474 const Variable& sampler = ((VariableReference&) *arguments[0]).fVariable;
1475 const Symbol* textureSizeSymbol = (*fSymbolTable)["textureSize"];
1476 ASSERT(textureSizeSymbol->fKind == Symbol::kFunctionDeclaration_Kind);
1477 const FunctionDeclaration& textureSize = (FunctionDeclaration&) *textureSizeSymbol;
1478 std::vector<std::unique_ptr<Expression>> sizeArguments;
1479 sizeArguments.emplace_back(new VariableReference(-1, sampler));
1480 std::unique_ptr<Expression> float2ize = call(-1, textureSize, std::move(sizeArguments));
1481 const Type& type = arguments[1]->fType;
1482 std::unique_ptr<Expression> scale;
1483 if (type == *fContext.fFloat2_Type) {
1484 scale = std::move(float2ize);
1485 } else {
1486 ASSERT(type == *fContext.fFloat3_Type);
1487 std::vector<std::unique_ptr<Expression>> float3rguments;
1488 float3rguments.push_back(std::move(float2ize));
1489 float3rguments.emplace_back(new FloatLiteral(fContext, -1, 1.0));
1490 scale.reset(new Constructor(-1, *fContext.fFloat3_Type, std::move(float3rguments)));
1491 }
1492 arguments[1].reset(new BinaryExpression(-1, std::move(scale), Token::STAR,
1493 std::move(arguments[1]), type));
1494 }
1495
call(int offset,const FunctionDeclaration & function,std::vector<std::unique_ptr<Expression>> arguments)1496 std::unique_ptr<Expression> IRGenerator::call(int offset,
1497 const FunctionDeclaration& function,
1498 std::vector<std::unique_ptr<Expression>> arguments) {
1499 if (function.fParameters.size() != arguments.size()) {
1500 String msg = "call to '" + function.fName + "' expected " +
1501 to_string((uint64_t) function.fParameters.size()) +
1502 " argument";
1503 if (function.fParameters.size() != 1) {
1504 msg += "s";
1505 }
1506 msg += ", but found " + to_string((uint64_t) arguments.size());
1507 fErrors.error(offset, msg);
1508 return nullptr;
1509 }
1510 std::vector<const Type*> types;
1511 const Type* returnType;
1512 if (!function.determineFinalTypes(arguments, &types, &returnType)) {
1513 String msg = "no match for " + function.fName + "(";
1514 String separator;
1515 for (size_t i = 0; i < arguments.size(); i++) {
1516 msg += separator;
1517 separator = ", ";
1518 msg += arguments[i]->fType.description();
1519 }
1520 msg += ")";
1521 fErrors.error(offset, msg);
1522 return nullptr;
1523 }
1524 for (size_t i = 0; i < arguments.size(); i++) {
1525 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
1526 if (!arguments[i]) {
1527 return nullptr;
1528 }
1529 if (arguments[i] && (function.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag)) {
1530 this->markWrittenTo(*arguments[i],
1531 function.fParameters[i]->fModifiers.fFlags & Modifiers::kIn_Flag);
1532 }
1533 }
1534 if (function.fBuiltin && function.fName == "texture" &&
1535 arguments[0]->fType == *fContext.fSampler2DRect_Type) {
1536 this->fixRectSampling(arguments);
1537 }
1538 return std::unique_ptr<FunctionCall>(new FunctionCall(offset, *returnType, function,
1539 std::move(arguments)));
1540 }
1541
1542 /**
1543 * Determines the cost of coercing the arguments of a function to the required types. Cost has no
1544 * particular meaning other than "lower costs are preferred". Returns INT_MAX if the call is not
1545 * valid.
1546 */
callCost(const FunctionDeclaration & function,const std::vector<std::unique_ptr<Expression>> & arguments)1547 int IRGenerator::callCost(const FunctionDeclaration& function,
1548 const std::vector<std::unique_ptr<Expression>>& arguments) {
1549 if (function.fParameters.size() != arguments.size()) {
1550 return INT_MAX;
1551 }
1552 int total = 0;
1553 std::vector<const Type*> types;
1554 const Type* ignored;
1555 if (!function.determineFinalTypes(arguments, &types, &ignored)) {
1556 return INT_MAX;
1557 }
1558 for (size_t i = 0; i < arguments.size(); i++) {
1559 int cost = arguments[i]->coercionCost(*types[i]);
1560 if (cost != INT_MAX) {
1561 total += cost;
1562 } else {
1563 return INT_MAX;
1564 }
1565 }
1566 return total;
1567 }
1568
call(int offset,std::unique_ptr<Expression> functionValue,std::vector<std::unique_ptr<Expression>> arguments)1569 std::unique_ptr<Expression> IRGenerator::call(int offset,
1570 std::unique_ptr<Expression> functionValue,
1571 std::vector<std::unique_ptr<Expression>> arguments) {
1572 if (functionValue->fKind == Expression::kTypeReference_Kind) {
1573 return this->convertConstructor(offset,
1574 ((TypeReference&) *functionValue).fValue,
1575 std::move(arguments));
1576 }
1577 if (functionValue->fKind != Expression::kFunctionReference_Kind) {
1578 fErrors.error(offset, "'" + functionValue->description() + "' is not a function");
1579 return nullptr;
1580 }
1581 FunctionReference* ref = (FunctionReference*) functionValue.get();
1582 int bestCost = INT_MAX;
1583 const FunctionDeclaration* best = nullptr;
1584 if (ref->fFunctions.size() > 1) {
1585 for (const auto& f : ref->fFunctions) {
1586 int cost = this->callCost(*f, arguments);
1587 if (cost < bestCost) {
1588 bestCost = cost;
1589 best = f;
1590 }
1591 }
1592 if (best) {
1593 return this->call(offset, *best, std::move(arguments));
1594 }
1595 String msg = "no match for " + ref->fFunctions[0]->fName + "(";
1596 String separator;
1597 for (size_t i = 0; i < arguments.size(); i++) {
1598 msg += separator;
1599 separator = ", ";
1600 msg += arguments[i]->fType.description();
1601 }
1602 msg += ")";
1603 fErrors.error(offset, msg);
1604 return nullptr;
1605 }
1606 return this->call(offset, *ref->fFunctions[0], std::move(arguments));
1607 }
1608
convertNumberConstructor(int offset,const Type & type,std::vector<std::unique_ptr<Expression>> args)1609 std::unique_ptr<Expression> IRGenerator::convertNumberConstructor(
1610 int offset,
1611 const Type& type,
1612 std::vector<std::unique_ptr<Expression>> args) {
1613 ASSERT(type.isNumber());
1614 if (args.size() != 1) {
1615 fErrors.error(offset, "invalid arguments to '" + type.description() +
1616 "' constructor, (expected exactly 1 argument, but found " +
1617 to_string((uint64_t) args.size()) + ")");
1618 return nullptr;
1619 }
1620 if (type == args[0]->fType) {
1621 return std::move(args[0]);
1622 }
1623 if (type.isFloat() && args.size() == 1 && args[0]->fKind == Expression::kFloatLiteral_Kind) {
1624 double value = ((FloatLiteral&) *args[0]).fValue;
1625 return std::unique_ptr<Expression>(new FloatLiteral(fContext, offset, value, &type));
1626 }
1627 if (type.isFloat() && args.size() == 1 && args[0]->fKind == Expression::kIntLiteral_Kind) {
1628 int64_t value = ((IntLiteral&) *args[0]).fValue;
1629 return std::unique_ptr<Expression>(new FloatLiteral(fContext, offset, (double) value,
1630 &type));
1631 }
1632 if (args[0]->fKind == Expression::kIntLiteral_Kind && (type == *fContext.fInt_Type ||
1633 type == *fContext.fUInt_Type)) {
1634 return std::unique_ptr<Expression>(new IntLiteral(fContext,
1635 offset,
1636 ((IntLiteral&) *args[0]).fValue,
1637 &type));
1638 }
1639 if (args[0]->fType == *fContext.fBool_Type) {
1640 std::unique_ptr<IntLiteral> zero(new IntLiteral(fContext, offset, 0));
1641 std::unique_ptr<IntLiteral> one(new IntLiteral(fContext, offset, 1));
1642 return std::unique_ptr<Expression>(
1643 new TernaryExpression(offset, std::move(args[0]),
1644 this->coerce(std::move(one), type),
1645 this->coerce(std::move(zero),
1646 type)));
1647 }
1648 if (!args[0]->fType.isNumber()) {
1649 fErrors.error(offset, "invalid argument to '" + type.description() +
1650 "' constructor (expected a number or bool, but found '" +
1651 args[0]->fType.description() + "')");
1652 return nullptr;
1653 }
1654 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
1655 }
1656
component_count(const Type & type)1657 int component_count(const Type& type) {
1658 switch (type.kind()) {
1659 case Type::kVector_Kind:
1660 return type.columns();
1661 case Type::kMatrix_Kind:
1662 return type.columns() * type.rows();
1663 default:
1664 return 1;
1665 }
1666 }
1667
convertCompoundConstructor(int offset,const Type & type,std::vector<std::unique_ptr<Expression>> args)1668 std::unique_ptr<Expression> IRGenerator::convertCompoundConstructor(
1669 int offset,
1670 const Type& type,
1671 std::vector<std::unique_ptr<Expression>> args) {
1672 ASSERT(type.kind() == Type::kVector_Kind || type.kind() == Type::kMatrix_Kind);
1673 if (type.kind() == Type::kMatrix_Kind && args.size() == 1 &&
1674 args[0]->fType.kind() == Type::kMatrix_Kind) {
1675 // matrix from matrix is always legal
1676 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
1677 }
1678 int actual = 0;
1679 int expected = type.rows() * type.columns();
1680 if (args.size() != 1 || expected != component_count(args[0]->fType) ||
1681 type.componentType().isNumber() != args[0]->fType.componentType().isNumber()) {
1682 for (size_t i = 0; i < args.size(); i++) {
1683 if (args[i]->fType.kind() == Type::kVector_Kind) {
1684 if (type.componentType().isNumber() !=
1685 args[i]->fType.componentType().isNumber()) {
1686 fErrors.error(offset, "'" + args[i]->fType.description() + "' is not a valid "
1687 "parameter to '" + type.description() +
1688 "' constructor");
1689 return nullptr;
1690 }
1691 actual += args[i]->fType.columns();
1692 } else if (args[i]->fType.kind() == Type::kScalar_Kind) {
1693 actual += 1;
1694 if (type.kind() != Type::kScalar_Kind) {
1695 args[i] = this->coerce(std::move(args[i]), type.componentType());
1696 if (!args[i]) {
1697 return nullptr;
1698 }
1699 }
1700 } else {
1701 fErrors.error(offset, "'" + args[i]->fType.description() + "' is not a valid "
1702 "parameter to '" + type.description() + "' constructor");
1703 return nullptr;
1704 }
1705 }
1706 if (actual != 1 && actual != expected) {
1707 fErrors.error(offset, "invalid arguments to '" + type.description() +
1708 "' constructor (expected " + to_string(expected) +
1709 " scalars, but found " + to_string(actual) + ")");
1710 return nullptr;
1711 }
1712 }
1713 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
1714 }
1715
convertConstructor(int offset,const Type & type,std::vector<std::unique_ptr<Expression>> args)1716 std::unique_ptr<Expression> IRGenerator::convertConstructor(
1717 int offset,
1718 const Type& type,
1719 std::vector<std::unique_ptr<Expression>> args) {
1720 // FIXME: add support for structs
1721 Type::Kind kind = type.kind();
1722 if (args.size() == 1 && args[0]->fType == type) {
1723 // argument is already the right type, just return it
1724 return std::move(args[0]);
1725 }
1726 if (type.isNumber()) {
1727 return this->convertNumberConstructor(offset, type, std::move(args));
1728 } else if (kind == Type::kArray_Kind) {
1729 const Type& base = type.componentType();
1730 for (size_t i = 0; i < args.size(); i++) {
1731 args[i] = this->coerce(std::move(args[i]), base);
1732 if (!args[i]) {
1733 return nullptr;
1734 }
1735 }
1736 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
1737 } else if (kind == Type::kVector_Kind || kind == Type::kMatrix_Kind) {
1738 return this->convertCompoundConstructor(offset, type, std::move(args));
1739 } else {
1740 fErrors.error(offset, "cannot construct '" + type.description() + "'");
1741 return nullptr;
1742 }
1743 }
1744
convertPrefixExpression(const ASTPrefixExpression & expression)1745 std::unique_ptr<Expression> IRGenerator::convertPrefixExpression(
1746 const ASTPrefixExpression& expression) {
1747 std::unique_ptr<Expression> base = this->convertExpression(*expression.fOperand);
1748 if (!base) {
1749 return nullptr;
1750 }
1751 switch (expression.fOperator) {
1752 case Token::PLUS:
1753 if (!base->fType.isNumber() && base->fType.kind() != Type::kVector_Kind) {
1754 fErrors.error(expression.fOffset,
1755 "'+' cannot operate on '" + base->fType.description() + "'");
1756 return nullptr;
1757 }
1758 return base;
1759 case Token::MINUS:
1760 if (!base->fType.isNumber() && base->fType.kind() != Type::kVector_Kind) {
1761 fErrors.error(expression.fOffset,
1762 "'-' cannot operate on '" + base->fType.description() + "'");
1763 return nullptr;
1764 }
1765 if (base->fKind == Expression::kIntLiteral_Kind) {
1766 return std::unique_ptr<Expression>(new IntLiteral(fContext, base->fOffset,
1767 -((IntLiteral&) *base).fValue));
1768 }
1769 if (base->fKind == Expression::kFloatLiteral_Kind) {
1770 double value = -((FloatLiteral&) *base).fValue;
1771 return std::unique_ptr<Expression>(new FloatLiteral(fContext, base->fOffset,
1772 value));
1773 }
1774 return std::unique_ptr<Expression>(new PrefixExpression(Token::MINUS, std::move(base)));
1775 case Token::PLUSPLUS:
1776 if (!base->fType.isNumber()) {
1777 fErrors.error(expression.fOffset,
1778 String("'") + Compiler::OperatorName(expression.fOperator) +
1779 "' cannot operate on '" + base->fType.description() + "'");
1780 return nullptr;
1781 }
1782 this->markWrittenTo(*base, true);
1783 break;
1784 case Token::MINUSMINUS:
1785 if (!base->fType.isNumber()) {
1786 fErrors.error(expression.fOffset,
1787 String("'") + Compiler::OperatorName(expression.fOperator) +
1788 "' cannot operate on '" + base->fType.description() + "'");
1789 return nullptr;
1790 }
1791 this->markWrittenTo(*base, true);
1792 break;
1793 case Token::LOGICALNOT:
1794 if (base->fType != *fContext.fBool_Type) {
1795 fErrors.error(expression.fOffset,
1796 String("'") + Compiler::OperatorName(expression.fOperator) +
1797 "' cannot operate on '" + base->fType.description() + "'");
1798 return nullptr;
1799 }
1800 if (base->fKind == Expression::kBoolLiteral_Kind) {
1801 return std::unique_ptr<Expression>(new BoolLiteral(fContext, base->fOffset,
1802 !((BoolLiteral&) *base).fValue));
1803 }
1804 break;
1805 case Token::BITWISENOT:
1806 if (base->fType != *fContext.fInt_Type) {
1807 fErrors.error(expression.fOffset,
1808 String("'") + Compiler::OperatorName(expression.fOperator) +
1809 "' cannot operate on '" + base->fType.description() + "'");
1810 return nullptr;
1811 }
1812 break;
1813 default:
1814 ABORT("unsupported prefix operator\n");
1815 }
1816 return std::unique_ptr<Expression>(new PrefixExpression(expression.fOperator,
1817 std::move(base)));
1818 }
1819
convertIndex(std::unique_ptr<Expression> base,const ASTExpression & index)1820 std::unique_ptr<Expression> IRGenerator::convertIndex(std::unique_ptr<Expression> base,
1821 const ASTExpression& index) {
1822 if (base->fKind == Expression::kTypeReference_Kind) {
1823 if (index.fKind == ASTExpression::kInt_Kind) {
1824 const Type& oldType = ((TypeReference&) *base).fValue;
1825 int64_t size = ((const ASTIntLiteral&) index).fValue;
1826 Type* newType = new Type(oldType.name() + "[" + to_string(size) + "]",
1827 Type::kArray_Kind, oldType, size);
1828 fSymbolTable->takeOwnership(newType);
1829 return std::unique_ptr<Expression>(new TypeReference(fContext, base->fOffset,
1830 *newType));
1831
1832 } else {
1833 fErrors.error(base->fOffset, "array size must be a constant");
1834 return nullptr;
1835 }
1836 }
1837 if (base->fType.kind() != Type::kArray_Kind && base->fType.kind() != Type::kMatrix_Kind &&
1838 base->fType.kind() != Type::kVector_Kind) {
1839 fErrors.error(base->fOffset, "expected array, but found '" + base->fType.description() +
1840 "'");
1841 return nullptr;
1842 }
1843 std::unique_ptr<Expression> converted = this->convertExpression(index);
1844 if (!converted) {
1845 return nullptr;
1846 }
1847 if (converted->fType != *fContext.fUInt_Type) {
1848 converted = this->coerce(std::move(converted), *fContext.fInt_Type);
1849 if (!converted) {
1850 return nullptr;
1851 }
1852 }
1853 return std::unique_ptr<Expression>(new IndexExpression(fContext, std::move(base),
1854 std::move(converted)));
1855 }
1856
convertField(std::unique_ptr<Expression> base,StringFragment field)1857 std::unique_ptr<Expression> IRGenerator::convertField(std::unique_ptr<Expression> base,
1858 StringFragment field) {
1859 auto fields = base->fType.fields();
1860 for (size_t i = 0; i < fields.size(); i++) {
1861 if (fields[i].fName == field) {
1862 return std::unique_ptr<Expression>(new FieldAccess(std::move(base), (int) i));
1863 }
1864 }
1865 fErrors.error(base->fOffset, "type '" + base->fType.description() + "' does not have a "
1866 "field named '" + field + "");
1867 return nullptr;
1868 }
1869
convertSwizzle(std::unique_ptr<Expression> base,StringFragment fields)1870 std::unique_ptr<Expression> IRGenerator::convertSwizzle(std::unique_ptr<Expression> base,
1871 StringFragment fields) {
1872 if (base->fType.kind() != Type::kVector_Kind) {
1873 fErrors.error(base->fOffset, "cannot swizzle type '" + base->fType.description() + "'");
1874 return nullptr;
1875 }
1876 std::vector<int> swizzleComponents;
1877 for (size_t i = 0; i < fields.fLength; i++) {
1878 switch (fields[i]) {
1879 case 'x': // fall through
1880 case 'r': // fall through
1881 case 's':
1882 swizzleComponents.push_back(0);
1883 break;
1884 case 'y': // fall through
1885 case 'g': // fall through
1886 case 't':
1887 if (base->fType.columns() >= 2) {
1888 swizzleComponents.push_back(1);
1889 break;
1890 }
1891 // fall through
1892 case 'z': // fall through
1893 case 'b': // fall through
1894 case 'p':
1895 if (base->fType.columns() >= 3) {
1896 swizzleComponents.push_back(2);
1897 break;
1898 }
1899 // fall through
1900 case 'w': // fall through
1901 case 'a': // fall through
1902 case 'q':
1903 if (base->fType.columns() >= 4) {
1904 swizzleComponents.push_back(3);
1905 break;
1906 }
1907 // fall through
1908 default:
1909 fErrors.error(base->fOffset, String::printf("invalid swizzle component '%c'",
1910 fields[i]));
1911 return nullptr;
1912 }
1913 }
1914 ASSERT(swizzleComponents.size() > 0);
1915 if (swizzleComponents.size() > 4) {
1916 fErrors.error(base->fOffset, "too many components in swizzle mask '" + fields + "'");
1917 return nullptr;
1918 }
1919 return std::unique_ptr<Expression>(new Swizzle(fContext, std::move(base), swizzleComponents));
1920 }
1921
getCap(int offset,String name)1922 std::unique_ptr<Expression> IRGenerator::getCap(int offset, String name) {
1923 auto found = fCapsMap.find(name);
1924 if (found == fCapsMap.end()) {
1925 fErrors.error(offset, "unknown capability flag '" + name + "'");
1926 return nullptr;
1927 }
1928 String fullName = "sk_Caps." + name;
1929 return std::unique_ptr<Expression>(new Setting(offset, fullName,
1930 found->second.literal(fContext, offset)));
1931 }
1932
getArg(int offset,String name)1933 std::unique_ptr<Expression> IRGenerator::getArg(int offset, String name) {
1934 auto found = fSettings->fArgs.find(name);
1935 if (found == fSettings->fArgs.end()) {
1936 fErrors.error(offset, "unknown argument '" + name + "'");
1937 return nullptr;
1938 }
1939 String fullName = "sk_Args." + name;
1940 return std::unique_ptr<Expression>(new Setting(offset,
1941 fullName,
1942 found->second.literal(fContext, offset)));
1943 }
1944
convertTypeField(int offset,const Type & type,StringFragment field)1945 std::unique_ptr<Expression> IRGenerator::convertTypeField(int offset, const Type& type,
1946 StringFragment field) {
1947 std::unique_ptr<Expression> result;
1948 for (const auto& e : *fProgramElements) {
1949 if (e->fKind == ProgramElement::kEnum_Kind && type.name() == ((Enum&) *e).fTypeName) {
1950 std::shared_ptr<SymbolTable> old = fSymbolTable;
1951 fSymbolTable = ((Enum&) *e).fSymbols;
1952 result = convertIdentifier(ASTIdentifier(offset, field));
1953 fSymbolTable = old;
1954 }
1955 }
1956 if (!result) {
1957 fErrors.error(offset, "type '" + type.fName + "' does not have a field named '" + field +
1958 "'");
1959 }
1960 return result;
1961 }
1962
convertSuffixExpression(const ASTSuffixExpression & expression)1963 std::unique_ptr<Expression> IRGenerator::convertSuffixExpression(
1964 const ASTSuffixExpression& expression) {
1965 std::unique_ptr<Expression> base = this->convertExpression(*expression.fBase);
1966 if (!base) {
1967 return nullptr;
1968 }
1969 switch (expression.fSuffix->fKind) {
1970 case ASTSuffix::kIndex_Kind: {
1971 const ASTExpression* expr = ((ASTIndexSuffix&) *expression.fSuffix).fExpression.get();
1972 if (expr) {
1973 return this->convertIndex(std::move(base), *expr);
1974 } else if (base->fKind == Expression::kTypeReference_Kind) {
1975 const Type& oldType = ((TypeReference&) *base).fValue;
1976 Type* newType = new Type(oldType.name() + "[]", Type::kArray_Kind, oldType,
1977 -1);
1978 fSymbolTable->takeOwnership(newType);
1979 return std::unique_ptr<Expression>(new TypeReference(fContext, base->fOffset,
1980 *newType));
1981 } else {
1982 fErrors.error(expression.fOffset, "'[]' must follow a type name");
1983 return nullptr;
1984 }
1985 }
1986 case ASTSuffix::kCall_Kind: {
1987 auto rawArguments = &((ASTCallSuffix&) *expression.fSuffix).fArguments;
1988 std::vector<std::unique_ptr<Expression>> arguments;
1989 for (size_t i = 0; i < rawArguments->size(); i++) {
1990 std::unique_ptr<Expression> converted =
1991 this->convertExpression(*(*rawArguments)[i]);
1992 if (!converted) {
1993 return nullptr;
1994 }
1995 arguments.push_back(std::move(converted));
1996 }
1997 return this->call(expression.fOffset, std::move(base), std::move(arguments));
1998 }
1999 case ASTSuffix::kField_Kind: {
2000 StringFragment field = ((ASTFieldSuffix&) *expression.fSuffix).fField;
2001 if (base->fType == *fContext.fSkCaps_Type) {
2002 return this->getCap(expression.fOffset, field);
2003 }
2004 if (base->fType == *fContext.fSkArgs_Type) {
2005 return this->getArg(expression.fOffset, field);
2006 }
2007 if (base->fKind == Expression::kTypeReference_Kind) {
2008 return this->convertTypeField(base->fOffset, ((TypeReference&) *base).fValue,
2009 field);
2010 }
2011 switch (base->fType.kind()) {
2012 case Type::kVector_Kind:
2013 return this->convertSwizzle(std::move(base), field);
2014 case Type::kStruct_Kind:
2015 return this->convertField(std::move(base), field);
2016 default:
2017 fErrors.error(base->fOffset, "cannot swizzle value of type '" +
2018 base->fType.description() + "'");
2019 return nullptr;
2020 }
2021 }
2022 case ASTSuffix::kPostIncrement_Kind:
2023 if (!base->fType.isNumber()) {
2024 fErrors.error(expression.fOffset,
2025 "'++' cannot operate on '" + base->fType.description() + "'");
2026 return nullptr;
2027 }
2028 this->markWrittenTo(*base, true);
2029 return std::unique_ptr<Expression>(new PostfixExpression(std::move(base),
2030 Token::PLUSPLUS));
2031 case ASTSuffix::kPostDecrement_Kind:
2032 if (!base->fType.isNumber()) {
2033 fErrors.error(expression.fOffset,
2034 "'--' cannot operate on '" + base->fType.description() + "'");
2035 return nullptr;
2036 }
2037 this->markWrittenTo(*base, true);
2038 return std::unique_ptr<Expression>(new PostfixExpression(std::move(base),
2039 Token::MINUSMINUS));
2040 default:
2041 ABORT("unsupported suffix operator");
2042 }
2043 }
2044
checkValid(const Expression & expr)2045 void IRGenerator::checkValid(const Expression& expr) {
2046 switch (expr.fKind) {
2047 case Expression::kFunctionReference_Kind:
2048 fErrors.error(expr.fOffset, "expected '(' to begin function call");
2049 break;
2050 case Expression::kTypeReference_Kind:
2051 fErrors.error(expr.fOffset, "expected '(' to begin constructor invocation");
2052 break;
2053 default:
2054 if (expr.fType == *fContext.fInvalid_Type) {
2055 fErrors.error(expr.fOffset, "invalid expression");
2056 }
2057 }
2058 }
2059
has_duplicates(const Swizzle & swizzle)2060 static bool has_duplicates(const Swizzle& swizzle) {
2061 int bits = 0;
2062 for (int idx : swizzle.fComponents) {
2063 ASSERT(idx >= 0 && idx <= 3);
2064 int bit = 1 << idx;
2065 if (bits & bit) {
2066 return true;
2067 }
2068 bits |= bit;
2069 }
2070 return false;
2071 }
2072
markWrittenTo(const Expression & expr,bool readWrite)2073 void IRGenerator::markWrittenTo(const Expression& expr, bool readWrite) {
2074 switch (expr.fKind) {
2075 case Expression::kVariableReference_Kind: {
2076 const Variable& var = ((VariableReference&) expr).fVariable;
2077 if (var.fModifiers.fFlags & (Modifiers::kConst_Flag | Modifiers::kUniform_Flag)) {
2078 fErrors.error(expr.fOffset,
2079 "cannot modify immutable variable '" + var.fName + "'");
2080 }
2081 ((VariableReference&) expr).setRefKind(readWrite ? VariableReference::kReadWrite_RefKind
2082 : VariableReference::kWrite_RefKind);
2083 break;
2084 }
2085 case Expression::kFieldAccess_Kind:
2086 this->markWrittenTo(*((FieldAccess&) expr).fBase, readWrite);
2087 break;
2088 case Expression::kSwizzle_Kind:
2089 if (has_duplicates((Swizzle&) expr)) {
2090 fErrors.error(expr.fOffset,
2091 "cannot write to the same swizzle field more than once");
2092 }
2093 this->markWrittenTo(*((Swizzle&) expr).fBase, readWrite);
2094 break;
2095 case Expression::kIndex_Kind:
2096 this->markWrittenTo(*((IndexExpression&) expr).fBase, readWrite);
2097 break;
2098 case Expression::kTernary_Kind: {
2099 TernaryExpression& t = (TernaryExpression&) expr;
2100 this->markWrittenTo(*t.fIfTrue, readWrite);
2101 this->markWrittenTo(*t.fIfFalse, readWrite);
2102 break;
2103 }
2104 default:
2105 fErrors.error(expr.fOffset, "cannot assign to '" + expr.description() + "'");
2106 break;
2107 }
2108 }
2109
convertProgram(Program::Kind kind,const char * text,size_t length,SymbolTable & types,std::vector<std::unique_ptr<ProgramElement>> * out)2110 void IRGenerator::convertProgram(Program::Kind kind,
2111 const char* text,
2112 size_t length,
2113 SymbolTable& types,
2114 std::vector<std::unique_ptr<ProgramElement>>* out) {
2115 fKind = kind;
2116 fProgramElements = out;
2117 Parser parser(text, length, types, fErrors);
2118 std::vector<std::unique_ptr<ASTDeclaration>> parsed = parser.file();
2119 if (fErrors.errorCount()) {
2120 return;
2121 }
2122 for (size_t i = 0; i < parsed.size(); i++) {
2123 ASTDeclaration& decl = *parsed[i];
2124 switch (decl.fKind) {
2125 case ASTDeclaration::kVar_Kind: {
2126 std::unique_ptr<VarDeclarations> s = this->convertVarDeclarations(
2127 (ASTVarDeclarations&) decl,
2128 Variable::kGlobal_Storage);
2129 if (s) {
2130 fProgramElements->push_back(std::move(s));
2131 }
2132 break;
2133 }
2134 case ASTDeclaration::kEnum_Kind: {
2135 this->convertEnum((ASTEnum&) decl);
2136 break;
2137 }
2138 case ASTDeclaration::kFunction_Kind: {
2139 this->convertFunction((ASTFunction&) decl);
2140 break;
2141 }
2142 case ASTDeclaration::kModifiers_Kind: {
2143 std::unique_ptr<ModifiersDeclaration> f = this->convertModifiersDeclaration(
2144 (ASTModifiersDeclaration&) decl);
2145 if (f) {
2146 fProgramElements->push_back(std::move(f));
2147 }
2148 break;
2149 }
2150 case ASTDeclaration::kInterfaceBlock_Kind: {
2151 std::unique_ptr<InterfaceBlock> i = this->convertInterfaceBlock(
2152 (ASTInterfaceBlock&) decl);
2153 if (i) {
2154 fProgramElements->push_back(std::move(i));
2155 }
2156 break;
2157 }
2158 case ASTDeclaration::kExtension_Kind: {
2159 std::unique_ptr<Extension> e = this->convertExtension((ASTExtension&) decl);
2160 if (e) {
2161 fProgramElements->push_back(std::move(e));
2162 }
2163 break;
2164 }
2165 case ASTDeclaration::kSection_Kind: {
2166 std::unique_ptr<Section> s = this->convertSection((ASTSection&) decl);
2167 if (s) {
2168 fProgramElements->push_back(std::move(s));
2169 }
2170 break;
2171 }
2172 default:
2173 ABORT("unsupported declaration: %s\n", decl.description().c_str());
2174 }
2175 }
2176 }
2177
2178
2179 }
2180