blob: 2e280d870225a2efd89cf49f067c9aec42457b9e [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 */
Ethan Nicholas11d53972016-11-28 11:23:23 -05007
ethannicholasb3058bd2016-07-01 08:22:01 -07008#include "SkSLIRGenerator.h"
9
10#include "limits.h"
Ethan Nicholasaf197692017-02-27 13:26:45 -050011#include <unordered_set>
ethannicholasb3058bd2016-07-01 08:22:01 -070012
Ethan Nicholas941e7e22016-12-12 15:33:30 -050013#include "SkSLCompiler.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070014#include "ast/SkSLASTBoolLiteral.h"
15#include "ast/SkSLASTFieldSuffix.h"
16#include "ast/SkSLASTFloatLiteral.h"
17#include "ast/SkSLASTIndexSuffix.h"
18#include "ast/SkSLASTIntLiteral.h"
19#include "ir/SkSLBinaryExpression.h"
20#include "ir/SkSLBoolLiteral.h"
21#include "ir/SkSLBreakStatement.h"
22#include "ir/SkSLConstructor.h"
23#include "ir/SkSLContinueStatement.h"
24#include "ir/SkSLDiscardStatement.h"
25#include "ir/SkSLDoStatement.h"
26#include "ir/SkSLExpressionStatement.h"
27#include "ir/SkSLField.h"
28#include "ir/SkSLFieldAccess.h"
29#include "ir/SkSLFloatLiteral.h"
30#include "ir/SkSLForStatement.h"
31#include "ir/SkSLFunctionCall.h"
32#include "ir/SkSLFunctionDeclaration.h"
33#include "ir/SkSLFunctionDefinition.h"
34#include "ir/SkSLFunctionReference.h"
35#include "ir/SkSLIfStatement.h"
36#include "ir/SkSLIndexExpression.h"
37#include "ir/SkSLInterfaceBlock.h"
38#include "ir/SkSLIntLiteral.h"
39#include "ir/SkSLLayout.h"
40#include "ir/SkSLPostfixExpression.h"
41#include "ir/SkSLPrefixExpression.h"
42#include "ir/SkSLReturnStatement.h"
Ethan Nicholasaf197692017-02-27 13:26:45 -050043#include "ir/SkSLSwitchCase.h"
44#include "ir/SkSLSwitchStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070045#include "ir/SkSLSwizzle.h"
46#include "ir/SkSLTernaryExpression.h"
47#include "ir/SkSLUnresolvedFunction.h"
48#include "ir/SkSLVariable.h"
ethannicholas22f939e2016-10-13 13:25:34 -070049#include "ir/SkSLVarDeclarations.h"
50#include "ir/SkSLVarDeclarationsStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070051#include "ir/SkSLVariableReference.h"
52#include "ir/SkSLWhileStatement.h"
53
54namespace SkSL {
55
56class AutoSymbolTable {
57public:
Ethan Nicholas11d53972016-11-28 11:23:23 -050058 AutoSymbolTable(IRGenerator* ir)
ethannicholasb3058bd2016-07-01 08:22:01 -070059 : fIR(ir)
60 , fPrevious(fIR->fSymbolTable) {
61 fIR->pushSymbolTable();
62 }
63
64 ~AutoSymbolTable() {
65 fIR->popSymbolTable();
66 ASSERT(fPrevious == fIR->fSymbolTable);
67 }
68
69 IRGenerator* fIR;
70 std::shared_ptr<SymbolTable> fPrevious;
71};
72
ethannicholas22f939e2016-10-13 13:25:34 -070073class AutoLoopLevel {
74public:
Ethan Nicholas11d53972016-11-28 11:23:23 -050075 AutoLoopLevel(IRGenerator* ir)
ethannicholas22f939e2016-10-13 13:25:34 -070076 : fIR(ir) {
77 fIR->fLoopLevel++;
78 }
79
80 ~AutoLoopLevel() {
81 fIR->fLoopLevel--;
82 }
83
84 IRGenerator* fIR;
85};
86
Ethan Nicholasaf197692017-02-27 13:26:45 -050087class AutoSwitchLevel {
88public:
89 AutoSwitchLevel(IRGenerator* ir)
90 : fIR(ir) {
91 fIR->fSwitchLevel++;
92 }
93
94 ~AutoSwitchLevel() {
95 fIR->fSwitchLevel--;
96 }
97
98 IRGenerator* fIR;
99};
100
Ethan Nicholas11d53972016-11-28 11:23:23 -0500101IRGenerator::IRGenerator(const Context* context, std::shared_ptr<SymbolTable> symbolTable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700102 ErrorReporter& errorReporter)
ethannicholasd598f792016-07-25 10:08:54 -0700103: fContext(*context)
104, fCurrentFunction(nullptr)
105, fSymbolTable(std::move(symbolTable))
ethannicholas22f939e2016-10-13 13:25:34 -0700106, fLoopLevel(0)
Ethan Nicholasaf197692017-02-27 13:26:45 -0500107, fSwitchLevel(0)
ethannicholasd598f792016-07-25 10:08:54 -0700108, fErrors(errorReporter) {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700109
110void IRGenerator::pushSymbolTable() {
Ethan Nicholas8feeff92017-03-30 14:11:58 -0400111 fSymbolTable.reset(new SymbolTable(std::move(fSymbolTable), &fErrors));
ethannicholasb3058bd2016-07-01 08:22:01 -0700112}
113
114void IRGenerator::popSymbolTable() {
115 fSymbolTable = fSymbolTable->fParent;
116}
117
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400118static void fill_caps(const SKSL_CAPS_CLASS& caps, std::unordered_map<String, CapValue>* capsMap) {
119#define CAP(name) capsMap->insert(std::make_pair(String(#name), CapValue(caps.name())));
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500120 CAP(fbFetchSupport);
121 CAP(fbFetchNeedsCustomOutput);
122 CAP(bindlessTextureSupport);
123 CAP(dropsTileOnZeroDivide);
124 CAP(flatInterpolationSupport);
125 CAP(noperspectiveInterpolationSupport);
126 CAP(multisampleInterpolationSupport);
127 CAP(sampleVariablesSupport);
128 CAP(sampleMaskOverrideCoverageSupport);
129 CAP(externalTextureSupport);
130 CAP(texelFetchSupport);
131 CAP(imageLoadStoreSupport);
132 CAP(mustEnableAdvBlendEqs);
133 CAP(mustEnableSpecificAdvBlendEqs);
134 CAP(mustDeclareFragmentShaderOutput);
135 CAP(canUseAnyFunctionInShader);
136#undef CAP
137}
138
139void IRGenerator::start(const Program::Settings* settings) {
140 fSettings = settings;
141 fCapsMap.clear();
142 if (settings->fCaps) {
143 fill_caps(*settings->fCaps, &fCapsMap);
144 }
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500145 this->pushSymbolTable();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500146 fInputs.reset();
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500147}
148
149void IRGenerator::finish() {
150 this->popSymbolTable();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500151 fSettings = nullptr;
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500152}
153
ethannicholasb3058bd2016-07-01 08:22:01 -0700154std::unique_ptr<Extension> IRGenerator::convertExtension(const ASTExtension& extension) {
155 return std::unique_ptr<Extension>(new Extension(extension.fPosition, extension.fName));
156}
157
158std::unique_ptr<Statement> IRGenerator::convertStatement(const ASTStatement& statement) {
159 switch (statement.fKind) {
160 case ASTStatement::kBlock_Kind:
161 return this->convertBlock((ASTBlock&) statement);
162 case ASTStatement::kVarDeclaration_Kind:
163 return this->convertVarDeclarationStatement((ASTVarDeclarationStatement&) statement);
164 case ASTStatement::kExpression_Kind:
165 return this->convertExpressionStatement((ASTExpressionStatement&) statement);
166 case ASTStatement::kIf_Kind:
167 return this->convertIf((ASTIfStatement&) statement);
168 case ASTStatement::kFor_Kind:
169 return this->convertFor((ASTForStatement&) statement);
170 case ASTStatement::kWhile_Kind:
171 return this->convertWhile((ASTWhileStatement&) statement);
172 case ASTStatement::kDo_Kind:
173 return this->convertDo((ASTDoStatement&) statement);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500174 case ASTStatement::kSwitch_Kind:
175 return this->convertSwitch((ASTSwitchStatement&) statement);
ethannicholasb3058bd2016-07-01 08:22:01 -0700176 case ASTStatement::kReturn_Kind:
177 return this->convertReturn((ASTReturnStatement&) statement);
178 case ASTStatement::kBreak_Kind:
179 return this->convertBreak((ASTBreakStatement&) statement);
180 case ASTStatement::kContinue_Kind:
181 return this->convertContinue((ASTContinueStatement&) statement);
182 case ASTStatement::kDiscard_Kind:
183 return this->convertDiscard((ASTDiscardStatement&) statement);
184 default:
185 ABORT("unsupported statement type: %d\n", statement.fKind);
186 }
187}
188
189std::unique_ptr<Block> IRGenerator::convertBlock(const ASTBlock& block) {
190 AutoSymbolTable table(this);
191 std::vector<std::unique_ptr<Statement>> statements;
192 for (size_t i = 0; i < block.fStatements.size(); i++) {
193 std::unique_ptr<Statement> statement = this->convertStatement(*block.fStatements[i]);
194 if (!statement) {
195 return nullptr;
196 }
197 statements.push_back(std::move(statement));
198 }
ethannicholasd598f792016-07-25 10:08:54 -0700199 return std::unique_ptr<Block>(new Block(block.fPosition, std::move(statements), fSymbolTable));
ethannicholasb3058bd2016-07-01 08:22:01 -0700200}
201
202std::unique_ptr<Statement> IRGenerator::convertVarDeclarationStatement(
203 const ASTVarDeclarationStatement& s) {
ethannicholas14fe8cc2016-09-07 13:37:16 -0700204 auto decl = this->convertVarDeclarations(*s.fDeclarations, Variable::kLocal_Storage);
ethannicholasb3058bd2016-07-01 08:22:01 -0700205 if (!decl) {
206 return nullptr;
207 }
ethannicholas14fe8cc2016-09-07 13:37:16 -0700208 return std::unique_ptr<Statement>(new VarDeclarationsStatement(std::move(decl)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700209}
210
ethannicholas14fe8cc2016-09-07 13:37:16 -0700211std::unique_ptr<VarDeclarations> IRGenerator::convertVarDeclarations(const ASTVarDeclarations& decl,
212 Variable::Storage storage) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400213 std::vector<std::unique_ptr<VarDeclaration>> variables;
ethannicholasd598f792016-07-25 10:08:54 -0700214 const Type* baseType = this->convertType(*decl.fType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700215 if (!baseType) {
216 return nullptr;
217 }
ethannicholas14fe8cc2016-09-07 13:37:16 -0700218 for (const auto& varDecl : decl.fVars) {
ethannicholasd598f792016-07-25 10:08:54 -0700219 const Type* type = baseType;
ethannicholas14fe8cc2016-09-07 13:37:16 -0700220 std::vector<std::unique_ptr<Expression>> sizes;
221 for (const auto& rawSize : varDecl.fSizes) {
222 if (rawSize) {
223 auto size = this->coerce(this->convertExpression(*rawSize), *fContext.fInt_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700224 if (!size) {
225 return nullptr;
226 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400227 String name = type->fName;
Ethan Nicholas50afc172017-02-16 14:49:57 -0500228 int64_t count;
ethannicholasb3058bd2016-07-01 08:22:01 -0700229 if (size->fKind == Expression::kIntLiteral_Kind) {
230 count = ((IntLiteral&) *size).fValue;
231 if (count <= 0) {
232 fErrors.error(size->fPosition, "array size must be positive");
233 }
234 name += "[" + to_string(count) + "]";
235 } else {
236 count = -1;
237 name += "[]";
238 }
ethannicholasd598f792016-07-25 10:08:54 -0700239 type = new Type(name, Type::kArray_Kind, *type, (int) count);
240 fSymbolTable->takeOwnership((Type*) type);
ethannicholas14fe8cc2016-09-07 13:37:16 -0700241 sizes.push_back(std::move(size));
ethannicholasb3058bd2016-07-01 08:22:01 -0700242 } else {
ethannicholasd598f792016-07-25 10:08:54 -0700243 type = new Type(type->fName + "[]", Type::kArray_Kind, *type, -1);
244 fSymbolTable->takeOwnership((Type*) type);
ethannicholas14fe8cc2016-09-07 13:37:16 -0700245 sizes.push_back(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700246 }
247 }
Ethan Nicholas11d53972016-11-28 11:23:23 -0500248 auto var = std::unique_ptr<Variable>(new Variable(decl.fPosition, decl.fModifiers,
249 varDecl.fName, *type, storage));
ethannicholasb3058bd2016-07-01 08:22:01 -0700250 std::unique_ptr<Expression> value;
ethannicholas14fe8cc2016-09-07 13:37:16 -0700251 if (varDecl.fValue) {
252 value = this->convertExpression(*varDecl.fValue);
ethannicholasb3058bd2016-07-01 08:22:01 -0700253 if (!value) {
254 return nullptr;
255 }
ethannicholasd598f792016-07-25 10:08:54 -0700256 value = this->coerce(std::move(value), *type);
Ethan Nicholascb670962017-04-20 19:31:52 -0400257 var->fWriteCount = 1;
ethannicholasb3058bd2016-07-01 08:22:01 -0700258 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400259 if (storage == Variable::kGlobal_Storage && varDecl.fName == String("sk_FragColor") &&
ethannicholasea4567c2016-10-17 11:24:37 -0700260 (*fSymbolTable)[varDecl.fName]) {
ethannicholas5961bc92016-10-12 06:39:56 -0700261 // already defined, ignore
ethannicholasea4567c2016-10-17 11:24:37 -0700262 } else if (storage == Variable::kGlobal_Storage && (*fSymbolTable)[varDecl.fName] &&
263 (*fSymbolTable)[varDecl.fName]->fKind == Symbol::kVariable_Kind &&
ethannicholas5961bc92016-10-12 06:39:56 -0700264 ((Variable*) (*fSymbolTable)[varDecl.fName])->fModifiers.fLayout.fBuiltin >= 0) {
ethannicholasf789b382016-08-03 12:43:36 -0700265 // already defined, just update the modifiers
ethannicholas14fe8cc2016-09-07 13:37:16 -0700266 Variable* old = (Variable*) (*fSymbolTable)[varDecl.fName];
ethannicholasf789b382016-08-03 12:43:36 -0700267 old->fModifiers = var->fModifiers;
268 } else {
Ethan Nicholascb670962017-04-20 19:31:52 -0400269 variables.emplace_back(new VarDeclaration(var.get(), std::move(sizes),
270 std::move(value)));
ethannicholas14fe8cc2016-09-07 13:37:16 -0700271 fSymbolTable->add(varDecl.fName, std::move(var));
ethannicholasf789b382016-08-03 12:43:36 -0700272 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700273 }
Ethan Nicholas11d53972016-11-28 11:23:23 -0500274 return std::unique_ptr<VarDeclarations>(new VarDeclarations(decl.fPosition,
ethannicholas14fe8cc2016-09-07 13:37:16 -0700275 baseType,
276 std::move(variables)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700277}
278
ethannicholas5961bc92016-10-12 06:39:56 -0700279std::unique_ptr<ModifiersDeclaration> IRGenerator::convertModifiersDeclaration(
280 const ASTModifiersDeclaration& m) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500281 return std::unique_ptr<ModifiersDeclaration>(new ModifiersDeclaration(m.fModifiers));
ethannicholas5961bc92016-10-12 06:39:56 -0700282}
283
ethannicholasb3058bd2016-07-01 08:22:01 -0700284std::unique_ptr<Statement> IRGenerator::convertIf(const ASTIfStatement& s) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500285 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*s.fTest),
ethannicholasd598f792016-07-25 10:08:54 -0700286 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700287 if (!test) {
288 return nullptr;
289 }
290 std::unique_ptr<Statement> ifTrue = this->convertStatement(*s.fIfTrue);
291 if (!ifTrue) {
292 return nullptr;
293 }
294 std::unique_ptr<Statement> ifFalse;
295 if (s.fIfFalse) {
296 ifFalse = this->convertStatement(*s.fIfFalse);
297 if (!ifFalse) {
298 return nullptr;
299 }
300 }
ethannicholas08a92112016-11-09 13:26:45 -0800301 if (test->fKind == Expression::kBoolLiteral_Kind) {
302 // static boolean value, fold down to a single branch
303 if (((BoolLiteral&) *test).fValue) {
304 return ifTrue;
305 } else if (s.fIfFalse) {
306 return ifFalse;
307 } else {
308 // False & no else clause. Not an error, so don't return null!
309 std::vector<std::unique_ptr<Statement>> empty;
Ethan Nicholas11d53972016-11-28 11:23:23 -0500310 return std::unique_ptr<Statement>(new Block(s.fPosition, std::move(empty),
ethannicholas08a92112016-11-09 13:26:45 -0800311 fSymbolTable));
312 }
313 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400314 return std::unique_ptr<Statement>(new IfStatement(s.fPosition, s.fIsStatic, std::move(test),
ethannicholasb3058bd2016-07-01 08:22:01 -0700315 std::move(ifTrue), std::move(ifFalse)));
316}
317
318std::unique_ptr<Statement> IRGenerator::convertFor(const ASTForStatement& f) {
ethannicholas22f939e2016-10-13 13:25:34 -0700319 AutoLoopLevel level(this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700320 AutoSymbolTable table(this);
ethannicholas22f939e2016-10-13 13:25:34 -0700321 std::unique_ptr<Statement> initializer;
322 if (f.fInitializer) {
323 initializer = this->convertStatement(*f.fInitializer);
324 if (!initializer) {
325 return nullptr;
326 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700327 }
ethannicholas22f939e2016-10-13 13:25:34 -0700328 std::unique_ptr<Expression> test;
329 if (f.fTest) {
330 test = this->coerce(this->convertExpression(*f.fTest), *fContext.fBool_Type);
331 if (!test) {
332 return nullptr;
333 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700334 }
ethannicholas22f939e2016-10-13 13:25:34 -0700335 std::unique_ptr<Expression> next;
336 if (f.fNext) {
337 next = this->convertExpression(*f.fNext);
338 if (!next) {
339 return nullptr;
340 }
341 this->checkValid(*next);
ethannicholasb3058bd2016-07-01 08:22:01 -0700342 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700343 std::unique_ptr<Statement> statement = this->convertStatement(*f.fStatement);
344 if (!statement) {
345 return nullptr;
346 }
Ethan Nicholas11d53972016-11-28 11:23:23 -0500347 return std::unique_ptr<Statement>(new ForStatement(f.fPosition, std::move(initializer),
ethannicholasb3058bd2016-07-01 08:22:01 -0700348 std::move(test), std::move(next),
ethannicholasd598f792016-07-25 10:08:54 -0700349 std::move(statement), fSymbolTable));
ethannicholasb3058bd2016-07-01 08:22:01 -0700350}
351
352std::unique_ptr<Statement> IRGenerator::convertWhile(const ASTWhileStatement& w) {
ethannicholas22f939e2016-10-13 13:25:34 -0700353 AutoLoopLevel level(this);
Ethan Nicholas11d53972016-11-28 11:23:23 -0500354 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*w.fTest),
ethannicholasd598f792016-07-25 10:08:54 -0700355 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700356 if (!test) {
357 return nullptr;
358 }
359 std::unique_ptr<Statement> statement = this->convertStatement(*w.fStatement);
360 if (!statement) {
361 return nullptr;
362 }
363 return std::unique_ptr<Statement>(new WhileStatement(w.fPosition, std::move(test),
364 std::move(statement)));
365}
366
367std::unique_ptr<Statement> IRGenerator::convertDo(const ASTDoStatement& d) {
ethannicholas22f939e2016-10-13 13:25:34 -0700368 AutoLoopLevel level(this);
ethannicholasd598f792016-07-25 10:08:54 -0700369 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*d.fTest),
370 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700371 if (!test) {
372 return nullptr;
373 }
374 std::unique_ptr<Statement> statement = this->convertStatement(*d.fStatement);
375 if (!statement) {
376 return nullptr;
377 }
Ethan Nicholas11d53972016-11-28 11:23:23 -0500378 return std::unique_ptr<Statement>(new DoStatement(d.fPosition, std::move(statement),
ethannicholasb3058bd2016-07-01 08:22:01 -0700379 std::move(test)));
380}
381
Ethan Nicholasaf197692017-02-27 13:26:45 -0500382std::unique_ptr<Statement> IRGenerator::convertSwitch(const ASTSwitchStatement& s) {
383 AutoSwitchLevel level(this);
384 std::unique_ptr<Expression> value = this->convertExpression(*s.fValue);
385 if (!value) {
386 return nullptr;
387 }
388 if (value->fType != *fContext.fUInt_Type) {
389 value = this->coerce(std::move(value), *fContext.fInt_Type);
390 if (!value) {
391 return nullptr;
392 }
393 }
394 AutoSymbolTable table(this);
395 std::unordered_set<int> caseValues;
396 std::vector<std::unique_ptr<SwitchCase>> cases;
397 for (const auto& c : s.fCases) {
398 std::unique_ptr<Expression> caseValue;
399 if (c->fValue) {
400 caseValue = this->convertExpression(*c->fValue);
401 if (!caseValue) {
402 return nullptr;
403 }
404 if (caseValue->fType != *fContext.fUInt_Type) {
405 caseValue = this->coerce(std::move(caseValue), *fContext.fInt_Type);
406 if (!caseValue) {
407 return nullptr;
408 }
409 }
410 if (!caseValue->isConstant()) {
411 fErrors.error(caseValue->fPosition, "case value must be a constant");
412 return nullptr;
413 }
414 ASSERT(caseValue->fKind == Expression::kIntLiteral_Kind);
415 int64_t v = ((IntLiteral&) *caseValue).fValue;
416 if (caseValues.find(v) != caseValues.end()) {
417 fErrors.error(caseValue->fPosition, "duplicate case value");
418 }
419 caseValues.insert(v);
420 }
421 std::vector<std::unique_ptr<Statement>> statements;
422 for (const auto& s : c->fStatements) {
423 std::unique_ptr<Statement> converted = this->convertStatement(*s);
424 if (!converted) {
425 return nullptr;
426 }
427 statements.push_back(std::move(converted));
428 }
429 cases.emplace_back(new SwitchCase(c->fPosition, std::move(caseValue),
430 std::move(statements)));
431 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400432 return std::unique_ptr<Statement>(new SwitchStatement(s.fPosition, s.fIsStatic,
433 std::move(value), std::move(cases)));
Ethan Nicholasaf197692017-02-27 13:26:45 -0500434}
435
ethannicholasb3058bd2016-07-01 08:22:01 -0700436std::unique_ptr<Statement> IRGenerator::convertExpressionStatement(
437 const ASTExpressionStatement& s) {
438 std::unique_ptr<Expression> e = this->convertExpression(*s.fExpression);
439 if (!e) {
440 return nullptr;
441 }
442 this->checkValid(*e);
443 return std::unique_ptr<Statement>(new ExpressionStatement(std::move(e)));
444}
445
446std::unique_ptr<Statement> IRGenerator::convertReturn(const ASTReturnStatement& r) {
447 ASSERT(fCurrentFunction);
448 if (r.fExpression) {
449 std::unique_ptr<Expression> result = this->convertExpression(*r.fExpression);
450 if (!result) {
451 return nullptr;
452 }
ethannicholasd598f792016-07-25 10:08:54 -0700453 if (fCurrentFunction->fReturnType == *fContext.fVoid_Type) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700454 fErrors.error(result->fPosition, "may not return a value from a void function");
455 } else {
456 result = this->coerce(std::move(result), fCurrentFunction->fReturnType);
457 if (!result) {
458 return nullptr;
459 }
460 }
461 return std::unique_ptr<Statement>(new ReturnStatement(std::move(result)));
462 } else {
ethannicholasd598f792016-07-25 10:08:54 -0700463 if (fCurrentFunction->fReturnType != *fContext.fVoid_Type) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700464 fErrors.error(r.fPosition, "expected function to return '" +
ethannicholasd598f792016-07-25 10:08:54 -0700465 fCurrentFunction->fReturnType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -0700466 }
467 return std::unique_ptr<Statement>(new ReturnStatement(r.fPosition));
468 }
469}
470
471std::unique_ptr<Statement> IRGenerator::convertBreak(const ASTBreakStatement& b) {
Ethan Nicholasaf197692017-02-27 13:26:45 -0500472 if (fLoopLevel > 0 || fSwitchLevel > 0) {
ethannicholas22f939e2016-10-13 13:25:34 -0700473 return std::unique_ptr<Statement>(new BreakStatement(b.fPosition));
474 } else {
Ethan Nicholasaf197692017-02-27 13:26:45 -0500475 fErrors.error(b.fPosition, "break statement must be inside a loop or switch");
ethannicholas22f939e2016-10-13 13:25:34 -0700476 return nullptr;
477 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700478}
479
480std::unique_ptr<Statement> IRGenerator::convertContinue(const ASTContinueStatement& c) {
ethannicholas22f939e2016-10-13 13:25:34 -0700481 if (fLoopLevel > 0) {
482 return std::unique_ptr<Statement>(new ContinueStatement(c.fPosition));
483 } else {
484 fErrors.error(c.fPosition, "continue statement must be inside a loop");
485 return nullptr;
486 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700487}
488
489std::unique_ptr<Statement> IRGenerator::convertDiscard(const ASTDiscardStatement& d) {
490 return std::unique_ptr<Statement>(new DiscardStatement(d.fPosition));
491}
492
ethannicholasb3058bd2016-07-01 08:22:01 -0700493std::unique_ptr<FunctionDefinition> IRGenerator::convertFunction(const ASTFunction& f) {
ethannicholasd598f792016-07-25 10:08:54 -0700494 const Type* returnType = this->convertType(*f.fReturnType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700495 if (!returnType) {
496 return nullptr;
497 }
ethannicholasd598f792016-07-25 10:08:54 -0700498 std::vector<const Variable*> parameters;
ethannicholasb3058bd2016-07-01 08:22:01 -0700499 for (const auto& param : f.fParameters) {
ethannicholasd598f792016-07-25 10:08:54 -0700500 const Type* type = this->convertType(*param->fType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700501 if (!type) {
502 return nullptr;
503 }
504 for (int j = (int) param->fSizes.size() - 1; j >= 0; j--) {
505 int size = param->fSizes[j];
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400506 String name = type->name() + "[" + to_string(size) + "]";
ethannicholasd598f792016-07-25 10:08:54 -0700507 Type* newType = new Type(std::move(name), Type::kArray_Kind, *type, size);
508 fSymbolTable->takeOwnership(newType);
509 type = newType;
ethannicholasb3058bd2016-07-01 08:22:01 -0700510 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400511 String name = param->fName;
ethannicholasb3058bd2016-07-01 08:22:01 -0700512 Position pos = param->fPosition;
Ethan Nicholas11d53972016-11-28 11:23:23 -0500513 Variable* var = new Variable(pos, param->fModifiers, std::move(name), *type,
ethannicholasd598f792016-07-25 10:08:54 -0700514 Variable::kParameter_Storage);
515 fSymbolTable->takeOwnership(var);
516 parameters.push_back(var);
ethannicholasb3058bd2016-07-01 08:22:01 -0700517 }
518
519 // find existing declaration
ethannicholasd598f792016-07-25 10:08:54 -0700520 const FunctionDeclaration* decl = nullptr;
521 auto entry = (*fSymbolTable)[f.fName];
ethannicholasb3058bd2016-07-01 08:22:01 -0700522 if (entry) {
ethannicholasd598f792016-07-25 10:08:54 -0700523 std::vector<const FunctionDeclaration*> functions;
ethannicholasb3058bd2016-07-01 08:22:01 -0700524 switch (entry->fKind) {
525 case Symbol::kUnresolvedFunction_Kind:
ethannicholasd598f792016-07-25 10:08:54 -0700526 functions = ((UnresolvedFunction*) entry)->fFunctions;
ethannicholasb3058bd2016-07-01 08:22:01 -0700527 break;
528 case Symbol::kFunctionDeclaration_Kind:
ethannicholasd598f792016-07-25 10:08:54 -0700529 functions.push_back((FunctionDeclaration*) entry);
ethannicholasb3058bd2016-07-01 08:22:01 -0700530 break;
531 default:
532 fErrors.error(f.fPosition, "symbol '" + f.fName + "' was already defined");
533 return nullptr;
534 }
535 for (const auto& other : functions) {
536 ASSERT(other->fName == f.fName);
537 if (parameters.size() == other->fParameters.size()) {
538 bool match = true;
539 for (size_t i = 0; i < parameters.size(); i++) {
540 if (parameters[i]->fType != other->fParameters[i]->fType) {
541 match = false;
542 break;
543 }
544 }
545 if (match) {
ethannicholasd598f792016-07-25 10:08:54 -0700546 if (*returnType != other->fReturnType) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400547 FunctionDeclaration newDecl(f.fPosition, f.fModifiers, f.fName, parameters,
548 *returnType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700549 fErrors.error(f.fPosition, "functions '" + newDecl.description() +
Ethan Nicholas11d53972016-11-28 11:23:23 -0500550 "' and '" + other->description() +
ethannicholasb3058bd2016-07-01 08:22:01 -0700551 "' differ only in return type");
552 return nullptr;
553 }
554 decl = other;
555 for (size_t i = 0; i < parameters.size(); i++) {
556 if (parameters[i]->fModifiers != other->fParameters[i]->fModifiers) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500557 fErrors.error(f.fPosition, "modifiers on parameter " +
558 to_string((uint64_t) i + 1) +
ethannicholas5961bc92016-10-12 06:39:56 -0700559 " differ between declaration and "
560 "definition");
ethannicholasb3058bd2016-07-01 08:22:01 -0700561 return nullptr;
562 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700563 }
564 if (other->fDefined) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500565 fErrors.error(f.fPosition, "duplicate definition of " +
ethannicholasb3058bd2016-07-01 08:22:01 -0700566 other->description());
567 }
568 break;
569 }
570 }
571 }
572 }
573 if (!decl) {
574 // couldn't find an existing declaration
ethannicholas471e8942016-10-28 09:02:46 -0700575 auto newDecl = std::unique_ptr<FunctionDeclaration>(new FunctionDeclaration(f.fPosition,
Ethan Nicholascb670962017-04-20 19:31:52 -0400576 f.fModifiers,
ethannicholas471e8942016-10-28 09:02:46 -0700577 f.fName,
578 parameters,
579 *returnType));
580 decl = newDecl.get();
581 fSymbolTable->add(decl->fName, std::move(newDecl));
ethannicholasb3058bd2016-07-01 08:22:01 -0700582 }
ethannicholasd598f792016-07-25 10:08:54 -0700583 if (f.fBody) {
584 ASSERT(!fCurrentFunction);
585 fCurrentFunction = decl;
586 decl->fDefined = true;
587 std::shared_ptr<SymbolTable> old = fSymbolTable;
588 AutoSymbolTable table(this);
589 for (size_t i = 0; i < parameters.size(); i++) {
590 fSymbolTable->addWithoutOwnership(parameters[i]->fName, decl->fParameters[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -0700591 }
ethannicholasd598f792016-07-25 10:08:54 -0700592 std::unique_ptr<Block> body = this->convertBlock(*f.fBody);
593 fCurrentFunction = nullptr;
594 if (!body) {
595 return nullptr;
596 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400597 // conservatively assume all user-defined functions have side effects
598 ((Modifiers&) decl->fModifiers).fFlags |= Modifiers::kHasSideEffects_Flag;
Ethan Nicholas11d53972016-11-28 11:23:23 -0500599 return std::unique_ptr<FunctionDefinition>(new FunctionDefinition(f.fPosition, *decl,
ethannicholasd598f792016-07-25 10:08:54 -0700600 std::move(body)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700601 }
602 return nullptr;
603}
604
605std::unique_ptr<InterfaceBlock> IRGenerator::convertInterfaceBlock(const ASTInterfaceBlock& intf) {
606 std::shared_ptr<SymbolTable> old = fSymbolTable;
607 AutoSymbolTable table(this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700608 std::vector<Type::Field> fields;
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400609 bool haveRuntimeArray = false;
ethannicholasb3058bd2016-07-01 08:22:01 -0700610 for (size_t i = 0; i < intf.fDeclarations.size(); i++) {
ethannicholas14fe8cc2016-09-07 13:37:16 -0700611 std::unique_ptr<VarDeclarations> decl = this->convertVarDeclarations(
Ethan Nicholas11d53972016-11-28 11:23:23 -0500612 *intf.fDeclarations[i],
ethannicholasb3058bd2016-07-01 08:22:01 -0700613 Variable::kGlobal_Storage);
ethannicholas7effa7a2016-10-14 09:56:33 -0700614 if (!decl) {
615 return nullptr;
616 }
ethannicholas14fe8cc2016-09-07 13:37:16 -0700617 for (const auto& var : decl->fVars) {
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400618 if (haveRuntimeArray) {
619 fErrors.error(decl->fPosition,
620 "only the last entry in an interface block may be a runtime-sized "
621 "array");
622 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400623 fields.push_back(Type::Field(var->fVar->fModifiers, var->fVar->fName,
624 &var->fVar->fType));
625 if (var->fValue) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500626 fErrors.error(decl->fPosition,
ethannicholasb3058bd2016-07-01 08:22:01 -0700627 "initializers are not permitted on interface block fields");
628 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400629 if (var->fVar->fModifiers.fFlags & (Modifiers::kIn_Flag |
630 Modifiers::kOut_Flag |
631 Modifiers::kUniform_Flag |
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400632 Modifiers::kBuffer_Flag |
Ethan Nicholascb670962017-04-20 19:31:52 -0400633 Modifiers::kConst_Flag)) {
ethannicholas14fe8cc2016-09-07 13:37:16 -0700634 fErrors.error(decl->fPosition,
ethannicholasb3058bd2016-07-01 08:22:01 -0700635 "interface block fields may not have storage qualifiers");
636 }
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400637 if (var->fVar->fType.kind() == Type::kArray_Kind &&
638 var->fVar->fType.columns() == -1) {
639 haveRuntimeArray = true;
640 }
Ethan Nicholas11d53972016-11-28 11:23:23 -0500641 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700642 }
Ethan Nicholas50afc172017-02-16 14:49:57 -0500643 Type* type = new Type(intf.fPosition, intf.fTypeName, fields);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500644 old->takeOwnership(type);
Ethan Nicholas50afc172017-02-16 14:49:57 -0500645 std::vector<std::unique_ptr<Expression>> sizes;
646 for (const auto& size : intf.fSizes) {
647 if (size) {
648 std::unique_ptr<Expression> converted = this->convertExpression(*size);
649 if (!converted) {
650 return nullptr;
651 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400652 String name = type->fName;
Ethan Nicholas50afc172017-02-16 14:49:57 -0500653 int64_t count;
654 if (converted->fKind == Expression::kIntLiteral_Kind) {
655 count = ((IntLiteral&) *converted).fValue;
656 if (count <= 0) {
657 fErrors.error(converted->fPosition, "array size must be positive");
658 }
659 name += "[" + to_string(count) + "]";
660 } else {
661 count = -1;
662 name += "[]";
663 }
664 type = new Type(name, Type::kArray_Kind, *type, (int) count);
665 fSymbolTable->takeOwnership((Type*) type);
666 sizes.push_back(std::move(converted));
667 } else {
668 type = new Type(type->fName + "[]", Type::kArray_Kind, *type, -1);
669 fSymbolTable->takeOwnership((Type*) type);
670 sizes.push_back(nullptr);
671 }
672 }
673 Variable* var = new Variable(intf.fPosition, intf.fModifiers,
674 intf.fInstanceName.size() ? intf.fInstanceName : intf.fTypeName,
675 *type, Variable::kGlobal_Storage);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500676 old->takeOwnership(var);
Ethan Nicholas50afc172017-02-16 14:49:57 -0500677 if (intf.fInstanceName.size()) {
678 old->addWithoutOwnership(intf.fInstanceName, var);
ethannicholasb3058bd2016-07-01 08:22:01 -0700679 } else {
680 for (size_t i = 0; i < fields.size(); i++) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500681 old->add(fields[i].fName, std::unique_ptr<Field>(new Field(intf.fPosition, *var,
ethannicholasd598f792016-07-25 10:08:54 -0700682 (int) i)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700683 }
684 }
Ethan Nicholas8feeff92017-03-30 14:11:58 -0400685 return std::unique_ptr<InterfaceBlock>(new InterfaceBlock(intf.fPosition,
686 var,
Ethan Nicholas50afc172017-02-16 14:49:57 -0500687 intf.fTypeName,
688 intf.fInstanceName,
689 std::move(sizes),
690 fSymbolTable));
ethannicholasb3058bd2016-07-01 08:22:01 -0700691}
692
ethannicholasd598f792016-07-25 10:08:54 -0700693const Type* IRGenerator::convertType(const ASTType& type) {
694 const Symbol* result = (*fSymbolTable)[type.fName];
ethannicholasb3058bd2016-07-01 08:22:01 -0700695 if (result && result->fKind == Symbol::kType_Kind) {
Ethan Nicholas50afc172017-02-16 14:49:57 -0500696 for (int size : type.fSizes) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400697 String name = result->fName + "[";
Ethan Nicholas50afc172017-02-16 14:49:57 -0500698 if (size != -1) {
699 name += to_string(size);
700 }
701 name += "]";
702 result = new Type(name, Type::kArray_Kind, (const Type&) *result, size);
703 fSymbolTable->takeOwnership((Type*) result);
704 }
ethannicholasd598f792016-07-25 10:08:54 -0700705 return (const Type*) result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700706 }
707 fErrors.error(type.fPosition, "unknown type '" + type.fName + "'");
708 return nullptr;
709}
710
711std::unique_ptr<Expression> IRGenerator::convertExpression(const ASTExpression& expr) {
712 switch (expr.fKind) {
713 case ASTExpression::kIdentifier_Kind:
714 return this->convertIdentifier((ASTIdentifier&) expr);
715 case ASTExpression::kBool_Kind:
ethannicholasd598f792016-07-25 10:08:54 -0700716 return std::unique_ptr<Expression>(new BoolLiteral(fContext, expr.fPosition,
ethannicholasb3058bd2016-07-01 08:22:01 -0700717 ((ASTBoolLiteral&) expr).fValue));
718 case ASTExpression::kInt_Kind:
ethannicholasd598f792016-07-25 10:08:54 -0700719 return std::unique_ptr<Expression>(new IntLiteral(fContext, expr.fPosition,
ethannicholasb3058bd2016-07-01 08:22:01 -0700720 ((ASTIntLiteral&) expr).fValue));
721 case ASTExpression::kFloat_Kind:
ethannicholasd598f792016-07-25 10:08:54 -0700722 return std::unique_ptr<Expression>(new FloatLiteral(fContext, expr.fPosition,
ethannicholasb3058bd2016-07-01 08:22:01 -0700723 ((ASTFloatLiteral&) expr).fValue));
724 case ASTExpression::kBinary_Kind:
725 return this->convertBinaryExpression((ASTBinaryExpression&) expr);
726 case ASTExpression::kPrefix_Kind:
727 return this->convertPrefixExpression((ASTPrefixExpression&) expr);
728 case ASTExpression::kSuffix_Kind:
729 return this->convertSuffixExpression((ASTSuffixExpression&) expr);
730 case ASTExpression::kTernary_Kind:
731 return this->convertTernaryExpression((ASTTernaryExpression&) expr);
732 default:
733 ABORT("unsupported expression type: %d\n", expr.fKind);
734 }
735}
736
737std::unique_ptr<Expression> IRGenerator::convertIdentifier(const ASTIdentifier& identifier) {
ethannicholasd598f792016-07-25 10:08:54 -0700738 const Symbol* result = (*fSymbolTable)[identifier.fText];
ethannicholasb3058bd2016-07-01 08:22:01 -0700739 if (!result) {
740 fErrors.error(identifier.fPosition, "unknown identifier '" + identifier.fText + "'");
741 return nullptr;
742 }
743 switch (result->fKind) {
744 case Symbol::kFunctionDeclaration_Kind: {
ethannicholasd598f792016-07-25 10:08:54 -0700745 std::vector<const FunctionDeclaration*> f = {
746 (const FunctionDeclaration*) result
ethannicholasb3058bd2016-07-01 08:22:01 -0700747 };
ethannicholasd598f792016-07-25 10:08:54 -0700748 return std::unique_ptr<FunctionReference>(new FunctionReference(fContext,
749 identifier.fPosition,
750 f));
ethannicholasb3058bd2016-07-01 08:22:01 -0700751 }
752 case Symbol::kUnresolvedFunction_Kind: {
ethannicholasd598f792016-07-25 10:08:54 -0700753 const UnresolvedFunction* f = (const UnresolvedFunction*) result;
754 return std::unique_ptr<FunctionReference>(new FunctionReference(fContext,
755 identifier.fPosition,
ethannicholasb3058bd2016-07-01 08:22:01 -0700756 f->fFunctions));
757 }
758 case Symbol::kVariable_Kind: {
Ethan Nicholas38657112017-02-09 17:01:22 -0500759 const Variable* var = (const Variable*) result;
760 if (var->fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
761 fInputs.fFlipY = true;
762 if (fSettings->fFlipY &&
763 (!fSettings->fCaps ||
764 !fSettings->fCaps->fragCoordConventionsExtensionString())) {
765 fInputs.fRTHeight = true;
766 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500767 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500768 // default to kRead_RefKind; this will be corrected later if the variable is written to
769 return std::unique_ptr<VariableReference>(new VariableReference(
770 identifier.fPosition,
771 *var,
772 VariableReference::kRead_RefKind));
ethannicholasb3058bd2016-07-01 08:22:01 -0700773 }
774 case Symbol::kField_Kind: {
ethannicholasd598f792016-07-25 10:08:54 -0700775 const Field* field = (const Field*) result;
Ethan Nicholas86a43402017-01-19 13:32:00 -0500776 VariableReference* base = new VariableReference(identifier.fPosition, field->fOwner,
777 VariableReference::kRead_RefKind);
ethannicholasf789b382016-08-03 12:43:36 -0700778 return std::unique_ptr<Expression>(new FieldAccess(
779 std::unique_ptr<Expression>(base),
780 field->fFieldIndex,
781 FieldAccess::kAnonymousInterfaceBlock_OwnerKind));
ethannicholasb3058bd2016-07-01 08:22:01 -0700782 }
783 case Symbol::kType_Kind: {
ethannicholasd598f792016-07-25 10:08:54 -0700784 const Type* t = (const Type*) result;
Ethan Nicholas11d53972016-11-28 11:23:23 -0500785 return std::unique_ptr<TypeReference>(new TypeReference(fContext, identifier.fPosition,
ethannicholasd598f792016-07-25 10:08:54 -0700786 *t));
ethannicholasb3058bd2016-07-01 08:22:01 -0700787 }
788 default:
789 ABORT("unsupported symbol type %d\n", result->fKind);
790 }
791
792}
793
Ethan Nicholas11d53972016-11-28 11:23:23 -0500794std::unique_ptr<Expression> IRGenerator::coerce(std::unique_ptr<Expression> expr,
ethannicholasd598f792016-07-25 10:08:54 -0700795 const Type& type) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700796 if (!expr) {
797 return nullptr;
798 }
ethannicholasd598f792016-07-25 10:08:54 -0700799 if (expr->fType == type) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700800 return expr;
801 }
802 this->checkValid(*expr);
ethannicholasd598f792016-07-25 10:08:54 -0700803 if (expr->fType == *fContext.fInvalid_Type) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700804 return nullptr;
805 }
ethannicholasd598f792016-07-25 10:08:54 -0700806 if (!expr->fType.canCoerceTo(type)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500807 fErrors.error(expr->fPosition, "expected '" + type.description() + "', but found '" +
ethannicholasd598f792016-07-25 10:08:54 -0700808 expr->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -0700809 return nullptr;
810 }
ethannicholasd598f792016-07-25 10:08:54 -0700811 if (type.kind() == Type::kScalar_Kind) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700812 std::vector<std::unique_ptr<Expression>> args;
813 args.push_back(std::move(expr));
ethannicholasd598f792016-07-25 10:08:54 -0700814 ASTIdentifier id(Position(), type.description());
ethannicholasb3058bd2016-07-01 08:22:01 -0700815 std::unique_ptr<Expression> ctor = this->convertIdentifier(id);
816 ASSERT(ctor);
817 return this->call(Position(), std::move(ctor), std::move(args));
818 }
ethannicholas5961bc92016-10-12 06:39:56 -0700819 std::vector<std::unique_ptr<Expression>> args;
820 args.push_back(std::move(expr));
821 return std::unique_ptr<Expression>(new Constructor(Position(), type, std::move(args)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700822}
823
ethannicholasf789b382016-08-03 12:43:36 -0700824static bool is_matrix_multiply(const Type& left, const Type& right) {
825 if (left.kind() == Type::kMatrix_Kind) {
826 return right.kind() == Type::kMatrix_Kind || right.kind() == Type::kVector_Kind;
827 }
828 return left.kind() == Type::kVector_Kind && right.kind() == Type::kMatrix_Kind;
829}
ethannicholasea4567c2016-10-17 11:24:37 -0700830
ethannicholasb3058bd2016-07-01 08:22:01 -0700831/**
832 * Determines the operand and result types of a binary expression. Returns true if the expression is
833 * legal, false otherwise. If false, the values of the out parameters are undefined.
834 */
Ethan Nicholas11d53972016-11-28 11:23:23 -0500835static bool determine_binary_type(const Context& context,
836 Token::Kind op,
837 const Type& left,
838 const Type& right,
ethannicholasd598f792016-07-25 10:08:54 -0700839 const Type** outLeftType,
840 const Type** outRightType,
841 const Type** outResultType,
ethannicholasb3058bd2016-07-01 08:22:01 -0700842 bool tryFlipped) {
843 bool isLogical;
ethannicholasea4567c2016-10-17 11:24:37 -0700844 bool validMatrixOrVectorOp;
ethannicholasb3058bd2016-07-01 08:22:01 -0700845 switch (op) {
ethannicholasea4567c2016-10-17 11:24:37 -0700846 case Token::EQ:
847 *outLeftType = &left;
848 *outRightType = &left;
849 *outResultType = &left;
850 return right.canCoerceTo(left);
ethannicholasb3058bd2016-07-01 08:22:01 -0700851 case Token::EQEQ: // fall through
ethannicholasea4567c2016-10-17 11:24:37 -0700852 case Token::NEQ:
853 isLogical = true;
854 validMatrixOrVectorOp = true;
855 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700856 case Token::LT: // fall through
857 case Token::GT: // fall through
858 case Token::LTEQ: // fall through
859 case Token::GTEQ:
860 isLogical = true;
ethannicholasea4567c2016-10-17 11:24:37 -0700861 validMatrixOrVectorOp = false;
ethannicholasb3058bd2016-07-01 08:22:01 -0700862 break;
863 case Token::LOGICALOR: // fall through
864 case Token::LOGICALAND: // fall through
865 case Token::LOGICALXOR: // fall through
866 case Token::LOGICALOREQ: // fall through
867 case Token::LOGICALANDEQ: // fall through
868 case Token::LOGICALXOREQ:
ethannicholasd598f792016-07-25 10:08:54 -0700869 *outLeftType = context.fBool_Type.get();
870 *outRightType = context.fBool_Type.get();
871 *outResultType = context.fBool_Type.get();
Ethan Nicholas11d53972016-11-28 11:23:23 -0500872 return left.canCoerceTo(*context.fBool_Type) &&
ethannicholasd598f792016-07-25 10:08:54 -0700873 right.canCoerceTo(*context.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700874 case Token::STAR: // fall through
Ethan Nicholas11d53972016-11-28 11:23:23 -0500875 case Token::STAREQ:
ethannicholasf789b382016-08-03 12:43:36 -0700876 if (is_matrix_multiply(left, right)) {
877 // determine final component type
878 if (determine_binary_type(context, Token::STAR, left.componentType(),
879 right.componentType(), outLeftType, outRightType,
880 outResultType, false)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500881 *outLeftType = &(*outResultType)->toCompound(context, left.columns(),
ethannicholasf789b382016-08-03 12:43:36 -0700882 left.rows());;
Ethan Nicholas11d53972016-11-28 11:23:23 -0500883 *outRightType = &(*outResultType)->toCompound(context, right.columns(),
ethannicholasf789b382016-08-03 12:43:36 -0700884 right.rows());;
885 int leftColumns = left.columns();
886 int leftRows = left.rows();
887 int rightColumns;
888 int rightRows;
889 if (right.kind() == Type::kVector_Kind) {
890 // matrix * vector treats the vector as a column vector, so we need to
891 // transpose it
892 rightColumns = right.rows();
893 rightRows = right.columns();
894 ASSERT(rightColumns == 1);
895 } else {
896 rightColumns = right.columns();
897 rightRows = right.rows();
898 }
899 if (rightColumns > 1) {
900 *outResultType = &(*outResultType)->toCompound(context, rightColumns,
901 leftRows);
902 } else {
903 // result was a column vector, transpose it back to a row
904 *outResultType = &(*outResultType)->toCompound(context, leftRows,
905 rightColumns);
906 }
907 return leftColumns == rightRows;
908 } else {
909 return false;
910 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700911 }
ethannicholasea4567c2016-10-17 11:24:37 -0700912 isLogical = false;
913 validMatrixOrVectorOp = true;
914 break;
915 case Token::PLUS: // fall through
916 case Token::PLUSEQ: // fall through
917 case Token::MINUS: // fall through
918 case Token::MINUSEQ: // fall through
919 case Token::SLASH: // fall through
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400920 case Token::SLASHEQ: // fall through
ethannicholasea4567c2016-10-17 11:24:37 -0700921 isLogical = false;
922 validMatrixOrVectorOp = true;
923 break;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400924 case Token::COMMA:
925 *outLeftType = &left;
926 *outRightType = &right;
927 *outResultType = &right;
928 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -0700929 default:
930 isLogical = false;
ethannicholasea4567c2016-10-17 11:24:37 -0700931 validMatrixOrVectorOp = false;
ethannicholasb3058bd2016-07-01 08:22:01 -0700932 }
ethannicholasea4567c2016-10-17 11:24:37 -0700933 bool isVectorOrMatrix = left.kind() == Type::kVector_Kind || left.kind() == Type::kMatrix_Kind;
934 // FIXME: incorrect for shift
Ethan Nicholas11d53972016-11-28 11:23:23 -0500935 if (right.canCoerceTo(left) && (left.kind() == Type::kScalar_Kind ||
ethannicholasea4567c2016-10-17 11:24:37 -0700936 (isVectorOrMatrix && validMatrixOrVectorOp))) {
ethannicholasd598f792016-07-25 10:08:54 -0700937 *outLeftType = &left;
938 *outRightType = &left;
ethannicholasb3058bd2016-07-01 08:22:01 -0700939 if (isLogical) {
ethannicholasd598f792016-07-25 10:08:54 -0700940 *outResultType = context.fBool_Type.get();
ethannicholasb3058bd2016-07-01 08:22:01 -0700941 } else {
ethannicholasd598f792016-07-25 10:08:54 -0700942 *outResultType = &left;
ethannicholasb3058bd2016-07-01 08:22:01 -0700943 }
944 return true;
945 }
Ethan Nicholas11d53972016-11-28 11:23:23 -0500946 if ((left.kind() == Type::kVector_Kind || left.kind() == Type::kMatrix_Kind) &&
ethannicholasd598f792016-07-25 10:08:54 -0700947 (right.kind() == Type::kScalar_Kind)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500948 if (determine_binary_type(context, op, left.componentType(), right, outLeftType,
ethannicholasd598f792016-07-25 10:08:54 -0700949 outRightType, outResultType, false)) {
950 *outLeftType = &(*outLeftType)->toCompound(context, left.columns(), left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -0700951 if (!isLogical) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500952 *outResultType = &(*outResultType)->toCompound(context, left.columns(),
ethannicholasd598f792016-07-25 10:08:54 -0700953 left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -0700954 }
955 return true;
956 }
957 return false;
958 }
959 if (tryFlipped) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500960 return determine_binary_type(context, op, right, left, outRightType, outLeftType,
ethannicholasd598f792016-07-25 10:08:54 -0700961 outResultType, false);
ethannicholasb3058bd2016-07-01 08:22:01 -0700962 }
963 return false;
964}
965
ethannicholas08a92112016-11-09 13:26:45 -0800966std::unique_ptr<Expression> IRGenerator::constantFold(const Expression& left,
967 Token::Kind op,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500968 const Expression& right) const {
Ethan Nicholascb670962017-04-20 19:31:52 -0400969 if (!left.isConstant() || !right.isConstant()) {
970 return nullptr;
971 }
ethannicholas08a92112016-11-09 13:26:45 -0800972 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
973 // precision to calculate the results and hope the result makes sense. The plan is to move the
974 // Skia caps into SkSL, so we have access to all of them including the precisions of the various
975 // types, which will let us be more intelligent about this.
Ethan Nicholas11d53972016-11-28 11:23:23 -0500976 if (left.fKind == Expression::kBoolLiteral_Kind &&
ethannicholas08a92112016-11-09 13:26:45 -0800977 right.fKind == Expression::kBoolLiteral_Kind) {
978 bool leftVal = ((BoolLiteral&) left).fValue;
979 bool rightVal = ((BoolLiteral&) right).fValue;
980 bool result;
981 switch (op) {
982 case Token::LOGICALAND: result = leftVal && rightVal; break;
983 case Token::LOGICALOR: result = leftVal || rightVal; break;
984 case Token::LOGICALXOR: result = leftVal ^ rightVal; break;
985 default: return nullptr;
986 }
987 return std::unique_ptr<Expression>(new BoolLiteral(fContext, left.fPosition, result));
988 }
989 #define RESULT(t, op) std::unique_ptr<Expression>(new t ## Literal(fContext, left.fPosition, \
990 leftVal op rightVal))
991 if (left.fKind == Expression::kIntLiteral_Kind && right.fKind == Expression::kIntLiteral_Kind) {
992 int64_t leftVal = ((IntLiteral&) left).fValue;
993 int64_t rightVal = ((IntLiteral&) right).fValue;
994 switch (op) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400995 case Token::PLUS: return RESULT(Int, +);
996 case Token::MINUS: return RESULT(Int, -);
997 case Token::STAR: return RESULT(Int, *);
Ethan Nicholas9a5610e2017-01-03 15:16:29 -0500998 case Token::SLASH:
999 if (rightVal) {
1000 return RESULT(Int, /);
1001 }
1002 fErrors.error(right.fPosition, "division by zero");
1003 return nullptr;
Ethan Nicholas2503ab62017-01-05 10:44:25 -05001004 case Token::PERCENT:
1005 if (rightVal) {
1006 return RESULT(Int, %);
1007 }
1008 fErrors.error(right.fPosition, "division by zero");
1009 return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001010 case Token::BITWISEAND: return RESULT(Int, &);
1011 case Token::BITWISEOR: return RESULT(Int, |);
1012 case Token::BITWISEXOR: return RESULT(Int, ^);
1013 case Token::SHL: return RESULT(Int, <<);
1014 case Token::SHR: return RESULT(Int, >>);
1015 case Token::EQEQ: return RESULT(Bool, ==);
1016 case Token::NEQ: return RESULT(Bool, !=);
1017 case Token::GT: return RESULT(Bool, >);
1018 case Token::GTEQ: return RESULT(Bool, >=);
1019 case Token::LT: return RESULT(Bool, <);
1020 case Token::LTEQ: return RESULT(Bool, <=);
1021 default: return nullptr;
1022 }
1023 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001024 if (left.fKind == Expression::kFloatLiteral_Kind &&
ethannicholas08a92112016-11-09 13:26:45 -08001025 right.fKind == Expression::kFloatLiteral_Kind) {
1026 double leftVal = ((FloatLiteral&) left).fValue;
1027 double rightVal = ((FloatLiteral&) right).fValue;
1028 switch (op) {
1029 case Token::PLUS: return RESULT(Float, +);
1030 case Token::MINUS: return RESULT(Float, -);
1031 case Token::STAR: return RESULT(Float, *);
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001032 case Token::SLASH:
1033 if (rightVal) {
1034 return RESULT(Float, /);
1035 }
1036 fErrors.error(right.fPosition, "division by zero");
1037 return nullptr;
Ethan Nicholascb670962017-04-20 19:31:52 -04001038 case Token::EQEQ: return RESULT(Bool, ==);
1039 case Token::NEQ: return RESULT(Bool, !=);
1040 case Token::GT: return RESULT(Bool, >);
1041 case Token::GTEQ: return RESULT(Bool, >=);
1042 case Token::LT: return RESULT(Bool, <);
1043 case Token::LTEQ: return RESULT(Bool, <=);
ethannicholas08a92112016-11-09 13:26:45 -08001044 default: return nullptr;
1045 }
1046 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001047 if (left.fType.kind() == Type::kVector_Kind &&
1048 left.fType.componentType() == *fContext.fFloat_Type &&
1049 left.fType == right.fType) {
1050 ASSERT(left.fKind == Expression::kConstructor_Kind);
1051 ASSERT(right.fKind == Expression::kConstructor_Kind);
1052 std::vector<std::unique_ptr<Expression>> args;
1053 #define RETURN_VEC_COMPONENTWISE_RESULT(op) \
1054 for (int i = 0; i < left.fType.columns(); i++) { \
1055 float value = ((Constructor&) left).getFVecComponent(i) op \
1056 ((Constructor&) right).getFVecComponent(i); \
1057 args.emplace_back(new FloatLiteral(fContext, Position(), value)); \
1058 } \
1059 return std::unique_ptr<Expression>(new Constructor(Position(), left.fType, \
1060 std::move(args)));
1061 switch (op) {
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001062 case Token::EQEQ:
1063 return std::unique_ptr<Expression>(new BoolLiteral(fContext, Position(),
1064 left.compareConstant(fContext, right)));
1065 case Token::NEQ:
1066 return std::unique_ptr<Expression>(new BoolLiteral(fContext, Position(),
1067 !left.compareConstant(fContext, right)));
Ethan Nicholascb670962017-04-20 19:31:52 -04001068 case Token::PLUS: RETURN_VEC_COMPONENTWISE_RESULT(+);
1069 case Token::MINUS: RETURN_VEC_COMPONENTWISE_RESULT(-);
1070 case Token::STAR: RETURN_VEC_COMPONENTWISE_RESULT(*);
1071 case Token::SLASH: RETURN_VEC_COMPONENTWISE_RESULT(/);
1072 default: return nullptr;
1073 }
1074 }
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001075 if (left.fType.kind() == Type::kMatrix_Kind &&
1076 right.fType.kind() == Type::kMatrix_Kind &&
1077 left.fKind == right.fKind) {
1078 switch (op) {
1079 case Token::EQEQ:
1080 return std::unique_ptr<Expression>(new BoolLiteral(fContext, Position(),
1081 left.compareConstant(fContext, right)));
1082 case Token::NEQ:
1083 return std::unique_ptr<Expression>(new BoolLiteral(fContext, Position(),
1084 !left.compareConstant(fContext, right)));
1085 default:
1086 return nullptr;
1087 }
1088 }
ethannicholas08a92112016-11-09 13:26:45 -08001089 #undef RESULT
1090 return nullptr;
1091}
1092
ethannicholasb3058bd2016-07-01 08:22:01 -07001093std::unique_ptr<Expression> IRGenerator::convertBinaryExpression(
1094 const ASTBinaryExpression& expression) {
1095 std::unique_ptr<Expression> left = this->convertExpression(*expression.fLeft);
1096 if (!left) {
1097 return nullptr;
1098 }
1099 std::unique_ptr<Expression> right = this->convertExpression(*expression.fRight);
1100 if (!right) {
1101 return nullptr;
1102 }
ethannicholasd598f792016-07-25 10:08:54 -07001103 const Type* leftType;
1104 const Type* rightType;
1105 const Type* resultType;
1106 if (!determine_binary_type(fContext, expression.fOperator, left->fType, right->fType, &leftType,
Ethan Nicholas86a43402017-01-19 13:32:00 -05001107 &rightType, &resultType,
1108 !Token::IsAssignment(expression.fOperator))) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001109 fErrors.error(expression.fPosition, "type mismatch: '" +
1110 Token::OperatorName(expression.fOperator) +
1111 "' cannot operate on '" + left->fType.fName +
ethannicholasd598f792016-07-25 10:08:54 -07001112 "', '" + right->fType.fName + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001113 return nullptr;
1114 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001115 if (Token::IsAssignment(expression.fOperator)) {
1116 this->markWrittenTo(*left, expression.fOperator != Token::EQ);
ethannicholasea4567c2016-10-17 11:24:37 -07001117 }
1118 left = this->coerce(std::move(left), *leftType);
1119 right = this->coerce(std::move(right), *rightType);
1120 if (!left || !right) {
1121 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001122 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001123 std::unique_ptr<Expression> result = this->constantFold(*left.get(), expression.fOperator,
ethannicholas08a92112016-11-09 13:26:45 -08001124 *right.get());
1125 if (!result) {
1126 result = std::unique_ptr<Expression>(new BinaryExpression(expression.fPosition,
1127 std::move(left),
1128 expression.fOperator,
1129 std::move(right),
1130 *resultType));
1131 }
1132 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07001133}
1134
Ethan Nicholas11d53972016-11-28 11:23:23 -05001135std::unique_ptr<Expression> IRGenerator::convertTernaryExpression(
ethannicholasb3058bd2016-07-01 08:22:01 -07001136 const ASTTernaryExpression& expression) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001137 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*expression.fTest),
ethannicholasd598f792016-07-25 10:08:54 -07001138 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -07001139 if (!test) {
1140 return nullptr;
1141 }
1142 std::unique_ptr<Expression> ifTrue = this->convertExpression(*expression.fIfTrue);
1143 if (!ifTrue) {
1144 return nullptr;
1145 }
1146 std::unique_ptr<Expression> ifFalse = this->convertExpression(*expression.fIfFalse);
1147 if (!ifFalse) {
1148 return nullptr;
1149 }
ethannicholasd598f792016-07-25 10:08:54 -07001150 const Type* trueType;
1151 const Type* falseType;
1152 const Type* resultType;
1153 if (!determine_binary_type(fContext, Token::EQEQ, ifTrue->fType, ifFalse->fType, &trueType,
Ethan Nicholas2be687a2017-01-03 16:44:39 -05001154 &falseType, &resultType, true) || trueType != falseType) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001155 fErrors.error(expression.fPosition, "ternary operator result mismatch: '" +
1156 ifTrue->fType.fName + "', '" +
ethannicholasd598f792016-07-25 10:08:54 -07001157 ifFalse->fType.fName + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001158 return nullptr;
1159 }
ethannicholasd598f792016-07-25 10:08:54 -07001160 ifTrue = this->coerce(std::move(ifTrue), *trueType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05001161 if (!ifTrue) {
1162 return nullptr;
1163 }
ethannicholasd598f792016-07-25 10:08:54 -07001164 ifFalse = this->coerce(std::move(ifFalse), *falseType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05001165 if (!ifFalse) {
1166 return nullptr;
1167 }
ethannicholas08a92112016-11-09 13:26:45 -08001168 if (test->fKind == Expression::kBoolLiteral_Kind) {
1169 // static boolean test, just return one of the branches
1170 if (((BoolLiteral&) *test).fValue) {
1171 return ifTrue;
1172 } else {
1173 return ifFalse;
1174 }
1175 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001176 return std::unique_ptr<Expression>(new TernaryExpression(expression.fPosition,
ethannicholasb3058bd2016-07-01 08:22:01 -07001177 std::move(test),
Ethan Nicholas11d53972016-11-28 11:23:23 -05001178 std::move(ifTrue),
ethannicholasb3058bd2016-07-01 08:22:01 -07001179 std::move(ifFalse)));
1180}
1181
Ethan Nicholas5338f992017-04-19 15:54:07 -04001182// scales the texture coordinates by the texture size for sampling rectangle textures.
1183// For vec2 coordinates, implements the transformation:
1184// texture(sampler, coord) -> texture(sampler, textureSize(sampler) * coord)
1185// For vec3 coordinates, implements the transformation:
1186// texture(sampler, coord) -> texture(sampler, vec3(textureSize(sampler), 1.0) * coord))
1187void IRGenerator::fixRectSampling(std::vector<std::unique_ptr<Expression>>& arguments) {
1188 ASSERT(arguments.size() == 2);
1189 ASSERT(arguments[0]->fType == *fContext.fSampler2DRect_Type);
1190 ASSERT(arguments[0]->fKind == Expression::kVariableReference_Kind);
1191 const Variable& sampler = ((VariableReference&) *arguments[0]).fVariable;
1192 const Symbol* textureSizeSymbol = (*fSymbolTable)["textureSize"];
1193 ASSERT(textureSizeSymbol->fKind == Symbol::kFunctionDeclaration_Kind);
1194 const FunctionDeclaration& textureSize = (FunctionDeclaration&) *textureSizeSymbol;
1195 std::vector<std::unique_ptr<Expression>> sizeArguments;
1196 sizeArguments.emplace_back(new VariableReference(Position(), sampler));
1197 std::unique_ptr<Expression> vec2Size = call(Position(), textureSize, std::move(sizeArguments));
1198 const Type& type = arguments[1]->fType;
1199 std::unique_ptr<Expression> scale;
1200 if (type == *fContext.fVec2_Type) {
1201 scale = std::move(vec2Size);
1202 } else {
1203 ASSERT(type == *fContext.fVec3_Type);
1204 std::vector<std::unique_ptr<Expression>> vec3Arguments;
1205 vec3Arguments.push_back(std::move(vec2Size));
1206 vec3Arguments.emplace_back(new FloatLiteral(fContext, Position(), 1.0));
1207 scale.reset(new Constructor(Position(), *fContext.fVec3_Type, std::move(vec3Arguments)));
1208 }
1209 arguments[1].reset(new BinaryExpression(Position(), std::move(scale), Token::STAR,
1210 std::move(arguments[1]), type));
1211}
1212
Ethan Nicholas11d53972016-11-28 11:23:23 -05001213std::unique_ptr<Expression> IRGenerator::call(Position position,
1214 const FunctionDeclaration& function,
ethannicholasd598f792016-07-25 10:08:54 -07001215 std::vector<std::unique_ptr<Expression>> arguments) {
1216 if (function.fParameters.size() != arguments.size()) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001217 String msg = "call to '" + function.fName + "' expected " +
Ethan Nicholas11d53972016-11-28 11:23:23 -05001218 to_string((uint64_t) function.fParameters.size()) +
ethannicholasb3058bd2016-07-01 08:22:01 -07001219 " argument";
ethannicholasd598f792016-07-25 10:08:54 -07001220 if (function.fParameters.size() != 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001221 msg += "s";
1222 }
ethannicholas5961bc92016-10-12 06:39:56 -07001223 msg += ", but found " + to_string((uint64_t) arguments.size());
ethannicholasb3058bd2016-07-01 08:22:01 -07001224 fErrors.error(position, msg);
1225 return nullptr;
1226 }
ethannicholas471e8942016-10-28 09:02:46 -07001227 std::vector<const Type*> types;
1228 const Type* returnType;
1229 if (!function.determineFinalTypes(arguments, &types, &returnType)) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001230 String msg = "no match for " + function.fName + "(";
1231 String separator;
ethannicholas471e8942016-10-28 09:02:46 -07001232 for (size_t i = 0; i < arguments.size(); i++) {
1233 msg += separator;
1234 separator = ", ";
1235 msg += arguments[i]->fType.description();
1236 }
1237 msg += ")";
1238 fErrors.error(position, msg);
1239 return nullptr;
1240 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001241 for (size_t i = 0; i < arguments.size(); i++) {
ethannicholas471e8942016-10-28 09:02:46 -07001242 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
ethannicholasea4567c2016-10-17 11:24:37 -07001243 if (!arguments[i]) {
1244 return nullptr;
1245 }
ethannicholasd598f792016-07-25 10:08:54 -07001246 if (arguments[i] && (function.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag)) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001247 this->markWrittenTo(*arguments[i],
1248 function.fParameters[i]->fModifiers.fFlags & Modifiers::kIn_Flag);
ethannicholasb3058bd2016-07-01 08:22:01 -07001249 }
1250 }
Ethan Nicholas5338f992017-04-19 15:54:07 -04001251 if (function.fBuiltin && function.fName == "texture" &&
1252 arguments[0]->fType == *fContext.fSampler2DRect_Type) {
1253 this->fixRectSampling(arguments);
1254 }
ethannicholas471e8942016-10-28 09:02:46 -07001255 return std::unique_ptr<FunctionCall>(new FunctionCall(position, *returnType, function,
ethannicholasb3058bd2016-07-01 08:22:01 -07001256 std::move(arguments)));
1257}
1258
1259/**
Ethan Nicholas11d53972016-11-28 11:23:23 -05001260 * Determines the cost of coercing the arguments of a function to the required types. Returns true
1261 * if the cost could be computed, false if the call is not valid. Cost has no particular meaning
ethannicholasb3058bd2016-07-01 08:22:01 -07001262 * other than "lower costs are preferred".
1263 */
Ethan Nicholas11d53972016-11-28 11:23:23 -05001264bool IRGenerator::determineCallCost(const FunctionDeclaration& function,
ethannicholasb3058bd2016-07-01 08:22:01 -07001265 const std::vector<std::unique_ptr<Expression>>& arguments,
1266 int* outCost) {
ethannicholasd598f792016-07-25 10:08:54 -07001267 if (function.fParameters.size() != arguments.size()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001268 return false;
1269 }
1270 int total = 0;
ethannicholas471e8942016-10-28 09:02:46 -07001271 std::vector<const Type*> types;
1272 const Type* ignored;
1273 if (!function.determineFinalTypes(arguments, &types, &ignored)) {
1274 return false;
1275 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001276 for (size_t i = 0; i < arguments.size(); i++) {
1277 int cost;
ethannicholas471e8942016-10-28 09:02:46 -07001278 if (arguments[i]->fType.determineCoercionCost(*types[i], &cost)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001279 total += cost;
1280 } else {
1281 return false;
1282 }
1283 }
1284 *outCost = total;
1285 return true;
1286}
1287
Ethan Nicholas11d53972016-11-28 11:23:23 -05001288std::unique_ptr<Expression> IRGenerator::call(Position position,
1289 std::unique_ptr<Expression> functionValue,
ethannicholasb3058bd2016-07-01 08:22:01 -07001290 std::vector<std::unique_ptr<Expression>> arguments) {
1291 if (functionValue->fKind == Expression::kTypeReference_Kind) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001292 return this->convertConstructor(position,
1293 ((TypeReference&) *functionValue).fValue,
ethannicholasb3058bd2016-07-01 08:22:01 -07001294 std::move(arguments));
1295 }
1296 if (functionValue->fKind != Expression::kFunctionReference_Kind) {
1297 fErrors.error(position, "'" + functionValue->description() + "' is not a function");
1298 return nullptr;
1299 }
1300 FunctionReference* ref = (FunctionReference*) functionValue.get();
1301 int bestCost = INT_MAX;
ethannicholasd598f792016-07-25 10:08:54 -07001302 const FunctionDeclaration* best = nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001303 if (ref->fFunctions.size() > 1) {
1304 for (const auto& f : ref->fFunctions) {
1305 int cost;
ethannicholasd598f792016-07-25 10:08:54 -07001306 if (this->determineCallCost(*f, arguments, &cost) && cost < bestCost) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001307 bestCost = cost;
1308 best = f;
1309 }
1310 }
1311 if (best) {
ethannicholasd598f792016-07-25 10:08:54 -07001312 return this->call(position, *best, std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07001313 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001314 String msg = "no match for " + ref->fFunctions[0]->fName + "(";
1315 String separator;
ethannicholasb3058bd2016-07-01 08:22:01 -07001316 for (size_t i = 0; i < arguments.size(); i++) {
1317 msg += separator;
1318 separator = ", ";
ethannicholasd598f792016-07-25 10:08:54 -07001319 msg += arguments[i]->fType.description();
ethannicholasb3058bd2016-07-01 08:22:01 -07001320 }
1321 msg += ")";
1322 fErrors.error(position, msg);
1323 return nullptr;
1324 }
ethannicholasd598f792016-07-25 10:08:54 -07001325 return this->call(position, *ref->fFunctions[0], std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07001326}
1327
Ethan Nicholas84645e32017-02-09 13:57:14 -05001328std::unique_ptr<Expression> IRGenerator::convertNumberConstructor(
Ethan Nicholas11d53972016-11-28 11:23:23 -05001329 Position position,
1330 const Type& type,
ethannicholasb3058bd2016-07-01 08:22:01 -07001331 std::vector<std::unique_ptr<Expression>> args) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001332 ASSERT(type.isNumber());
1333 if (args.size() != 1) {
1334 fErrors.error(position, "invalid arguments to '" + type.description() +
1335 "' constructor, (expected exactly 1 argument, but found " +
1336 to_string((uint64_t) args.size()) + ")");
ethannicholasb3058bd2016-07-01 08:22:01 -07001337 return nullptr;
1338 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001339 if (type == *fContext.fFloat_Type && args.size() == 1 &&
ethannicholasb3058bd2016-07-01 08:22:01 -07001340 args[0]->fKind == Expression::kIntLiteral_Kind) {
1341 int64_t value = ((IntLiteral&) *args[0]).fValue;
ethannicholasd598f792016-07-25 10:08:54 -07001342 return std::unique_ptr<Expression>(new FloatLiteral(fContext, position, (double) value));
ethannicholasb3058bd2016-07-01 08:22:01 -07001343 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05001344 if (args[0]->fKind == Expression::kIntLiteral_Kind && (type == *fContext.fInt_Type ||
1345 type == *fContext.fUInt_Type)) {
1346 return std::unique_ptr<Expression>(new IntLiteral(fContext,
1347 position,
1348 ((IntLiteral&) *args[0]).fValue,
1349 &type));
ethannicholasb3058bd2016-07-01 08:22:01 -07001350 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05001351 if (args[0]->fType == *fContext.fBool_Type) {
1352 std::unique_ptr<IntLiteral> zero(new IntLiteral(fContext, position, 0));
1353 std::unique_ptr<IntLiteral> one(new IntLiteral(fContext, position, 1));
1354 return std::unique_ptr<Expression>(
1355 new TernaryExpression(position, std::move(args[0]),
1356 this->coerce(std::move(one), type),
1357 this->coerce(std::move(zero),
1358 type)));
1359 }
1360 if (!args[0]->fType.isNumber()) {
1361 fErrors.error(position, "invalid argument to '" + type.description() +
1362 "' constructor (expected a number or bool, but found '" +
1363 args[0]->fType.description() + "')");
1364 return nullptr;
1365 }
1366 return std::unique_ptr<Expression>(new Constructor(position, std::move(type), std::move(args)));
1367}
1368
1369int component_count(const Type& type) {
1370 switch (type.kind()) {
1371 case Type::kVector_Kind:
1372 return type.columns();
1373 case Type::kMatrix_Kind:
1374 return type.columns() * type.rows();
1375 default:
1376 return 1;
1377 }
1378}
1379
1380std::unique_ptr<Expression> IRGenerator::convertCompoundConstructor(
1381 Position position,
1382 const Type& type,
1383 std::vector<std::unique_ptr<Expression>> args) {
1384 ASSERT(type.kind() == Type::kVector_Kind || type.kind() == Type::kMatrix_Kind);
1385 if (type.kind() == Type::kMatrix_Kind && args.size() == 1 &&
1386 args[0]->fType.kind() == Type::kMatrix_Kind) {
1387 // matrix from matrix is always legal
1388 return std::unique_ptr<Expression>(new Constructor(position, std::move(type),
1389 std::move(args)));
1390 }
1391 int actual = 0;
1392 int expected = type.rows() * type.columns();
1393 if (args.size() != 1 || expected != component_count(args[0]->fType) ||
1394 type.componentType().isNumber() != args[0]->fType.componentType().isNumber()) {
ethannicholas5961bc92016-10-12 06:39:56 -07001395 for (size_t i = 0; i < args.size(); i++) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001396 if (args[i]->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00001397 if (type.componentType().isNumber() !=
1398 args[i]->fType.componentType().isNumber()) {
1399 fErrors.error(position, "'" + args[i]->fType.description() + "' is not a valid "
1400 "parameter to '" + type.description() +
1401 "' constructor");
1402 return nullptr;
1403 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05001404 actual += args[i]->fType.columns();
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00001405 } else if (args[i]->fType.kind() == Type::kScalar_Kind) {
1406 actual += 1;
1407 if (type.kind() != Type::kScalar_Kind) {
1408 args[i] = this->coerce(std::move(args[i]), type.componentType());
1409 if (!args[i]) {
1410 return nullptr;
1411 }
1412 }
1413 } else {
1414 fErrors.error(position, "'" + args[i]->fType.description() + "' is not a valid "
1415 "parameter to '" + type.description() + "' constructor");
1416 return nullptr;
1417 }
1418 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05001419 if (actual != 1 && actual != expected) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00001420 fErrors.error(position, "invalid arguments to '" + type.description() +
Ethan Nicholas84645e32017-02-09 13:57:14 -05001421 "' constructor (expected " + to_string(expected) +
1422 " scalars, but found " + to_string(actual) + ")");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00001423 return nullptr;
1424 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001425 }
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00001426 return std::unique_ptr<Expression>(new Constructor(position, std::move(type), std::move(args)));
ethannicholasb3058bd2016-07-01 08:22:01 -07001427}
1428
Ethan Nicholas84645e32017-02-09 13:57:14 -05001429std::unique_ptr<Expression> IRGenerator::convertConstructor(
1430 Position position,
1431 const Type& type,
1432 std::vector<std::unique_ptr<Expression>> args) {
1433 // FIXME: add support for structs
1434 Type::Kind kind = type.kind();
1435 if (args.size() == 1 && args[0]->fType == type) {
1436 // argument is already the right type, just return it
1437 return std::move(args[0]);
1438 }
1439 if (type.isNumber()) {
1440 return this->convertNumberConstructor(position, type, std::move(args));
1441 } else if (kind == Type::kArray_Kind) {
1442 const Type& base = type.componentType();
1443 for (size_t i = 0; i < args.size(); i++) {
1444 args[i] = this->coerce(std::move(args[i]), base);
1445 if (!args[i]) {
1446 return nullptr;
1447 }
1448 }
1449 return std::unique_ptr<Expression>(new Constructor(position, std::move(type),
1450 std::move(args)));
1451 } else if (kind == Type::kVector_Kind || kind == Type::kMatrix_Kind) {
1452 return this->convertCompoundConstructor(position, type, std::move(args));
1453 } else {
1454 fErrors.error(position, "cannot construct '" + type.description() + "'");
1455 return nullptr;
1456 }
1457}
1458
ethannicholasb3058bd2016-07-01 08:22:01 -07001459std::unique_ptr<Expression> IRGenerator::convertPrefixExpression(
1460 const ASTPrefixExpression& expression) {
1461 std::unique_ptr<Expression> base = this->convertExpression(*expression.fOperand);
1462 if (!base) {
1463 return nullptr;
1464 }
1465 switch (expression.fOperator) {
1466 case Token::PLUS:
ethannicholasd598f792016-07-25 10:08:54 -07001467 if (!base->fType.isNumber() && base->fType.kind() != Type::kVector_Kind) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001468 fErrors.error(expression.fPosition,
ethannicholasd598f792016-07-25 10:08:54 -07001469 "'+' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001470 return nullptr;
1471 }
1472 return base;
1473 case Token::MINUS:
ethannicholasd598f792016-07-25 10:08:54 -07001474 if (!base->fType.isNumber() && base->fType.kind() != Type::kVector_Kind) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001475 fErrors.error(expression.fPosition,
ethannicholasd598f792016-07-25 10:08:54 -07001476 "'-' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001477 return nullptr;
1478 }
1479 if (base->fKind == Expression::kIntLiteral_Kind) {
ethannicholasd598f792016-07-25 10:08:54 -07001480 return std::unique_ptr<Expression>(new IntLiteral(fContext, base->fPosition,
ethannicholasb3058bd2016-07-01 08:22:01 -07001481 -((IntLiteral&) *base).fValue));
1482 }
1483 if (base->fKind == Expression::kFloatLiteral_Kind) {
1484 double value = -((FloatLiteral&) *base).fValue;
Ethan Nicholas11d53972016-11-28 11:23:23 -05001485 return std::unique_ptr<Expression>(new FloatLiteral(fContext, base->fPosition,
ethannicholasd598f792016-07-25 10:08:54 -07001486 value));
ethannicholasb3058bd2016-07-01 08:22:01 -07001487 }
1488 return std::unique_ptr<Expression>(new PrefixExpression(Token::MINUS, std::move(base)));
1489 case Token::PLUSPLUS:
ethannicholasd598f792016-07-25 10:08:54 -07001490 if (!base->fType.isNumber()) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001491 fErrors.error(expression.fPosition,
1492 "'" + Token::OperatorName(expression.fOperator) +
ethannicholasd598f792016-07-25 10:08:54 -07001493 "' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001494 return nullptr;
1495 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001496 this->markWrittenTo(*base, true);
ethannicholasb3058bd2016-07-01 08:22:01 -07001497 break;
Ethan Nicholas11d53972016-11-28 11:23:23 -05001498 case Token::MINUSMINUS:
ethannicholasd598f792016-07-25 10:08:54 -07001499 if (!base->fType.isNumber()) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001500 fErrors.error(expression.fPosition,
1501 "'" + Token::OperatorName(expression.fOperator) +
ethannicholasd598f792016-07-25 10:08:54 -07001502 "' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001503 return nullptr;
1504 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001505 this->markWrittenTo(*base, true);
ethannicholasb3058bd2016-07-01 08:22:01 -07001506 break;
ethannicholas5961bc92016-10-12 06:39:56 -07001507 case Token::LOGICALNOT:
ethannicholasd598f792016-07-25 10:08:54 -07001508 if (base->fType != *fContext.fBool_Type) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001509 fErrors.error(expression.fPosition,
1510 "'" + Token::OperatorName(expression.fOperator) +
ethannicholasd598f792016-07-25 10:08:54 -07001511 "' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001512 return nullptr;
1513 }
ethannicholas08a92112016-11-09 13:26:45 -08001514 if (base->fKind == Expression::kBoolLiteral_Kind) {
1515 return std::unique_ptr<Expression>(new BoolLiteral(fContext, base->fPosition,
1516 !((BoolLiteral&) *base).fValue));
1517 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001518 break;
ethannicholas5961bc92016-10-12 06:39:56 -07001519 case Token::BITWISENOT:
1520 if (base->fType != *fContext.fInt_Type) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001521 fErrors.error(expression.fPosition,
1522 "'" + Token::OperatorName(expression.fOperator) +
ethannicholas5961bc92016-10-12 06:39:56 -07001523 "' cannot operate on '" + base->fType.description() + "'");
1524 return nullptr;
1525 }
1526 break;
Ethan Nicholas11d53972016-11-28 11:23:23 -05001527 default:
ethannicholasb3058bd2016-07-01 08:22:01 -07001528 ABORT("unsupported prefix operator\n");
1529 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001530 return std::unique_ptr<Expression>(new PrefixExpression(expression.fOperator,
ethannicholasb3058bd2016-07-01 08:22:01 -07001531 std::move(base)));
1532}
1533
1534std::unique_ptr<Expression> IRGenerator::convertIndex(std::unique_ptr<Expression> base,
1535 const ASTExpression& index) {
Ethan Nicholas50afc172017-02-16 14:49:57 -05001536 if (base->fKind == Expression::kTypeReference_Kind) {
1537 if (index.fKind == ASTExpression::kInt_Kind) {
1538 const Type& oldType = ((TypeReference&) *base).fValue;
1539 int64_t size = ((const ASTIntLiteral&) index).fValue;
1540 Type* newType = new Type(oldType.name() + "[" + to_string(size) + "]",
1541 Type::kArray_Kind, oldType, size);
1542 fSymbolTable->takeOwnership(newType);
1543 return std::unique_ptr<Expression>(new TypeReference(fContext, base->fPosition,
1544 *newType));
1545
1546 } else {
1547 fErrors.error(base->fPosition, "array size must be a constant");
1548 return nullptr;
1549 }
1550 }
ethannicholas5961bc92016-10-12 06:39:56 -07001551 if (base->fType.kind() != Type::kArray_Kind && base->fType.kind() != Type::kMatrix_Kind &&
1552 base->fType.kind() != Type::kVector_Kind) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001553 fErrors.error(base->fPosition, "expected array, but found '" + base->fType.description() +
ethannicholasb3058bd2016-07-01 08:22:01 -07001554 "'");
1555 return nullptr;
1556 }
1557 std::unique_ptr<Expression> converted = this->convertExpression(index);
1558 if (!converted) {
1559 return nullptr;
1560 }
ethannicholas5961bc92016-10-12 06:39:56 -07001561 if (converted->fType != *fContext.fUInt_Type) {
1562 converted = this->coerce(std::move(converted), *fContext.fInt_Type);
1563 if (!converted) {
1564 return nullptr;
1565 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001566 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001567 return std::unique_ptr<Expression>(new IndexExpression(fContext, std::move(base),
ethannicholasd598f792016-07-25 10:08:54 -07001568 std::move(converted)));
ethannicholasb3058bd2016-07-01 08:22:01 -07001569}
1570
1571std::unique_ptr<Expression> IRGenerator::convertField(std::unique_ptr<Expression> base,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001572 const String& field) {
ethannicholasd598f792016-07-25 10:08:54 -07001573 auto fields = base->fType.fields();
ethannicholasb3058bd2016-07-01 08:22:01 -07001574 for (size_t i = 0; i < fields.size(); i++) {
1575 if (fields[i].fName == field) {
1576 return std::unique_ptr<Expression>(new FieldAccess(std::move(base), (int) i));
1577 }
1578 }
ethannicholasd598f792016-07-25 10:08:54 -07001579 fErrors.error(base->fPosition, "type '" + base->fType.description() + "' does not have a "
ethannicholasb3058bd2016-07-01 08:22:01 -07001580 "field named '" + field + "");
1581 return nullptr;
1582}
1583
1584std::unique_ptr<Expression> IRGenerator::convertSwizzle(std::unique_ptr<Expression> base,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001585 const String& fields) {
ethannicholasd598f792016-07-25 10:08:54 -07001586 if (base->fType.kind() != Type::kVector_Kind) {
1587 fErrors.error(base->fPosition, "cannot swizzle type '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001588 return nullptr;
1589 }
1590 std::vector<int> swizzleComponents;
Ethan Nicholas9e1138d2016-11-21 10:39:35 -05001591 for (size_t i = 0; i < fields.size(); i++) {
1592 switch (fields[i]) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001593 case 'x': // fall through
1594 case 'r': // fall through
Ethan Nicholas11d53972016-11-28 11:23:23 -05001595 case 's':
ethannicholasb3058bd2016-07-01 08:22:01 -07001596 swizzleComponents.push_back(0);
1597 break;
1598 case 'y': // fall through
1599 case 'g': // fall through
1600 case 't':
ethannicholasd598f792016-07-25 10:08:54 -07001601 if (base->fType.columns() >= 2) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001602 swizzleComponents.push_back(1);
1603 break;
1604 }
1605 // fall through
1606 case 'z': // fall through
1607 case 'b': // fall through
Ethan Nicholas11d53972016-11-28 11:23:23 -05001608 case 'p':
ethannicholasd598f792016-07-25 10:08:54 -07001609 if (base->fType.columns() >= 3) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001610 swizzleComponents.push_back(2);
1611 break;
1612 }
1613 // fall through
1614 case 'w': // fall through
1615 case 'a': // fall through
1616 case 'q':
ethannicholasd598f792016-07-25 10:08:54 -07001617 if (base->fType.columns() >= 4) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001618 swizzleComponents.push_back(3);
1619 break;
1620 }
1621 // fall through
1622 default:
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001623 fErrors.error(base->fPosition, String::printf("invalid swizzle component '%c'",
Ethan Nicholas9e1138d2016-11-21 10:39:35 -05001624 fields[i]));
ethannicholasb3058bd2016-07-01 08:22:01 -07001625 return nullptr;
1626 }
1627 }
1628 ASSERT(swizzleComponents.size() > 0);
1629 if (swizzleComponents.size() > 4) {
1630 fErrors.error(base->fPosition, "too many components in swizzle mask '" + fields + "'");
1631 return nullptr;
1632 }
ethannicholasd598f792016-07-25 10:08:54 -07001633 return std::unique_ptr<Expression>(new Swizzle(fContext, std::move(base), swizzleComponents));
ethannicholasb3058bd2016-07-01 08:22:01 -07001634}
1635
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001636std::unique_ptr<Expression> IRGenerator::getCap(Position position, String name) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001637 auto found = fCapsMap.find(name);
1638 if (found == fCapsMap.end()) {
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001639 fErrors.error(position, "unknown capability flag '" + name + "'");
1640 return nullptr;
1641 }
1642 switch (found->second.fKind) {
1643 case CapValue::kBool_Kind:
1644 return std::unique_ptr<Expression>(new BoolLiteral(fContext, position,
1645 (bool) found->second.fValue));
1646 case CapValue::kInt_Kind:
Ethan Nicholas11d53972016-11-28 11:23:23 -05001647 return std::unique_ptr<Expression>(new IntLiteral(fContext, position,
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001648 found->second.fValue));
1649 }
1650 ASSERT(false);
1651 return nullptr;
1652}
1653
ethannicholasb3058bd2016-07-01 08:22:01 -07001654std::unique_ptr<Expression> IRGenerator::convertSuffixExpression(
1655 const ASTSuffixExpression& expression) {
1656 std::unique_ptr<Expression> base = this->convertExpression(*expression.fBase);
1657 if (!base) {
1658 return nullptr;
1659 }
1660 switch (expression.fSuffix->fKind) {
ethannicholas5961bc92016-10-12 06:39:56 -07001661 case ASTSuffix::kIndex_Kind: {
1662 const ASTExpression* expr = ((ASTIndexSuffix&) *expression.fSuffix).fExpression.get();
1663 if (expr) {
1664 return this->convertIndex(std::move(base), *expr);
1665 } else if (base->fKind == Expression::kTypeReference_Kind) {
1666 const Type& oldType = ((TypeReference&) *base).fValue;
Ethan Nicholas11d53972016-11-28 11:23:23 -05001667 Type* newType = new Type(oldType.name() + "[]", Type::kArray_Kind, oldType,
ethannicholas5961bc92016-10-12 06:39:56 -07001668 -1);
1669 fSymbolTable->takeOwnership(newType);
Ethan Nicholas11d53972016-11-28 11:23:23 -05001670 return std::unique_ptr<Expression>(new TypeReference(fContext, base->fPosition,
ethannicholas5961bc92016-10-12 06:39:56 -07001671 *newType));
1672 } else {
1673 fErrors.error(expression.fPosition, "'[]' must follow a type name");
ethannicholasa54401d2016-10-14 08:37:32 -07001674 return nullptr;
ethannicholas5961bc92016-10-12 06:39:56 -07001675 }
1676 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001677 case ASTSuffix::kCall_Kind: {
1678 auto rawArguments = &((ASTCallSuffix&) *expression.fSuffix).fArguments;
1679 std::vector<std::unique_ptr<Expression>> arguments;
1680 for (size_t i = 0; i < rawArguments->size(); i++) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001681 std::unique_ptr<Expression> converted =
ethannicholasb3058bd2016-07-01 08:22:01 -07001682 this->convertExpression(*(*rawArguments)[i]);
1683 if (!converted) {
1684 return nullptr;
1685 }
1686 arguments.push_back(std::move(converted));
1687 }
1688 return this->call(expression.fPosition, std::move(base), std::move(arguments));
1689 }
1690 case ASTSuffix::kField_Kind: {
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001691 if (base->fType == *fContext.fSkCaps_Type) {
1692 return this->getCap(expression.fPosition,
1693 ((ASTFieldSuffix&) *expression.fSuffix).fField);
1694 }
ethannicholasd598f792016-07-25 10:08:54 -07001695 switch (base->fType.kind()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001696 case Type::kVector_Kind:
Ethan Nicholas11d53972016-11-28 11:23:23 -05001697 return this->convertSwizzle(std::move(base),
ethannicholasb3058bd2016-07-01 08:22:01 -07001698 ((ASTFieldSuffix&) *expression.fSuffix).fField);
1699 case Type::kStruct_Kind:
1700 return this->convertField(std::move(base),
1701 ((ASTFieldSuffix&) *expression.fSuffix).fField);
1702 default:
Ethan Nicholas11d53972016-11-28 11:23:23 -05001703 fErrors.error(base->fPosition, "cannot swizzle value of type '" +
ethannicholasd598f792016-07-25 10:08:54 -07001704 base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001705 return nullptr;
1706 }
1707 }
1708 case ASTSuffix::kPostIncrement_Kind:
ethannicholasd598f792016-07-25 10:08:54 -07001709 if (!base->fType.isNumber()) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001710 fErrors.error(expression.fPosition,
ethannicholasd598f792016-07-25 10:08:54 -07001711 "'++' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001712 return nullptr;
1713 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001714 this->markWrittenTo(*base, true);
Ethan Nicholas11d53972016-11-28 11:23:23 -05001715 return std::unique_ptr<Expression>(new PostfixExpression(std::move(base),
ethannicholasb3058bd2016-07-01 08:22:01 -07001716 Token::PLUSPLUS));
1717 case ASTSuffix::kPostDecrement_Kind:
ethannicholasd598f792016-07-25 10:08:54 -07001718 if (!base->fType.isNumber()) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001719 fErrors.error(expression.fPosition,
ethannicholasd598f792016-07-25 10:08:54 -07001720 "'--' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001721 return nullptr;
1722 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001723 this->markWrittenTo(*base, true);
Ethan Nicholas11d53972016-11-28 11:23:23 -05001724 return std::unique_ptr<Expression>(new PostfixExpression(std::move(base),
ethannicholasb3058bd2016-07-01 08:22:01 -07001725 Token::MINUSMINUS));
1726 default:
1727 ABORT("unsupported suffix operator");
1728 }
1729}
1730
1731void IRGenerator::checkValid(const Expression& expr) {
1732 switch (expr.fKind) {
1733 case Expression::kFunctionReference_Kind:
1734 fErrors.error(expr.fPosition, "expected '(' to begin function call");
1735 break;
1736 case Expression::kTypeReference_Kind:
1737 fErrors.error(expr.fPosition, "expected '(' to begin constructor invocation");
1738 break;
1739 default:
ethannicholasea4567c2016-10-17 11:24:37 -07001740 if (expr.fType == *fContext.fInvalid_Type) {
1741 fErrors.error(expr.fPosition, "invalid expression");
1742 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001743 }
1744}
1745
ethannicholasb3058bd2016-07-01 08:22:01 -07001746static bool has_duplicates(const Swizzle& swizzle) {
1747 int bits = 0;
1748 for (int idx : swizzle.fComponents) {
1749 ASSERT(idx >= 0 && idx <= 3);
1750 int bit = 1 << idx;
1751 if (bits & bit) {
1752 return true;
1753 }
1754 bits |= bit;
1755 }
1756 return false;
1757}
1758
Ethan Nicholas86a43402017-01-19 13:32:00 -05001759void IRGenerator::markWrittenTo(const Expression& expr, bool readWrite) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001760 switch (expr.fKind) {
1761 case Expression::kVariableReference_Kind: {
ethannicholasd598f792016-07-25 10:08:54 -07001762 const Variable& var = ((VariableReference&) expr).fVariable;
ethannicholasb3058bd2016-07-01 08:22:01 -07001763 if (var.fModifiers.fFlags & (Modifiers::kConst_Flag | Modifiers::kUniform_Flag)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001764 fErrors.error(expr.fPosition,
ethannicholasb3058bd2016-07-01 08:22:01 -07001765 "cannot modify immutable variable '" + var.fName + "'");
1766 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001767 ((VariableReference&) expr).setRefKind(readWrite ? VariableReference::kReadWrite_RefKind
1768 : VariableReference::kWrite_RefKind);
ethannicholasb3058bd2016-07-01 08:22:01 -07001769 break;
1770 }
1771 case Expression::kFieldAccess_Kind:
Ethan Nicholas86a43402017-01-19 13:32:00 -05001772 this->markWrittenTo(*((FieldAccess&) expr).fBase, readWrite);
ethannicholasb3058bd2016-07-01 08:22:01 -07001773 break;
1774 case Expression::kSwizzle_Kind:
1775 if (has_duplicates((Swizzle&) expr)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001776 fErrors.error(expr.fPosition,
ethannicholasb3058bd2016-07-01 08:22:01 -07001777 "cannot write to the same swizzle field more than once");
1778 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001779 this->markWrittenTo(*((Swizzle&) expr).fBase, readWrite);
ethannicholasb3058bd2016-07-01 08:22:01 -07001780 break;
1781 case Expression::kIndex_Kind:
Ethan Nicholas86a43402017-01-19 13:32:00 -05001782 this->markWrittenTo(*((IndexExpression&) expr).fBase, readWrite);
ethannicholasb3058bd2016-07-01 08:22:01 -07001783 break;
1784 default:
1785 fErrors.error(expr.fPosition, "cannot assign to '" + expr.description() + "'");
1786 break;
1787 }
1788}
1789
1790}