blob: cfa3049a2ccb034229e98e5d42a38751ba5b4c24 [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"
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -040014#include "SkSLParser.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070015#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"
Ethan Nicholasaae47c82017-11-10 15:34:03 -050027#include "ir/SkSLEnum.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070028#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"
Ethan Nicholas762466e2017-06-29 10:03:38 -040045#include "ir/SkSLSetting.h"
Ethan Nicholasaf197692017-02-27 13:26:45 -050046#include "ir/SkSLSwitchCase.h"
47#include "ir/SkSLSwitchStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070048#include "ir/SkSLSwizzle.h"
49#include "ir/SkSLTernaryExpression.h"
50#include "ir/SkSLUnresolvedFunction.h"
51#include "ir/SkSLVariable.h"
ethannicholas22f939e2016-10-13 13:25:34 -070052#include "ir/SkSLVarDeclarations.h"
53#include "ir/SkSLVarDeclarationsStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070054#include "ir/SkSLVariableReference.h"
55#include "ir/SkSLWhileStatement.h"
56
57namespace SkSL {
58
59class AutoSymbolTable {
60public:
Ethan Nicholas11d53972016-11-28 11:23:23 -050061 AutoSymbolTable(IRGenerator* ir)
ethannicholasb3058bd2016-07-01 08:22:01 -070062 : fIR(ir)
63 , fPrevious(fIR->fSymbolTable) {
64 fIR->pushSymbolTable();
65 }
66
67 ~AutoSymbolTable() {
68 fIR->popSymbolTable();
69 ASSERT(fPrevious == fIR->fSymbolTable);
70 }
71
72 IRGenerator* fIR;
73 std::shared_ptr<SymbolTable> fPrevious;
74};
75
ethannicholas22f939e2016-10-13 13:25:34 -070076class AutoLoopLevel {
77public:
Ethan Nicholas11d53972016-11-28 11:23:23 -050078 AutoLoopLevel(IRGenerator* ir)
ethannicholas22f939e2016-10-13 13:25:34 -070079 : fIR(ir) {
80 fIR->fLoopLevel++;
81 }
82
83 ~AutoLoopLevel() {
84 fIR->fLoopLevel--;
85 }
86
87 IRGenerator* fIR;
88};
89
Ethan Nicholasaf197692017-02-27 13:26:45 -050090class AutoSwitchLevel {
91public:
92 AutoSwitchLevel(IRGenerator* ir)
93 : fIR(ir) {
94 fIR->fSwitchLevel++;
95 }
96
97 ~AutoSwitchLevel() {
98 fIR->fSwitchLevel--;
99 }
100
101 IRGenerator* fIR;
102};
103
Ethan Nicholas11d53972016-11-28 11:23:23 -0500104IRGenerator::IRGenerator(const Context* context, std::shared_ptr<SymbolTable> symbolTable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700105 ErrorReporter& errorReporter)
ethannicholasd598f792016-07-25 10:08:54 -0700106: fContext(*context)
107, fCurrentFunction(nullptr)
Ethan Nicholas762466e2017-06-29 10:03:38 -0400108, fRootSymbolTable(symbolTable)
109, fSymbolTable(symbolTable)
ethannicholas22f939e2016-10-13 13:25:34 -0700110, fLoopLevel(0)
Ethan Nicholasaf197692017-02-27 13:26:45 -0500111, fSwitchLevel(0)
Ethan Nicholas762466e2017-06-29 10:03:38 -0400112, fTmpCount(0)
ethannicholasd598f792016-07-25 10:08:54 -0700113, fErrors(errorReporter) {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700114
115void IRGenerator::pushSymbolTable() {
Ethan Nicholas8feeff92017-03-30 14:11:58 -0400116 fSymbolTable.reset(new SymbolTable(std::move(fSymbolTable), &fErrors));
ethannicholasb3058bd2016-07-01 08:22:01 -0700117}
118
119void IRGenerator::popSymbolTable() {
120 fSymbolTable = fSymbolTable->fParent;
121}
122
Ethan Nicholas762466e2017-06-29 10:03:38 -0400123static 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())));
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500127 CAP(fbFetchSupport);
128 CAP(fbFetchNeedsCustomOutput);
129 CAP(bindlessTextureSupport);
130 CAP(dropsTileOnZeroDivide);
131 CAP(flatInterpolationSupport);
132 CAP(noperspectiveInterpolationSupport);
133 CAP(multisampleInterpolationSupport);
134 CAP(sampleVariablesSupport);
135 CAP(sampleMaskOverrideCoverageSupport);
136 CAP(externalTextureSupport);
137 CAP(texelFetchSupport);
138 CAP(imageLoadStoreSupport);
139 CAP(mustEnableAdvBlendEqs);
140 CAP(mustEnableSpecificAdvBlendEqs);
141 CAP(mustDeclareFragmentShaderOutput);
142 CAP(canUseAnyFunctionInShader);
Chris Dalton47c8ed32017-11-15 18:27:09 -0700143 CAP(floatIs32Bits);
Ethan Nicholas07990de2017-07-18 09:47:43 -0400144 CAP(integerSupport);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500145#undef CAP
146}
147
148void IRGenerator::start(const Program::Settings* settings) {
149 fSettings = settings;
150 fCapsMap.clear();
151 if (settings->fCaps) {
152 fill_caps(*settings->fCaps, &fCapsMap);
153 }
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500154 this->pushSymbolTable();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400155 fInvocations = -1;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500156 fInputs.reset();
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500157}
158
159void IRGenerator::finish() {
160 this->popSymbolTable();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500161 fSettings = nullptr;
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500162}
163
ethannicholasb3058bd2016-07-01 08:22:01 -0700164std::unique_ptr<Extension> IRGenerator::convertExtension(const ASTExtension& extension) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700165 return std::unique_ptr<Extension>(new Extension(extension.fOffset, extension.fName));
ethannicholasb3058bd2016-07-01 08:22:01 -0700166}
167
168std::unique_ptr<Statement> IRGenerator::convertStatement(const ASTStatement& statement) {
169 switch (statement.fKind) {
170 case ASTStatement::kBlock_Kind:
171 return this->convertBlock((ASTBlock&) statement);
172 case ASTStatement::kVarDeclaration_Kind:
173 return this->convertVarDeclarationStatement((ASTVarDeclarationStatement&) statement);
174 case ASTStatement::kExpression_Kind:
175 return this->convertExpressionStatement((ASTExpressionStatement&) statement);
176 case ASTStatement::kIf_Kind:
177 return this->convertIf((ASTIfStatement&) statement);
178 case ASTStatement::kFor_Kind:
179 return this->convertFor((ASTForStatement&) statement);
180 case ASTStatement::kWhile_Kind:
181 return this->convertWhile((ASTWhileStatement&) statement);
182 case ASTStatement::kDo_Kind:
183 return this->convertDo((ASTDoStatement&) statement);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500184 case ASTStatement::kSwitch_Kind:
185 return this->convertSwitch((ASTSwitchStatement&) statement);
ethannicholasb3058bd2016-07-01 08:22:01 -0700186 case ASTStatement::kReturn_Kind:
187 return this->convertReturn((ASTReturnStatement&) statement);
188 case ASTStatement::kBreak_Kind:
189 return this->convertBreak((ASTBreakStatement&) statement);
190 case ASTStatement::kContinue_Kind:
191 return this->convertContinue((ASTContinueStatement&) statement);
192 case ASTStatement::kDiscard_Kind:
193 return this->convertDiscard((ASTDiscardStatement&) statement);
194 default:
195 ABORT("unsupported statement type: %d\n", statement.fKind);
196 }
197}
198
199std::unique_ptr<Block> IRGenerator::convertBlock(const ASTBlock& block) {
200 AutoSymbolTable table(this);
201 std::vector<std::unique_ptr<Statement>> statements;
202 for (size_t i = 0; i < block.fStatements.size(); i++) {
203 std::unique_ptr<Statement> statement = this->convertStatement(*block.fStatements[i]);
204 if (!statement) {
205 return nullptr;
206 }
207 statements.push_back(std::move(statement));
208 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700209 return std::unique_ptr<Block>(new Block(block.fOffset, std::move(statements), fSymbolTable));
ethannicholasb3058bd2016-07-01 08:22:01 -0700210}
211
212std::unique_ptr<Statement> IRGenerator::convertVarDeclarationStatement(
213 const ASTVarDeclarationStatement& s) {
ethannicholas14fe8cc2016-09-07 13:37:16 -0700214 auto decl = this->convertVarDeclarations(*s.fDeclarations, Variable::kLocal_Storage);
ethannicholasb3058bd2016-07-01 08:22:01 -0700215 if (!decl) {
216 return nullptr;
217 }
ethannicholas14fe8cc2016-09-07 13:37:16 -0700218 return std::unique_ptr<Statement>(new VarDeclarationsStatement(std::move(decl)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700219}
220
ethannicholas14fe8cc2016-09-07 13:37:16 -0700221std::unique_ptr<VarDeclarations> IRGenerator::convertVarDeclarations(const ASTVarDeclarations& decl,
222 Variable::Storage storage) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000223 std::vector<std::unique_ptr<VarDeclaration>> variables;
ethannicholasd598f792016-07-25 10:08:54 -0700224 const Type* baseType = this->convertType(*decl.fType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700225 if (!baseType) {
226 return nullptr;
227 }
ethannicholas14fe8cc2016-09-07 13:37:16 -0700228 for (const auto& varDecl : decl.fVars) {
ethannicholasd598f792016-07-25 10:08:54 -0700229 const Type* type = baseType;
ethannicholas14fe8cc2016-09-07 13:37:16 -0700230 std::vector<std::unique_ptr<Expression>> sizes;
231 for (const auto& rawSize : varDecl.fSizes) {
232 if (rawSize) {
233 auto size = this->coerce(this->convertExpression(*rawSize), *fContext.fInt_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700234 if (!size) {
235 return nullptr;
236 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700237 String name(type->fName);
Ethan Nicholas50afc172017-02-16 14:49:57 -0500238 int64_t count;
ethannicholasb3058bd2016-07-01 08:22:01 -0700239 if (size->fKind == Expression::kIntLiteral_Kind) {
240 count = ((IntLiteral&) *size).fValue;
241 if (count <= 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700242 fErrors.error(size->fOffset, "array size must be positive");
ethannicholasb3058bd2016-07-01 08:22:01 -0700243 }
244 name += "[" + to_string(count) + "]";
245 } else {
246 count = -1;
247 name += "[]";
248 }
ethannicholasd598f792016-07-25 10:08:54 -0700249 type = new Type(name, Type::kArray_Kind, *type, (int) count);
250 fSymbolTable->takeOwnership((Type*) type);
ethannicholas14fe8cc2016-09-07 13:37:16 -0700251 sizes.push_back(std::move(size));
ethannicholasb3058bd2016-07-01 08:22:01 -0700252 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700253 type = new Type(type->name() + "[]", Type::kArray_Kind, *type, -1);
ethannicholasd598f792016-07-25 10:08:54 -0700254 fSymbolTable->takeOwnership((Type*) type);
ethannicholas14fe8cc2016-09-07 13:37:16 -0700255 sizes.push_back(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700256 }
257 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000258 auto var = std::unique_ptr<Variable>(new Variable(decl.fOffset, decl.fModifiers,
259 varDecl.fName, *type, storage));
ethannicholasb3058bd2016-07-01 08:22:01 -0700260 std::unique_ptr<Expression> value;
ethannicholas14fe8cc2016-09-07 13:37:16 -0700261 if (varDecl.fValue) {
262 value = this->convertExpression(*varDecl.fValue);
ethannicholasb3058bd2016-07-01 08:22:01 -0700263 if (!value) {
264 return nullptr;
265 }
ethannicholasd598f792016-07-25 10:08:54 -0700266 value = this->coerce(std::move(value), *type);
Ethan Nicholascb670962017-04-20 19:31:52 -0400267 var->fWriteCount = 1;
ethannicholasb3058bd2016-07-01 08:22:01 -0700268 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700269 if (storage == Variable::kGlobal_Storage && varDecl.fName == "sk_FragColor" &&
ethannicholasea4567c2016-10-17 11:24:37 -0700270 (*fSymbolTable)[varDecl.fName]) {
ethannicholas5961bc92016-10-12 06:39:56 -0700271 // already defined, ignore
ethannicholasea4567c2016-10-17 11:24:37 -0700272 } else if (storage == Variable::kGlobal_Storage && (*fSymbolTable)[varDecl.fName] &&
273 (*fSymbolTable)[varDecl.fName]->fKind == Symbol::kVariable_Kind &&
ethannicholas5961bc92016-10-12 06:39:56 -0700274 ((Variable*) (*fSymbolTable)[varDecl.fName])->fModifiers.fLayout.fBuiltin >= 0) {
ethannicholasf789b382016-08-03 12:43:36 -0700275 // already defined, just update the modifiers
ethannicholas14fe8cc2016-09-07 13:37:16 -0700276 Variable* old = (Variable*) (*fSymbolTable)[varDecl.fName];
ethannicholasf789b382016-08-03 12:43:36 -0700277 old->fModifiers = var->fModifiers;
278 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000279 variables.emplace_back(new VarDeclaration(var.get(), std::move(sizes),
280 std::move(value)));
ethannicholas14fe8cc2016-09-07 13:37:16 -0700281 fSymbolTable->add(varDecl.fName, std::move(var));
ethannicholasf789b382016-08-03 12:43:36 -0700282 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700283 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700284 return std::unique_ptr<VarDeclarations>(new VarDeclarations(decl.fOffset,
ethannicholas14fe8cc2016-09-07 13:37:16 -0700285 baseType,
286 std::move(variables)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700287}
288
ethannicholas5961bc92016-10-12 06:39:56 -0700289std::unique_ptr<ModifiersDeclaration> IRGenerator::convertModifiersDeclaration(
290 const ASTModifiersDeclaration& m) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400291 Modifiers modifiers = m.fModifiers;
292 if (modifiers.fLayout.fInvocations != -1) {
293 fInvocations = modifiers.fLayout.fInvocations;
Chris Daltonf1b47bb2017-10-06 11:57:51 -0600294 if (fSettings->fCaps && !fSettings->fCaps->gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400295 modifiers.fLayout.fInvocations = -1;
296 Variable* invocationId = (Variable*) (*fSymbolTable)["sk_InvocationID"];
297 ASSERT(invocationId);
298 invocationId->fModifiers.fLayout.fBuiltin = -1;
299 if (modifiers.fLayout.description() == "") {
300 return nullptr;
301 }
302 }
303 }
304 if (modifiers.fLayout.fMaxVertices != -1 && fInvocations > 0 && fSettings->fCaps &&
Chris Daltonf1b47bb2017-10-06 11:57:51 -0600305 !fSettings->fCaps->gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400306 modifiers.fLayout.fMaxVertices *= fInvocations;
307 }
308 return std::unique_ptr<ModifiersDeclaration>(new ModifiersDeclaration(modifiers));
ethannicholas5961bc92016-10-12 06:39:56 -0700309}
310
ethannicholasb3058bd2016-07-01 08:22:01 -0700311std::unique_ptr<Statement> IRGenerator::convertIf(const ASTIfStatement& s) {
Ethan Nicholas11d53972016-11-28 11:23:23 -0500312 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*s.fTest),
ethannicholasd598f792016-07-25 10:08:54 -0700313 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700314 if (!test) {
315 return nullptr;
316 }
317 std::unique_ptr<Statement> ifTrue = this->convertStatement(*s.fIfTrue);
318 if (!ifTrue) {
319 return nullptr;
320 }
321 std::unique_ptr<Statement> ifFalse;
322 if (s.fIfFalse) {
323 ifFalse = this->convertStatement(*s.fIfFalse);
324 if (!ifFalse) {
325 return nullptr;
326 }
327 }
ethannicholas08a92112016-11-09 13:26:45 -0800328 if (test->fKind == Expression::kBoolLiteral_Kind) {
329 // static boolean value, fold down to a single branch
330 if (((BoolLiteral&) *test).fValue) {
331 return ifTrue;
332 } else if (s.fIfFalse) {
333 return ifFalse;
334 } else {
335 // False & no else clause. Not an error, so don't return null!
336 std::vector<std::unique_ptr<Statement>> empty;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700337 return std::unique_ptr<Statement>(new Block(s.fOffset, std::move(empty),
ethannicholas08a92112016-11-09 13:26:45 -0800338 fSymbolTable));
339 }
340 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700341 return std::unique_ptr<Statement>(new IfStatement(s.fOffset, s.fIsStatic, std::move(test),
ethannicholasb3058bd2016-07-01 08:22:01 -0700342 std::move(ifTrue), std::move(ifFalse)));
343}
344
345std::unique_ptr<Statement> IRGenerator::convertFor(const ASTForStatement& f) {
ethannicholas22f939e2016-10-13 13:25:34 -0700346 AutoLoopLevel level(this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700347 AutoSymbolTable table(this);
ethannicholas22f939e2016-10-13 13:25:34 -0700348 std::unique_ptr<Statement> initializer;
349 if (f.fInitializer) {
350 initializer = this->convertStatement(*f.fInitializer);
351 if (!initializer) {
352 return nullptr;
353 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700354 }
ethannicholas22f939e2016-10-13 13:25:34 -0700355 std::unique_ptr<Expression> test;
356 if (f.fTest) {
357 test = this->coerce(this->convertExpression(*f.fTest), *fContext.fBool_Type);
358 if (!test) {
359 return nullptr;
360 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700361 }
ethannicholas22f939e2016-10-13 13:25:34 -0700362 std::unique_ptr<Expression> next;
363 if (f.fNext) {
364 next = this->convertExpression(*f.fNext);
365 if (!next) {
366 return nullptr;
367 }
368 this->checkValid(*next);
ethannicholasb3058bd2016-07-01 08:22:01 -0700369 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700370 std::unique_ptr<Statement> statement = this->convertStatement(*f.fStatement);
371 if (!statement) {
372 return nullptr;
373 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700374 return std::unique_ptr<Statement>(new ForStatement(f.fOffset, std::move(initializer),
ethannicholasb3058bd2016-07-01 08:22:01 -0700375 std::move(test), std::move(next),
ethannicholasd598f792016-07-25 10:08:54 -0700376 std::move(statement), fSymbolTable));
ethannicholasb3058bd2016-07-01 08:22:01 -0700377}
378
379std::unique_ptr<Statement> IRGenerator::convertWhile(const ASTWhileStatement& w) {
ethannicholas22f939e2016-10-13 13:25:34 -0700380 AutoLoopLevel level(this);
Ethan Nicholas11d53972016-11-28 11:23:23 -0500381 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*w.fTest),
ethannicholasd598f792016-07-25 10:08:54 -0700382 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700383 if (!test) {
384 return nullptr;
385 }
386 std::unique_ptr<Statement> statement = this->convertStatement(*w.fStatement);
387 if (!statement) {
388 return nullptr;
389 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700390 return std::unique_ptr<Statement>(new WhileStatement(w.fOffset, std::move(test),
ethannicholasb3058bd2016-07-01 08:22:01 -0700391 std::move(statement)));
392}
393
394std::unique_ptr<Statement> IRGenerator::convertDo(const ASTDoStatement& d) {
ethannicholas22f939e2016-10-13 13:25:34 -0700395 AutoLoopLevel level(this);
ethannicholasd598f792016-07-25 10:08:54 -0700396 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*d.fTest),
397 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700398 if (!test) {
399 return nullptr;
400 }
401 std::unique_ptr<Statement> statement = this->convertStatement(*d.fStatement);
402 if (!statement) {
403 return nullptr;
404 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700405 return std::unique_ptr<Statement>(new DoStatement(d.fOffset, std::move(statement),
ethannicholasb3058bd2016-07-01 08:22:01 -0700406 std::move(test)));
407}
408
Ethan Nicholasaf197692017-02-27 13:26:45 -0500409std::unique_ptr<Statement> IRGenerator::convertSwitch(const ASTSwitchStatement& s) {
410 AutoSwitchLevel level(this);
411 std::unique_ptr<Expression> value = this->convertExpression(*s.fValue);
412 if (!value) {
413 return nullptr;
414 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500415 if (value->fType != *fContext.fUInt_Type && value->fType.kind() != Type::kEnum_Kind) {
Ethan Nicholasaf197692017-02-27 13:26:45 -0500416 value = this->coerce(std::move(value), *fContext.fInt_Type);
417 if (!value) {
418 return nullptr;
419 }
420 }
421 AutoSymbolTable table(this);
422 std::unordered_set<int> caseValues;
423 std::vector<std::unique_ptr<SwitchCase>> cases;
424 for (const auto& c : s.fCases) {
425 std::unique_ptr<Expression> caseValue;
426 if (c->fValue) {
427 caseValue = this->convertExpression(*c->fValue);
428 if (!caseValue) {
429 return nullptr;
430 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500431 caseValue = this->coerce(std::move(caseValue), value->fType);
432 if (!caseValue) {
433 return nullptr;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500434 }
435 if (!caseValue->isConstant()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700436 fErrors.error(caseValue->fOffset, "case value must be a constant");
Ethan Nicholasaf197692017-02-27 13:26:45 -0500437 return nullptr;
438 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500439 int64_t v;
440 this->getConstantInt(*caseValue, &v);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500441 if (caseValues.find(v) != caseValues.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700442 fErrors.error(caseValue->fOffset, "duplicate case value");
Ethan Nicholasaf197692017-02-27 13:26:45 -0500443 }
444 caseValues.insert(v);
445 }
446 std::vector<std::unique_ptr<Statement>> statements;
447 for (const auto& s : c->fStatements) {
448 std::unique_ptr<Statement> converted = this->convertStatement(*s);
449 if (!converted) {
450 return nullptr;
451 }
452 statements.push_back(std::move(converted));
453 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700454 cases.emplace_back(new SwitchCase(c->fOffset, std::move(caseValue),
Ethan Nicholasaf197692017-02-27 13:26:45 -0500455 std::move(statements)));
456 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700457 return std::unique_ptr<Statement>(new SwitchStatement(s.fOffset, s.fIsStatic,
Ethan Nicholasc432b0c2017-07-18 13:22:37 -0400458 std::move(value), std::move(cases),
459 fSymbolTable));
Ethan Nicholasaf197692017-02-27 13:26:45 -0500460}
461
ethannicholasb3058bd2016-07-01 08:22:01 -0700462std::unique_ptr<Statement> IRGenerator::convertExpressionStatement(
463 const ASTExpressionStatement& s) {
464 std::unique_ptr<Expression> e = this->convertExpression(*s.fExpression);
465 if (!e) {
466 return nullptr;
467 }
468 this->checkValid(*e);
469 return std::unique_ptr<Statement>(new ExpressionStatement(std::move(e)));
470}
471
472std::unique_ptr<Statement> IRGenerator::convertReturn(const ASTReturnStatement& r) {
473 ASSERT(fCurrentFunction);
474 if (r.fExpression) {
475 std::unique_ptr<Expression> result = this->convertExpression(*r.fExpression);
476 if (!result) {
477 return nullptr;
478 }
ethannicholasd598f792016-07-25 10:08:54 -0700479 if (fCurrentFunction->fReturnType == *fContext.fVoid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700480 fErrors.error(result->fOffset, "may not return a value from a void function");
ethannicholasb3058bd2016-07-01 08:22:01 -0700481 } else {
482 result = this->coerce(std::move(result), fCurrentFunction->fReturnType);
483 if (!result) {
484 return nullptr;
485 }
486 }
487 return std::unique_ptr<Statement>(new ReturnStatement(std::move(result)));
488 } else {
ethannicholasd598f792016-07-25 10:08:54 -0700489 if (fCurrentFunction->fReturnType != *fContext.fVoid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700490 fErrors.error(r.fOffset, "expected function to return '" +
491 fCurrentFunction->fReturnType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -0700492 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700493 return std::unique_ptr<Statement>(new ReturnStatement(r.fOffset));
ethannicholasb3058bd2016-07-01 08:22:01 -0700494 }
495}
496
497std::unique_ptr<Statement> IRGenerator::convertBreak(const ASTBreakStatement& b) {
Ethan Nicholasaf197692017-02-27 13:26:45 -0500498 if (fLoopLevel > 0 || fSwitchLevel > 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700499 return std::unique_ptr<Statement>(new BreakStatement(b.fOffset));
ethannicholas22f939e2016-10-13 13:25:34 -0700500 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700501 fErrors.error(b.fOffset, "break statement must be inside a loop or switch");
ethannicholas22f939e2016-10-13 13:25:34 -0700502 return nullptr;
503 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700504}
505
506std::unique_ptr<Statement> IRGenerator::convertContinue(const ASTContinueStatement& c) {
ethannicholas22f939e2016-10-13 13:25:34 -0700507 if (fLoopLevel > 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700508 return std::unique_ptr<Statement>(new ContinueStatement(c.fOffset));
ethannicholas22f939e2016-10-13 13:25:34 -0700509 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700510 fErrors.error(c.fOffset, "continue statement must be inside a loop");
ethannicholas22f939e2016-10-13 13:25:34 -0700511 return nullptr;
512 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700513}
514
515std::unique_ptr<Statement> IRGenerator::convertDiscard(const ASTDiscardStatement& d) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700516 return std::unique_ptr<Statement>(new DiscardStatement(d.fOffset));
ethannicholasb3058bd2016-07-01 08:22:01 -0700517}
518
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500519std::unique_ptr<Block> IRGenerator::applyInvocationIDWorkaround(std::unique_ptr<Block> main) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400520 Layout invokeLayout;
521 Modifiers invokeModifiers(invokeLayout, Modifiers::kHasSideEffects_Flag);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700522 FunctionDeclaration* invokeDecl = new FunctionDeclaration(-1,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400523 invokeModifiers,
524 "_invoke",
525 std::vector<const Variable*>(),
526 *fContext.fVoid_Type);
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500527 fProgramElements->push_back(std::unique_ptr<ProgramElement>(
528 new FunctionDefinition(-1, *invokeDecl, std::move(main))));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400529 fSymbolTable->add(invokeDecl->fName, std::unique_ptr<FunctionDeclaration>(invokeDecl));
530
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000531 std::vector<std::unique_ptr<VarDeclaration>> variables;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400532 Variable* loopIdx = (Variable*) (*fSymbolTable)["sk_InvocationID"];
533 ASSERT(loopIdx);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700534 std::unique_ptr<Expression> test(new BinaryExpression(-1,
535 std::unique_ptr<Expression>(new VariableReference(-1, *loopIdx)),
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400536 Token::LT,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700537 std::unique_ptr<IntLiteral>(new IntLiteral(fContext, -1, fInvocations)),
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400538 *fContext.fBool_Type));
539 std::unique_ptr<Expression> next(new PostfixExpression(
540 std::unique_ptr<Expression>(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700541 new VariableReference(-1,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400542 *loopIdx,
543 VariableReference::kReadWrite_RefKind)),
544 Token::PLUSPLUS));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700545 ASTIdentifier endPrimitiveID = ASTIdentifier(-1, "EndPrimitive");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400546 std::unique_ptr<Expression> endPrimitive = this->convertExpression(endPrimitiveID);
547 ASSERT(endPrimitive);
548
549 std::vector<std::unique_ptr<Statement>> loopBody;
550 std::vector<std::unique_ptr<Expression>> invokeArgs;
551 loopBody.push_back(std::unique_ptr<Statement>(new ExpressionStatement(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700552 this->call(-1,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400553 *invokeDecl,
554 std::vector<std::unique_ptr<Expression>>()))));
555 loopBody.push_back(std::unique_ptr<Statement>(new ExpressionStatement(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700556 this->call(-1,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400557 std::move(endPrimitive),
558 std::vector<std::unique_ptr<Expression>>()))));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700559 std::unique_ptr<Expression> assignment(new BinaryExpression(-1,
560 std::unique_ptr<Expression>(new VariableReference(-1, *loopIdx)),
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400561 Token::EQ,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700562 std::unique_ptr<IntLiteral>(new IntLiteral(fContext, -1, 0)),
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400563 *fContext.fInt_Type));
564 std::unique_ptr<Statement> initializer(new ExpressionStatement(std::move(assignment)));
565 std::unique_ptr<Statement> loop = std::unique_ptr<Statement>(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700566 new ForStatement(-1,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400567 std::move(initializer),
568 std::move(test),
569 std::move(next),
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700570 std::unique_ptr<Block>(new Block(-1, std::move(loopBody))),
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400571 fSymbolTable));
572 std::vector<std::unique_ptr<Statement>> children;
573 children.push_back(std::move(loop));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700574 return std::unique_ptr<Block>(new Block(-1, std::move(children)));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400575}
576
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500577void IRGenerator::convertFunction(const ASTFunction& f) {
ethannicholasd598f792016-07-25 10:08:54 -0700578 const Type* returnType = this->convertType(*f.fReturnType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700579 if (!returnType) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400580 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700581 }
ethannicholasd598f792016-07-25 10:08:54 -0700582 std::vector<const Variable*> parameters;
ethannicholasb3058bd2016-07-01 08:22:01 -0700583 for (const auto& param : f.fParameters) {
ethannicholasd598f792016-07-25 10:08:54 -0700584 const Type* type = this->convertType(*param->fType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700585 if (!type) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400586 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700587 }
588 for (int j = (int) param->fSizes.size() - 1; j >= 0; j--) {
589 int size = param->fSizes[j];
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400590 String name = type->name() + "[" + to_string(size) + "]";
ethannicholasd598f792016-07-25 10:08:54 -0700591 Type* newType = new Type(std::move(name), Type::kArray_Kind, *type, size);
592 fSymbolTable->takeOwnership(newType);
593 type = newType;
ethannicholasb3058bd2016-07-01 08:22:01 -0700594 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700595 StringFragment name = param->fName;
596 Variable* var = new Variable(param->fOffset, param->fModifiers, name, *type,
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000597 Variable::kParameter_Storage);
ethannicholasd598f792016-07-25 10:08:54 -0700598 fSymbolTable->takeOwnership(var);
599 parameters.push_back(var);
ethannicholasb3058bd2016-07-01 08:22:01 -0700600 }
601
602 // find existing declaration
ethannicholasd598f792016-07-25 10:08:54 -0700603 const FunctionDeclaration* decl = nullptr;
604 auto entry = (*fSymbolTable)[f.fName];
ethannicholasb3058bd2016-07-01 08:22:01 -0700605 if (entry) {
ethannicholasd598f792016-07-25 10:08:54 -0700606 std::vector<const FunctionDeclaration*> functions;
ethannicholasb3058bd2016-07-01 08:22:01 -0700607 switch (entry->fKind) {
608 case Symbol::kUnresolvedFunction_Kind:
ethannicholasd598f792016-07-25 10:08:54 -0700609 functions = ((UnresolvedFunction*) entry)->fFunctions;
ethannicholasb3058bd2016-07-01 08:22:01 -0700610 break;
611 case Symbol::kFunctionDeclaration_Kind:
ethannicholasd598f792016-07-25 10:08:54 -0700612 functions.push_back((FunctionDeclaration*) entry);
ethannicholasb3058bd2016-07-01 08:22:01 -0700613 break;
614 default:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700615 fErrors.error(f.fOffset, "symbol '" + f.fName + "' was already defined");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400616 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700617 }
618 for (const auto& other : functions) {
619 ASSERT(other->fName == f.fName);
620 if (parameters.size() == other->fParameters.size()) {
621 bool match = true;
622 for (size_t i = 0; i < parameters.size(); i++) {
623 if (parameters[i]->fType != other->fParameters[i]->fType) {
624 match = false;
625 break;
626 }
627 }
628 if (match) {
ethannicholasd598f792016-07-25 10:08:54 -0700629 if (*returnType != other->fReturnType) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700630 FunctionDeclaration newDecl(f.fOffset, f.fModifiers, f.fName, parameters,
Ethan Nicholascb670962017-04-20 19:31:52 -0400631 *returnType);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700632 fErrors.error(f.fOffset, "functions '" + newDecl.description() +
633 "' and '" + other->description() +
634 "' differ only in return type");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400635 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700636 }
637 decl = other;
638 for (size_t i = 0; i < parameters.size(); i++) {
639 if (parameters[i]->fModifiers != other->fParameters[i]->fModifiers) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700640 fErrors.error(f.fOffset, "modifiers on parameter " +
641 to_string((uint64_t) i + 1) +
642 " differ between declaration and "
643 "definition");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400644 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700645 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700646 }
647 if (other->fDefined) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700648 fErrors.error(f.fOffset, "duplicate definition of " +
649 other->description());
ethannicholasb3058bd2016-07-01 08:22:01 -0700650 }
651 break;
652 }
653 }
654 }
655 }
656 if (!decl) {
657 // couldn't find an existing declaration
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700658 auto newDecl = std::unique_ptr<FunctionDeclaration>(new FunctionDeclaration(f.fOffset,
Ethan Nicholascb670962017-04-20 19:31:52 -0400659 f.fModifiers,
ethannicholas471e8942016-10-28 09:02:46 -0700660 f.fName,
661 parameters,
662 *returnType));
663 decl = newDecl.get();
664 fSymbolTable->add(decl->fName, std::move(newDecl));
ethannicholasb3058bd2016-07-01 08:22:01 -0700665 }
ethannicholasd598f792016-07-25 10:08:54 -0700666 if (f.fBody) {
667 ASSERT(!fCurrentFunction);
668 fCurrentFunction = decl;
669 decl->fDefined = true;
670 std::shared_ptr<SymbolTable> old = fSymbolTable;
671 AutoSymbolTable table(this);
672 for (size_t i = 0; i < parameters.size(); i++) {
673 fSymbolTable->addWithoutOwnership(parameters[i]->fName, decl->fParameters[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -0700674 }
Chris Daltonf1b47bb2017-10-06 11:57:51 -0600675 bool needInvocationIDWorkaround = fInvocations != -1 && f.fName == "main" &&
676 fSettings->fCaps &&
677 !fSettings->fCaps->gsInvocationsSupport();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400678 ASSERT(!fExtraVars.size());
ethannicholasd598f792016-07-25 10:08:54 -0700679 std::unique_ptr<Block> body = this->convertBlock(*f.fBody);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400680 for (auto& v : fExtraVars) {
681 body->fStatements.insert(body->fStatements.begin(), std::move(v));
682 }
683 fExtraVars.clear();
ethannicholasd598f792016-07-25 10:08:54 -0700684 fCurrentFunction = nullptr;
685 if (!body) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400686 return;
687 }
688 if (needInvocationIDWorkaround) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500689 body = this->applyInvocationIDWorkaround(std::move(body));
ethannicholasd598f792016-07-25 10:08:54 -0700690 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400691 // conservatively assume all user-defined functions have side effects
692 ((Modifiers&) decl->fModifiers).fFlags |= Modifiers::kHasSideEffects_Flag;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400693
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500694 fProgramElements->push_back(std::unique_ptr<FunctionDefinition>(
695 new FunctionDefinition(f.fOffset, *decl, std::move(body))));
ethannicholasb3058bd2016-07-01 08:22:01 -0700696 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700697}
698
699std::unique_ptr<InterfaceBlock> IRGenerator::convertInterfaceBlock(const ASTInterfaceBlock& intf) {
700 std::shared_ptr<SymbolTable> old = fSymbolTable;
701 AutoSymbolTable table(this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700702 std::vector<Type::Field> fields;
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400703 bool haveRuntimeArray = false;
ethannicholasb3058bd2016-07-01 08:22:01 -0700704 for (size_t i = 0; i < intf.fDeclarations.size(); i++) {
ethannicholas14fe8cc2016-09-07 13:37:16 -0700705 std::unique_ptr<VarDeclarations> decl = this->convertVarDeclarations(
Ethan Nicholas11d53972016-11-28 11:23:23 -0500706 *intf.fDeclarations[i],
ethannicholasb3058bd2016-07-01 08:22:01 -0700707 Variable::kGlobal_Storage);
ethannicholas7effa7a2016-10-14 09:56:33 -0700708 if (!decl) {
709 return nullptr;
710 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000711 for (const auto& stmt : decl->fVars) {
712 VarDeclaration& vd = (VarDeclaration&) *stmt;
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400713 if (haveRuntimeArray) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000714 fErrors.error(decl->fOffset,
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400715 "only the last entry in an interface block may be a runtime-sized "
716 "array");
717 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000718 fields.push_back(Type::Field(vd.fVar->fModifiers, vd.fVar->fName,
719 &vd.fVar->fType));
720 if (vd.fValue) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700721 fErrors.error(decl->fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700722 "initializers are not permitted on interface block fields");
723 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000724 if (vd.fVar->fModifiers.fFlags & (Modifiers::kIn_Flag |
725 Modifiers::kOut_Flag |
726 Modifiers::kUniform_Flag |
727 Modifiers::kBuffer_Flag |
728 Modifiers::kConst_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700729 fErrors.error(decl->fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700730 "interface block fields may not have storage qualifiers");
731 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000732 if (vd.fVar->fType.kind() == Type::kArray_Kind &&
733 vd.fVar->fType.columns() == -1) {
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400734 haveRuntimeArray = true;
735 }
Ethan Nicholas11d53972016-11-28 11:23:23 -0500736 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700737 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700738 Type* type = new Type(intf.fOffset, intf.fTypeName, fields);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500739 old->takeOwnership(type);
Ethan Nicholas50afc172017-02-16 14:49:57 -0500740 std::vector<std::unique_ptr<Expression>> sizes;
741 for (const auto& size : intf.fSizes) {
742 if (size) {
743 std::unique_ptr<Expression> converted = this->convertExpression(*size);
744 if (!converted) {
745 return nullptr;
746 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400747 String name = type->fName;
Ethan Nicholas50afc172017-02-16 14:49:57 -0500748 int64_t count;
749 if (converted->fKind == Expression::kIntLiteral_Kind) {
750 count = ((IntLiteral&) *converted).fValue;
751 if (count <= 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700752 fErrors.error(converted->fOffset, "array size must be positive");
Ethan Nicholas50afc172017-02-16 14:49:57 -0500753 }
754 name += "[" + to_string(count) + "]";
755 } else {
756 count = -1;
757 name += "[]";
758 }
759 type = new Type(name, Type::kArray_Kind, *type, (int) count);
760 fSymbolTable->takeOwnership((Type*) type);
761 sizes.push_back(std::move(converted));
762 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700763 type = new Type(type->name() + "[]", Type::kArray_Kind, *type, -1);
Ethan Nicholas50afc172017-02-16 14:49:57 -0500764 fSymbolTable->takeOwnership((Type*) type);
765 sizes.push_back(nullptr);
766 }
767 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700768 Variable* var = new Variable(intf.fOffset, intf.fModifiers,
769 intf.fInstanceName.fLength ? intf.fInstanceName : intf.fTypeName,
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000770 *type, Variable::kGlobal_Storage);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500771 old->takeOwnership(var);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700772 if (intf.fInstanceName.fLength) {
Ethan Nicholas50afc172017-02-16 14:49:57 -0500773 old->addWithoutOwnership(intf.fInstanceName, var);
ethannicholasb3058bd2016-07-01 08:22:01 -0700774 } else {
775 for (size_t i = 0; i < fields.size(); i++) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700776 old->add(fields[i].fName, std::unique_ptr<Field>(new Field(intf.fOffset, *var,
ethannicholasd598f792016-07-25 10:08:54 -0700777 (int) i)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700778 }
779 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700780 return std::unique_ptr<InterfaceBlock>(new InterfaceBlock(intf.fOffset,
Ethan Nicholas8feeff92017-03-30 14:11:58 -0400781 var,
Ethan Nicholas50afc172017-02-16 14:49:57 -0500782 intf.fTypeName,
783 intf.fInstanceName,
784 std::move(sizes),
785 fSymbolTable));
ethannicholasb3058bd2016-07-01 08:22:01 -0700786}
787
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500788void IRGenerator::getConstantInt(const Expression& value, int64_t* out) {
789 switch (value.fKind) {
790 case Expression::kIntLiteral_Kind:
791 *out = ((const IntLiteral&) value).fValue;
792 break;
793 case Expression::kVariableReference_Kind: {
794 const Variable& var = ((VariableReference&) value).fVariable;
795 if ((var.fModifiers.fFlags & Modifiers::kConst_Flag) &&
796 var.fInitialValue) {
797 this->getConstantInt(*var.fInitialValue, out);
798 }
799 break;
800 }
801 default:
802 fErrors.error(value.fOffset, "expected a constant int");
803 }
804}
805
806void IRGenerator::convertEnum(const ASTEnum& e) {
807 std::vector<Variable*> variables;
808 int64_t currentValue = 0;
809 Layout layout;
810 ASTType enumType(e.fOffset, e.fTypeName, ASTType::kIdentifier_Kind, {});
811 const Type* type = this->convertType(enumType);
812 Modifiers modifiers(layout, Modifiers::kConst_Flag);
813 std::shared_ptr<SymbolTable> symbols(new SymbolTable(fSymbolTable, &fErrors));
814 fSymbolTable = symbols;
815 for (size_t i = 0; i < e.fNames.size(); i++) {
816 std::unique_ptr<Expression> value;
817 if (e.fValues[i]) {
818 value = this->convertExpression(*e.fValues[i]);
819 if (!value) {
820 fSymbolTable = symbols->fParent;
821 return;
822 }
823 this->getConstantInt(*value, &currentValue);
824 }
825 value = std::unique_ptr<Expression>(new IntLiteral(fContext, e.fOffset, currentValue));
826 ++currentValue;
827 auto var = std::unique_ptr<Variable>(new Variable(e.fOffset, modifiers, e.fNames[i],
828 *type, Variable::kGlobal_Storage,
829 value.get()));
830 variables.push_back(var.get());
831 symbols->add(e.fNames[i], std::move(var));
832 symbols->takeOwnership(value.release());
833 }
834 fProgramElements->push_back(std::unique_ptr<ProgramElement>(new Enum(e.fOffset, e.fTypeName,
835 symbols)));
836 fSymbolTable = symbols->fParent;
837}
838
ethannicholasd598f792016-07-25 10:08:54 -0700839const Type* IRGenerator::convertType(const ASTType& type) {
840 const Symbol* result = (*fSymbolTable)[type.fName];
ethannicholasb3058bd2016-07-01 08:22:01 -0700841 if (result && result->fKind == Symbol::kType_Kind) {
Ethan Nicholas50afc172017-02-16 14:49:57 -0500842 for (int size : type.fSizes) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700843 String name(result->fName);
844 name += "[";
Ethan Nicholas50afc172017-02-16 14:49:57 -0500845 if (size != -1) {
846 name += to_string(size);
847 }
848 name += "]";
849 result = new Type(name, Type::kArray_Kind, (const Type&) *result, size);
850 fSymbolTable->takeOwnership((Type*) result);
851 }
ethannicholasd598f792016-07-25 10:08:54 -0700852 return (const Type*) result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700853 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700854 fErrors.error(type.fOffset, "unknown type '" + type.fName + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -0700855 return nullptr;
856}
857
858std::unique_ptr<Expression> IRGenerator::convertExpression(const ASTExpression& expr) {
859 switch (expr.fKind) {
860 case ASTExpression::kIdentifier_Kind:
861 return this->convertIdentifier((ASTIdentifier&) expr);
862 case ASTExpression::kBool_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700863 return std::unique_ptr<Expression>(new BoolLiteral(fContext, expr.fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700864 ((ASTBoolLiteral&) expr).fValue));
865 case ASTExpression::kInt_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700866 return std::unique_ptr<Expression>(new IntLiteral(fContext, expr.fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700867 ((ASTIntLiteral&) expr).fValue));
868 case ASTExpression::kFloat_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700869 return std::unique_ptr<Expression>(new FloatLiteral(fContext, expr.fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700870 ((ASTFloatLiteral&) expr).fValue));
871 case ASTExpression::kBinary_Kind:
872 return this->convertBinaryExpression((ASTBinaryExpression&) expr);
873 case ASTExpression::kPrefix_Kind:
874 return this->convertPrefixExpression((ASTPrefixExpression&) expr);
875 case ASTExpression::kSuffix_Kind:
876 return this->convertSuffixExpression((ASTSuffixExpression&) expr);
877 case ASTExpression::kTernary_Kind:
878 return this->convertTernaryExpression((ASTTernaryExpression&) expr);
879 default:
880 ABORT("unsupported expression type: %d\n", expr.fKind);
881 }
882}
883
884std::unique_ptr<Expression> IRGenerator::convertIdentifier(const ASTIdentifier& identifier) {
ethannicholasd598f792016-07-25 10:08:54 -0700885 const Symbol* result = (*fSymbolTable)[identifier.fText];
ethannicholasb3058bd2016-07-01 08:22:01 -0700886 if (!result) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700887 fErrors.error(identifier.fOffset, "unknown identifier '" + identifier.fText + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -0700888 return nullptr;
889 }
890 switch (result->fKind) {
891 case Symbol::kFunctionDeclaration_Kind: {
ethannicholasd598f792016-07-25 10:08:54 -0700892 std::vector<const FunctionDeclaration*> f = {
893 (const FunctionDeclaration*) result
ethannicholasb3058bd2016-07-01 08:22:01 -0700894 };
ethannicholasd598f792016-07-25 10:08:54 -0700895 return std::unique_ptr<FunctionReference>(new FunctionReference(fContext,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700896 identifier.fOffset,
ethannicholasd598f792016-07-25 10:08:54 -0700897 f));
ethannicholasb3058bd2016-07-01 08:22:01 -0700898 }
899 case Symbol::kUnresolvedFunction_Kind: {
ethannicholasd598f792016-07-25 10:08:54 -0700900 const UnresolvedFunction* f = (const UnresolvedFunction*) result;
901 return std::unique_ptr<FunctionReference>(new FunctionReference(fContext,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700902 identifier.fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700903 f->fFunctions));
904 }
905 case Symbol::kVariable_Kind: {
Ethan Nicholas38657112017-02-09 17:01:22 -0500906 const Variable* var = (const Variable*) result;
Ethan Nicholas762466e2017-06-29 10:03:38 -0400907#ifndef SKSL_STANDALONE
Ethan Nicholas38657112017-02-09 17:01:22 -0500908 if (var->fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
909 fInputs.fFlipY = true;
910 if (fSettings->fFlipY &&
911 (!fSettings->fCaps ||
912 !fSettings->fCaps->fragCoordConventionsExtensionString())) {
913 fInputs.fRTHeight = true;
914 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500915 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400916#endif
Ethan Nicholas86a43402017-01-19 13:32:00 -0500917 // default to kRead_RefKind; this will be corrected later if the variable is written to
918 return std::unique_ptr<VariableReference>(new VariableReference(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700919 identifier.fOffset,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500920 *var,
921 VariableReference::kRead_RefKind));
ethannicholasb3058bd2016-07-01 08:22:01 -0700922 }
923 case Symbol::kField_Kind: {
ethannicholasd598f792016-07-25 10:08:54 -0700924 const Field* field = (const Field*) result;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700925 VariableReference* base = new VariableReference(identifier.fOffset, field->fOwner,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500926 VariableReference::kRead_RefKind);
ethannicholasf789b382016-08-03 12:43:36 -0700927 return std::unique_ptr<Expression>(new FieldAccess(
928 std::unique_ptr<Expression>(base),
929 field->fFieldIndex,
930 FieldAccess::kAnonymousInterfaceBlock_OwnerKind));
ethannicholasb3058bd2016-07-01 08:22:01 -0700931 }
932 case Symbol::kType_Kind: {
ethannicholasd598f792016-07-25 10:08:54 -0700933 const Type* t = (const Type*) result;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700934 return std::unique_ptr<TypeReference>(new TypeReference(fContext, identifier.fOffset,
ethannicholasd598f792016-07-25 10:08:54 -0700935 *t));
ethannicholasb3058bd2016-07-01 08:22:01 -0700936 }
937 default:
938 ABORT("unsupported symbol type %d\n", result->fKind);
939 }
Ethan Nicholasc0709392017-06-27 11:20:22 -0400940}
941
Ethan Nicholas762466e2017-06-29 10:03:38 -0400942std::unique_ptr<Section> IRGenerator::convertSection(const ASTSection& s) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700943 return std::unique_ptr<Section>(new Section(s.fOffset, s.fName, s.fArgument, s.fText));
Ethan Nicholas762466e2017-06-29 10:03:38 -0400944}
945
946
Ethan Nicholas11d53972016-11-28 11:23:23 -0500947std::unique_ptr<Expression> IRGenerator::coerce(std::unique_ptr<Expression> expr,
ethannicholasd598f792016-07-25 10:08:54 -0700948 const Type& type) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700949 if (!expr) {
950 return nullptr;
951 }
ethannicholasd598f792016-07-25 10:08:54 -0700952 if (expr->fType == type) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700953 return expr;
954 }
955 this->checkValid(*expr);
ethannicholasd598f792016-07-25 10:08:54 -0700956 if (expr->fType == *fContext.fInvalid_Type) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700957 return nullptr;
958 }
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400959 if (expr->coercionCost(type) == INT_MAX) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700960 fErrors.error(expr->fOffset, "expected '" + type.description() + "', but found '" +
ethannicholasd598f792016-07-25 10:08:54 -0700961 expr->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -0700962 return nullptr;
963 }
ethannicholasd598f792016-07-25 10:08:54 -0700964 if (type.kind() == Type::kScalar_Kind) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700965 std::vector<std::unique_ptr<Expression>> args;
966 args.push_back(std::move(expr));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700967 ASTIdentifier id(-1, type.fName);
ethannicholasb3058bd2016-07-01 08:22:01 -0700968 std::unique_ptr<Expression> ctor = this->convertIdentifier(id);
969 ASSERT(ctor);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700970 return this->call(-1, std::move(ctor), std::move(args));
ethannicholasb3058bd2016-07-01 08:22:01 -0700971 }
ethannicholas5961bc92016-10-12 06:39:56 -0700972 std::vector<std::unique_ptr<Expression>> args;
973 args.push_back(std::move(expr));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700974 return std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700975}
976
ethannicholasf789b382016-08-03 12:43:36 -0700977static bool is_matrix_multiply(const Type& left, const Type& right) {
978 if (left.kind() == Type::kMatrix_Kind) {
979 return right.kind() == Type::kMatrix_Kind || right.kind() == Type::kVector_Kind;
980 }
981 return left.kind() == Type::kVector_Kind && right.kind() == Type::kMatrix_Kind;
982}
ethannicholasea4567c2016-10-17 11:24:37 -0700983
ethannicholasb3058bd2016-07-01 08:22:01 -0700984/**
985 * Determines the operand and result types of a binary expression. Returns true if the expression is
986 * legal, false otherwise. If false, the values of the out parameters are undefined.
987 */
Ethan Nicholas11d53972016-11-28 11:23:23 -0500988static bool determine_binary_type(const Context& context,
989 Token::Kind op,
990 const Type& left,
991 const Type& right,
ethannicholasd598f792016-07-25 10:08:54 -0700992 const Type** outLeftType,
993 const Type** outRightType,
994 const Type** outResultType,
ethannicholasb3058bd2016-07-01 08:22:01 -0700995 bool tryFlipped) {
996 bool isLogical;
ethannicholasea4567c2016-10-17 11:24:37 -0700997 bool validMatrixOrVectorOp;
ethannicholasb3058bd2016-07-01 08:22:01 -0700998 switch (op) {
ethannicholasea4567c2016-10-17 11:24:37 -0700999 case Token::EQ:
1000 *outLeftType = &left;
1001 *outRightType = &left;
1002 *outResultType = &left;
1003 return right.canCoerceTo(left);
ethannicholasb3058bd2016-07-01 08:22:01 -07001004 case Token::EQEQ: // fall through
ethannicholasea4567c2016-10-17 11:24:37 -07001005 case Token::NEQ:
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001006 if (left == right) {
1007 *outLeftType = &left;
1008 *outRightType = &right;
1009 *outResultType = context.fBool_Type.get();
1010 return true;
1011 }
ethannicholasea4567c2016-10-17 11:24:37 -07001012 isLogical = true;
1013 validMatrixOrVectorOp = true;
1014 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001015 case Token::LT: // fall through
1016 case Token::GT: // fall through
1017 case Token::LTEQ: // fall through
1018 case Token::GTEQ:
1019 isLogical = true;
ethannicholasea4567c2016-10-17 11:24:37 -07001020 validMatrixOrVectorOp = false;
ethannicholasb3058bd2016-07-01 08:22:01 -07001021 break;
1022 case Token::LOGICALOR: // fall through
1023 case Token::LOGICALAND: // fall through
1024 case Token::LOGICALXOR: // fall through
1025 case Token::LOGICALOREQ: // fall through
1026 case Token::LOGICALANDEQ: // fall through
1027 case Token::LOGICALXOREQ:
ethannicholasd598f792016-07-25 10:08:54 -07001028 *outLeftType = context.fBool_Type.get();
1029 *outRightType = context.fBool_Type.get();
1030 *outResultType = context.fBool_Type.get();
Ethan Nicholas11d53972016-11-28 11:23:23 -05001031 return left.canCoerceTo(*context.fBool_Type) &&
ethannicholasd598f792016-07-25 10:08:54 -07001032 right.canCoerceTo(*context.fBool_Type);
Ethan Nicholas11d53972016-11-28 11:23:23 -05001033 case Token::STAREQ:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001034 if (left.kind() == Type::kScalar_Kind) {
1035 *outLeftType = &left;
1036 *outRightType = &left;
1037 *outResultType = &left;
1038 return right.canCoerceTo(left);
1039 }
1040 // fall through
1041 case Token::STAR:
ethannicholasf789b382016-08-03 12:43:36 -07001042 if (is_matrix_multiply(left, right)) {
1043 // determine final component type
1044 if (determine_binary_type(context, Token::STAR, left.componentType(),
1045 right.componentType(), outLeftType, outRightType,
1046 outResultType, false)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001047 *outLeftType = &(*outResultType)->toCompound(context, left.columns(),
ethannicholasf789b382016-08-03 12:43:36 -07001048 left.rows());;
Ethan Nicholas11d53972016-11-28 11:23:23 -05001049 *outRightType = &(*outResultType)->toCompound(context, right.columns(),
ethannicholasf789b382016-08-03 12:43:36 -07001050 right.rows());;
1051 int leftColumns = left.columns();
1052 int leftRows = left.rows();
1053 int rightColumns;
1054 int rightRows;
1055 if (right.kind() == Type::kVector_Kind) {
1056 // matrix * vector treats the vector as a column vector, so we need to
1057 // transpose it
1058 rightColumns = right.rows();
1059 rightRows = right.columns();
1060 ASSERT(rightColumns == 1);
1061 } else {
1062 rightColumns = right.columns();
1063 rightRows = right.rows();
1064 }
1065 if (rightColumns > 1) {
1066 *outResultType = &(*outResultType)->toCompound(context, rightColumns,
1067 leftRows);
1068 } else {
1069 // result was a column vector, transpose it back to a row
1070 *outResultType = &(*outResultType)->toCompound(context, leftRows,
1071 rightColumns);
1072 }
1073 return leftColumns == rightRows;
1074 } else {
1075 return false;
1076 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001077 }
ethannicholasea4567c2016-10-17 11:24:37 -07001078 isLogical = false;
1079 validMatrixOrVectorOp = true;
1080 break;
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001081 case Token::PLUSEQ:
1082 case Token::MINUSEQ:
1083 case Token::SLASHEQ:
1084 case Token::PERCENTEQ:
1085 case Token::SHLEQ:
1086 case Token::SHREQ:
1087 if (left.kind() == Type::kScalar_Kind) {
1088 *outLeftType = &left;
1089 *outRightType = &left;
1090 *outResultType = &left;
1091 return right.canCoerceTo(left);
1092 }
1093 // fall through
ethannicholasea4567c2016-10-17 11:24:37 -07001094 case Token::PLUS: // fall through
ethannicholasea4567c2016-10-17 11:24:37 -07001095 case Token::MINUS: // fall through
ethannicholasea4567c2016-10-17 11:24:37 -07001096 case Token::SLASH: // fall through
ethannicholasea4567c2016-10-17 11:24:37 -07001097 isLogical = false;
1098 validMatrixOrVectorOp = true;
1099 break;
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001100 case Token::COMMA:
1101 *outLeftType = &left;
1102 *outRightType = &right;
1103 *outResultType = &right;
1104 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001105 default:
1106 isLogical = false;
ethannicholasea4567c2016-10-17 11:24:37 -07001107 validMatrixOrVectorOp = false;
ethannicholasb3058bd2016-07-01 08:22:01 -07001108 }
ethannicholasea4567c2016-10-17 11:24:37 -07001109 bool isVectorOrMatrix = left.kind() == Type::kVector_Kind || left.kind() == Type::kMatrix_Kind;
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001110 if (left.kind() == Type::kScalar_Kind && right.kind() == Type::kScalar_Kind &&
1111 right.canCoerceTo(left)) {
1112 if (left.priority() > right.priority()) {
1113 *outLeftType = &left;
1114 *outRightType = &left;
1115 } else {
1116 *outLeftType = &right;
1117 *outRightType = &right;
1118 }
1119 if (isLogical) {
1120 *outResultType = context.fBool_Type.get();
1121 } else {
1122 *outResultType = &left;
1123 }
1124 return true;
1125 }
1126 if (right.canCoerceTo(left) && isVectorOrMatrix && validMatrixOrVectorOp) {
ethannicholasd598f792016-07-25 10:08:54 -07001127 *outLeftType = &left;
1128 *outRightType = &left;
ethannicholasb3058bd2016-07-01 08:22:01 -07001129 if (isLogical) {
ethannicholasd598f792016-07-25 10:08:54 -07001130 *outResultType = context.fBool_Type.get();
ethannicholasb3058bd2016-07-01 08:22:01 -07001131 } else {
ethannicholasd598f792016-07-25 10:08:54 -07001132 *outResultType = &left;
ethannicholasb3058bd2016-07-01 08:22:01 -07001133 }
1134 return true;
1135 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001136 if ((left.kind() == Type::kVector_Kind || left.kind() == Type::kMatrix_Kind) &&
ethannicholasd598f792016-07-25 10:08:54 -07001137 (right.kind() == Type::kScalar_Kind)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001138 if (determine_binary_type(context, op, left.componentType(), right, outLeftType,
ethannicholasd598f792016-07-25 10:08:54 -07001139 outRightType, outResultType, false)) {
1140 *outLeftType = &(*outLeftType)->toCompound(context, left.columns(), left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001141 if (!isLogical) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001142 *outResultType = &(*outResultType)->toCompound(context, left.columns(),
ethannicholasd598f792016-07-25 10:08:54 -07001143 left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001144 }
1145 return true;
1146 }
1147 return false;
1148 }
1149 if (tryFlipped) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001150 return determine_binary_type(context, op, right, left, outRightType, outLeftType,
ethannicholasd598f792016-07-25 10:08:54 -07001151 outResultType, false);
ethannicholasb3058bd2016-07-01 08:22:01 -07001152 }
1153 return false;
1154}
1155
ethannicholas08a92112016-11-09 13:26:45 -08001156std::unique_ptr<Expression> IRGenerator::constantFold(const Expression& left,
1157 Token::Kind op,
Ethan Nicholas86a43402017-01-19 13:32:00 -05001158 const Expression& right) const {
Ethan Nicholascb670962017-04-20 19:31:52 -04001159 if (!left.isConstant() || !right.isConstant()) {
1160 return nullptr;
1161 }
ethannicholas08a92112016-11-09 13:26:45 -08001162 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
1163 // precision to calculate the results and hope the result makes sense. The plan is to move the
1164 // Skia caps into SkSL, so we have access to all of them including the precisions of the various
1165 // types, which will let us be more intelligent about this.
Ethan Nicholas11d53972016-11-28 11:23:23 -05001166 if (left.fKind == Expression::kBoolLiteral_Kind &&
ethannicholas08a92112016-11-09 13:26:45 -08001167 right.fKind == Expression::kBoolLiteral_Kind) {
1168 bool leftVal = ((BoolLiteral&) left).fValue;
1169 bool rightVal = ((BoolLiteral&) right).fValue;
1170 bool result;
1171 switch (op) {
1172 case Token::LOGICALAND: result = leftVal && rightVal; break;
1173 case Token::LOGICALOR: result = leftVal || rightVal; break;
1174 case Token::LOGICALXOR: result = leftVal ^ rightVal; break;
1175 default: return nullptr;
1176 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001177 return std::unique_ptr<Expression>(new BoolLiteral(fContext, left.fOffset, result));
ethannicholas08a92112016-11-09 13:26:45 -08001178 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001179 #define RESULT(t, op) std::unique_ptr<Expression>(new t ## Literal(fContext, left.fOffset, \
ethannicholas08a92112016-11-09 13:26:45 -08001180 leftVal op rightVal))
1181 if (left.fKind == Expression::kIntLiteral_Kind && right.fKind == Expression::kIntLiteral_Kind) {
1182 int64_t leftVal = ((IntLiteral&) left).fValue;
1183 int64_t rightVal = ((IntLiteral&) right).fValue;
1184 switch (op) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001185 case Token::PLUS: return RESULT(Int, +);
1186 case Token::MINUS: return RESULT(Int, -);
1187 case Token::STAR: return RESULT(Int, *);
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001188 case Token::SLASH:
1189 if (rightVal) {
1190 return RESULT(Int, /);
1191 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001192 fErrors.error(right.fOffset, "division by zero");
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001193 return nullptr;
Ethan Nicholas2503ab62017-01-05 10:44:25 -05001194 case Token::PERCENT:
1195 if (rightVal) {
1196 return RESULT(Int, %);
1197 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001198 fErrors.error(right.fOffset, "division by zero");
Ethan Nicholas2503ab62017-01-05 10:44:25 -05001199 return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001200 case Token::BITWISEAND: return RESULT(Int, &);
1201 case Token::BITWISEOR: return RESULT(Int, |);
1202 case Token::BITWISEXOR: return RESULT(Int, ^);
1203 case Token::SHL: return RESULT(Int, <<);
1204 case Token::SHR: return RESULT(Int, >>);
1205 case Token::EQEQ: return RESULT(Bool, ==);
1206 case Token::NEQ: return RESULT(Bool, !=);
1207 case Token::GT: return RESULT(Bool, >);
1208 case Token::GTEQ: return RESULT(Bool, >=);
1209 case Token::LT: return RESULT(Bool, <);
1210 case Token::LTEQ: return RESULT(Bool, <=);
1211 default: return nullptr;
1212 }
1213 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001214 if (left.fKind == Expression::kFloatLiteral_Kind &&
ethannicholas08a92112016-11-09 13:26:45 -08001215 right.fKind == Expression::kFloatLiteral_Kind) {
1216 double leftVal = ((FloatLiteral&) left).fValue;
1217 double rightVal = ((FloatLiteral&) right).fValue;
1218 switch (op) {
1219 case Token::PLUS: return RESULT(Float, +);
1220 case Token::MINUS: return RESULT(Float, -);
1221 case Token::STAR: return RESULT(Float, *);
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001222 case Token::SLASH:
1223 if (rightVal) {
1224 return RESULT(Float, /);
1225 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001226 fErrors.error(right.fOffset, "division by zero");
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001227 return nullptr;
Ethan Nicholascb670962017-04-20 19:31:52 -04001228 case Token::EQEQ: return RESULT(Bool, ==);
1229 case Token::NEQ: return RESULT(Bool, !=);
1230 case Token::GT: return RESULT(Bool, >);
1231 case Token::GTEQ: return RESULT(Bool, >=);
1232 case Token::LT: return RESULT(Bool, <);
1233 case Token::LTEQ: return RESULT(Bool, <=);
ethannicholas08a92112016-11-09 13:26:45 -08001234 default: return nullptr;
1235 }
1236 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001237 if (left.fType.kind() == Type::kVector_Kind &&
1238 left.fType.componentType() == *fContext.fFloat_Type &&
1239 left.fType == right.fType) {
1240 ASSERT(left.fKind == Expression::kConstructor_Kind);
1241 ASSERT(right.fKind == Expression::kConstructor_Kind);
1242 std::vector<std::unique_ptr<Expression>> args;
1243 #define RETURN_VEC_COMPONENTWISE_RESULT(op) \
1244 for (int i = 0; i < left.fType.columns(); i++) { \
1245 float value = ((Constructor&) left).getFVecComponent(i) op \
1246 ((Constructor&) right).getFVecComponent(i); \
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001247 args.emplace_back(new FloatLiteral(fContext, -1, value)); \
Ethan Nicholascb670962017-04-20 19:31:52 -04001248 } \
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001249 return std::unique_ptr<Expression>(new Constructor(-1, left.fType, \
Ethan Nicholascb670962017-04-20 19:31:52 -04001250 std::move(args)));
1251 switch (op) {
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001252 case Token::EQEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001253 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001254 left.compareConstant(fContext, right)));
1255 case Token::NEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001256 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001257 !left.compareConstant(fContext, right)));
Ethan Nicholascb670962017-04-20 19:31:52 -04001258 case Token::PLUS: RETURN_VEC_COMPONENTWISE_RESULT(+);
1259 case Token::MINUS: RETURN_VEC_COMPONENTWISE_RESULT(-);
1260 case Token::STAR: RETURN_VEC_COMPONENTWISE_RESULT(*);
1261 case Token::SLASH: RETURN_VEC_COMPONENTWISE_RESULT(/);
1262 default: return nullptr;
1263 }
1264 }
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001265 if (left.fType.kind() == Type::kMatrix_Kind &&
1266 right.fType.kind() == Type::kMatrix_Kind &&
1267 left.fKind == right.fKind) {
1268 switch (op) {
1269 case Token::EQEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001270 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001271 left.compareConstant(fContext, right)));
1272 case Token::NEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001273 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001274 !left.compareConstant(fContext, right)));
1275 default:
1276 return nullptr;
1277 }
1278 }
ethannicholas08a92112016-11-09 13:26:45 -08001279 #undef RESULT
1280 return nullptr;
1281}
1282
ethannicholasb3058bd2016-07-01 08:22:01 -07001283std::unique_ptr<Expression> IRGenerator::convertBinaryExpression(
1284 const ASTBinaryExpression& expression) {
1285 std::unique_ptr<Expression> left = this->convertExpression(*expression.fLeft);
1286 if (!left) {
1287 return nullptr;
1288 }
1289 std::unique_ptr<Expression> right = this->convertExpression(*expression.fRight);
1290 if (!right) {
1291 return nullptr;
1292 }
ethannicholasd598f792016-07-25 10:08:54 -07001293 const Type* leftType;
1294 const Type* rightType;
1295 const Type* resultType;
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001296 const Type* rawLeftType;
1297 if (left->fKind == Expression::kIntLiteral_Kind && right->fType.isInteger()) {
1298 rawLeftType = &right->fType;
1299 } else {
1300 rawLeftType = &left->fType;
1301 }
1302 const Type* rawRightType;
1303 if (right->fKind == Expression::kIntLiteral_Kind && left->fType.isInteger()) {
1304 rawRightType = &left->fType;
1305 } else {
1306 rawRightType = &right->fType;
1307 }
1308 if (!determine_binary_type(fContext, expression.fOperator, *rawLeftType, *rawRightType,
1309 &leftType, &rightType, &resultType,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001310 !Compiler::IsAssignment(expression.fOperator))) {
1311 fErrors.error(expression.fOffset, String("type mismatch: '") +
1312 Compiler::OperatorName(expression.fOperator) +
1313 "' cannot operate on '" + left->fType.fName +
1314 "', '" + right->fType.fName + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001315 return nullptr;
1316 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001317 if (Compiler::IsAssignment(expression.fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -05001318 this->markWrittenTo(*left, expression.fOperator != Token::EQ);
ethannicholasea4567c2016-10-17 11:24:37 -07001319 }
1320 left = this->coerce(std::move(left), *leftType);
1321 right = this->coerce(std::move(right), *rightType);
1322 if (!left || !right) {
1323 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001324 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001325 std::unique_ptr<Expression> result = this->constantFold(*left.get(), expression.fOperator,
ethannicholas08a92112016-11-09 13:26:45 -08001326 *right.get());
1327 if (!result) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001328 result = std::unique_ptr<Expression>(new BinaryExpression(expression.fOffset,
ethannicholas08a92112016-11-09 13:26:45 -08001329 std::move(left),
1330 expression.fOperator,
1331 std::move(right),
1332 *resultType));
1333 }
1334 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07001335}
1336
Ethan Nicholas11d53972016-11-28 11:23:23 -05001337std::unique_ptr<Expression> IRGenerator::convertTernaryExpression(
ethannicholasb3058bd2016-07-01 08:22:01 -07001338 const ASTTernaryExpression& expression) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001339 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*expression.fTest),
ethannicholasd598f792016-07-25 10:08:54 -07001340 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -07001341 if (!test) {
1342 return nullptr;
1343 }
1344 std::unique_ptr<Expression> ifTrue = this->convertExpression(*expression.fIfTrue);
1345 if (!ifTrue) {
1346 return nullptr;
1347 }
1348 std::unique_ptr<Expression> ifFalse = this->convertExpression(*expression.fIfFalse);
1349 if (!ifFalse) {
1350 return nullptr;
1351 }
ethannicholasd598f792016-07-25 10:08:54 -07001352 const Type* trueType;
1353 const Type* falseType;
1354 const Type* resultType;
1355 if (!determine_binary_type(fContext, Token::EQEQ, ifTrue->fType, ifFalse->fType, &trueType,
Ethan Nicholas2be687a2017-01-03 16:44:39 -05001356 &falseType, &resultType, true) || trueType != falseType) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001357 fErrors.error(expression.fOffset, "ternary operator result mismatch: '" +
1358 ifTrue->fType.fName + "', '" +
1359 ifFalse->fType.fName + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001360 return nullptr;
1361 }
ethannicholasd598f792016-07-25 10:08:54 -07001362 ifTrue = this->coerce(std::move(ifTrue), *trueType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05001363 if (!ifTrue) {
1364 return nullptr;
1365 }
ethannicholasd598f792016-07-25 10:08:54 -07001366 ifFalse = this->coerce(std::move(ifFalse), *falseType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05001367 if (!ifFalse) {
1368 return nullptr;
1369 }
ethannicholas08a92112016-11-09 13:26:45 -08001370 if (test->fKind == Expression::kBoolLiteral_Kind) {
1371 // static boolean test, just return one of the branches
1372 if (((BoolLiteral&) *test).fValue) {
1373 return ifTrue;
1374 } else {
1375 return ifFalse;
1376 }
1377 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001378 return std::unique_ptr<Expression>(new TernaryExpression(expression.fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -07001379 std::move(test),
Ethan Nicholas11d53972016-11-28 11:23:23 -05001380 std::move(ifTrue),
ethannicholasb3058bd2016-07-01 08:22:01 -07001381 std::move(ifFalse)));
1382}
1383
Ethan Nicholas5338f992017-04-19 15:54:07 -04001384// scales the texture coordinates by the texture size for sampling rectangle textures.
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001385// For float2coordinates, implements the transformation:
Ethan Nicholas5338f992017-04-19 15:54:07 -04001386// texture(sampler, coord) -> texture(sampler, textureSize(sampler) * coord)
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001387// For float3coordinates, implements the transformation:
1388// texture(sampler, coord) -> texture(sampler, float3textureSize(sampler), 1.0) * coord))
Ethan Nicholas5338f992017-04-19 15:54:07 -04001389void IRGenerator::fixRectSampling(std::vector<std::unique_ptr<Expression>>& arguments) {
1390 ASSERT(arguments.size() == 2);
1391 ASSERT(arguments[0]->fType == *fContext.fSampler2DRect_Type);
1392 ASSERT(arguments[0]->fKind == Expression::kVariableReference_Kind);
1393 const Variable& sampler = ((VariableReference&) *arguments[0]).fVariable;
1394 const Symbol* textureSizeSymbol = (*fSymbolTable)["textureSize"];
1395 ASSERT(textureSizeSymbol->fKind == Symbol::kFunctionDeclaration_Kind);
1396 const FunctionDeclaration& textureSize = (FunctionDeclaration&) *textureSizeSymbol;
1397 std::vector<std::unique_ptr<Expression>> sizeArguments;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001398 sizeArguments.emplace_back(new VariableReference(-1, sampler));
1399 std::unique_ptr<Expression> float2ize = call(-1, textureSize, std::move(sizeArguments));
Ethan Nicholas5338f992017-04-19 15:54:07 -04001400 const Type& type = arguments[1]->fType;
1401 std::unique_ptr<Expression> scale;
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001402 if (type == *fContext.fFloat2_Type) {
1403 scale = std::move(float2ize);
Ethan Nicholas5338f992017-04-19 15:54:07 -04001404 } else {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001405 ASSERT(type == *fContext.fFloat3_Type);
1406 std::vector<std::unique_ptr<Expression>> float3rguments;
1407 float3rguments.push_back(std::move(float2ize));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001408 float3rguments.emplace_back(new FloatLiteral(fContext, -1, 1.0));
1409 scale.reset(new Constructor(-1, *fContext.fFloat3_Type, std::move(float3rguments)));
Ethan Nicholas5338f992017-04-19 15:54:07 -04001410 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001411 arguments[1].reset(new BinaryExpression(-1, std::move(scale), Token::STAR,
Ethan Nicholas5338f992017-04-19 15:54:07 -04001412 std::move(arguments[1]), type));
1413}
1414
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001415std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05001416 const FunctionDeclaration& function,
ethannicholasd598f792016-07-25 10:08:54 -07001417 std::vector<std::unique_ptr<Expression>> arguments) {
1418 if (function.fParameters.size() != arguments.size()) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001419 String msg = "call to '" + function.fName + "' expected " +
Ethan Nicholas11d53972016-11-28 11:23:23 -05001420 to_string((uint64_t) function.fParameters.size()) +
ethannicholasb3058bd2016-07-01 08:22:01 -07001421 " argument";
ethannicholasd598f792016-07-25 10:08:54 -07001422 if (function.fParameters.size() != 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001423 msg += "s";
1424 }
ethannicholas5961bc92016-10-12 06:39:56 -07001425 msg += ", but found " + to_string((uint64_t) arguments.size());
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001426 fErrors.error(offset, msg);
ethannicholasb3058bd2016-07-01 08:22:01 -07001427 return nullptr;
1428 }
ethannicholas471e8942016-10-28 09:02:46 -07001429 std::vector<const Type*> types;
1430 const Type* returnType;
1431 if (!function.determineFinalTypes(arguments, &types, &returnType)) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001432 String msg = "no match for " + function.fName + "(";
1433 String separator;
ethannicholas471e8942016-10-28 09:02:46 -07001434 for (size_t i = 0; i < arguments.size(); i++) {
1435 msg += separator;
1436 separator = ", ";
1437 msg += arguments[i]->fType.description();
1438 }
1439 msg += ")";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001440 fErrors.error(offset, msg);
ethannicholas471e8942016-10-28 09:02:46 -07001441 return nullptr;
1442 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001443 for (size_t i = 0; i < arguments.size(); i++) {
ethannicholas471e8942016-10-28 09:02:46 -07001444 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
ethannicholasea4567c2016-10-17 11:24:37 -07001445 if (!arguments[i]) {
1446 return nullptr;
1447 }
ethannicholasd598f792016-07-25 10:08:54 -07001448 if (arguments[i] && (function.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag)) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001449 this->markWrittenTo(*arguments[i],
Ethan Nicholascb670962017-04-20 19:31:52 -04001450 function.fParameters[i]->fModifiers.fFlags & Modifiers::kIn_Flag);
ethannicholasb3058bd2016-07-01 08:22:01 -07001451 }
1452 }
Ethan Nicholas5338f992017-04-19 15:54:07 -04001453 if (function.fBuiltin && function.fName == "texture" &&
1454 arguments[0]->fType == *fContext.fSampler2DRect_Type) {
1455 this->fixRectSampling(arguments);
1456 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001457 return std::unique_ptr<FunctionCall>(new FunctionCall(offset, *returnType, function,
ethannicholasb3058bd2016-07-01 08:22:01 -07001458 std::move(arguments)));
1459}
1460
1461/**
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001462 * Determines the cost of coercing the arguments of a function to the required types. Cost has no
1463 * particular meaning other than "lower costs are preferred". Returns INT_MAX if the call is not
1464 * valid.
ethannicholasb3058bd2016-07-01 08:22:01 -07001465 */
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001466int IRGenerator::callCost(const FunctionDeclaration& function,
1467 const std::vector<std::unique_ptr<Expression>>& arguments) {
ethannicholasd598f792016-07-25 10:08:54 -07001468 if (function.fParameters.size() != arguments.size()) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001469 return INT_MAX;
ethannicholasb3058bd2016-07-01 08:22:01 -07001470 }
1471 int total = 0;
ethannicholas471e8942016-10-28 09:02:46 -07001472 std::vector<const Type*> types;
1473 const Type* ignored;
1474 if (!function.determineFinalTypes(arguments, &types, &ignored)) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001475 return INT_MAX;
ethannicholas471e8942016-10-28 09:02:46 -07001476 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001477 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001478 int cost = arguments[i]->coercionCost(*types[i]);
1479 if (cost != INT_MAX) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001480 total += cost;
1481 } else {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001482 return INT_MAX;
ethannicholasb3058bd2016-07-01 08:22:01 -07001483 }
1484 }
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001485 return total;
ethannicholasb3058bd2016-07-01 08:22:01 -07001486}
1487
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001488std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05001489 std::unique_ptr<Expression> functionValue,
ethannicholasb3058bd2016-07-01 08:22:01 -07001490 std::vector<std::unique_ptr<Expression>> arguments) {
1491 if (functionValue->fKind == Expression::kTypeReference_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001492 return this->convertConstructor(offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05001493 ((TypeReference&) *functionValue).fValue,
ethannicholasb3058bd2016-07-01 08:22:01 -07001494 std::move(arguments));
1495 }
1496 if (functionValue->fKind != Expression::kFunctionReference_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001497 fErrors.error(offset, "'" + functionValue->description() + "' is not a function");
ethannicholasb3058bd2016-07-01 08:22:01 -07001498 return nullptr;
1499 }
1500 FunctionReference* ref = (FunctionReference*) functionValue.get();
1501 int bestCost = INT_MAX;
ethannicholasd598f792016-07-25 10:08:54 -07001502 const FunctionDeclaration* best = nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001503 if (ref->fFunctions.size() > 1) {
1504 for (const auto& f : ref->fFunctions) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001505 int cost = this->callCost(*f, arguments);
1506 if (cost < bestCost) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001507 bestCost = cost;
1508 best = f;
1509 }
1510 }
1511 if (best) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001512 return this->call(offset, *best, std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07001513 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001514 String msg = "no match for " + ref->fFunctions[0]->fName + "(";
1515 String separator;
ethannicholasb3058bd2016-07-01 08:22:01 -07001516 for (size_t i = 0; i < arguments.size(); i++) {
1517 msg += separator;
1518 separator = ", ";
ethannicholasd598f792016-07-25 10:08:54 -07001519 msg += arguments[i]->fType.description();
ethannicholasb3058bd2016-07-01 08:22:01 -07001520 }
1521 msg += ")";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001522 fErrors.error(offset, msg);
ethannicholasb3058bd2016-07-01 08:22:01 -07001523 return nullptr;
1524 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001525 return this->call(offset, *ref->fFunctions[0], std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07001526}
1527
Ethan Nicholas84645e32017-02-09 13:57:14 -05001528std::unique_ptr<Expression> IRGenerator::convertNumberConstructor(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001529 int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05001530 const Type& type,
ethannicholasb3058bd2016-07-01 08:22:01 -07001531 std::vector<std::unique_ptr<Expression>> args) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001532 ASSERT(type.isNumber());
1533 if (args.size() != 1) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001534 fErrors.error(offset, "invalid arguments to '" + type.description() +
1535 "' constructor, (expected exactly 1 argument, but found " +
1536 to_string((uint64_t) args.size()) + ")");
ethannicholasb3058bd2016-07-01 08:22:01 -07001537 return nullptr;
1538 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001539 if (type == args[0]->fType) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001540 return std::move(args[0]);
1541 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001542 if (type.isFloat() && args.size() == 1 && args[0]->fKind == Expression::kFloatLiteral_Kind) {
1543 double value = ((FloatLiteral&) *args[0]).fValue;
1544 return std::unique_ptr<Expression>(new FloatLiteral(fContext, offset, value, &type));
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001545 }
1546 if (type.isFloat() && args.size() == 1 && args[0]->fKind == Expression::kIntLiteral_Kind) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001547 int64_t value = ((IntLiteral&) *args[0]).fValue;
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001548 return std::unique_ptr<Expression>(new FloatLiteral(fContext, offset, (double) value,
1549 &type));
ethannicholasb3058bd2016-07-01 08:22:01 -07001550 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05001551 if (args[0]->fKind == Expression::kIntLiteral_Kind && (type == *fContext.fInt_Type ||
1552 type == *fContext.fUInt_Type)) {
1553 return std::unique_ptr<Expression>(new IntLiteral(fContext,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001554 offset,
Ethan Nicholas84645e32017-02-09 13:57:14 -05001555 ((IntLiteral&) *args[0]).fValue,
1556 &type));
ethannicholasb3058bd2016-07-01 08:22:01 -07001557 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05001558 if (args[0]->fType == *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001559 std::unique_ptr<IntLiteral> zero(new IntLiteral(fContext, offset, 0));
1560 std::unique_ptr<IntLiteral> one(new IntLiteral(fContext, offset, 1));
Ethan Nicholas84645e32017-02-09 13:57:14 -05001561 return std::unique_ptr<Expression>(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001562 new TernaryExpression(offset, std::move(args[0]),
Ethan Nicholas84645e32017-02-09 13:57:14 -05001563 this->coerce(std::move(one), type),
1564 this->coerce(std::move(zero),
1565 type)));
1566 }
1567 if (!args[0]->fType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001568 fErrors.error(offset, "invalid argument to '" + type.description() +
1569 "' constructor (expected a number or bool, but found '" +
1570 args[0]->fType.description() + "')");
Ethan Nicholas84645e32017-02-09 13:57:14 -05001571 return nullptr;
1572 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001573 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
Ethan Nicholas84645e32017-02-09 13:57:14 -05001574}
1575
1576int component_count(const Type& type) {
1577 switch (type.kind()) {
1578 case Type::kVector_Kind:
1579 return type.columns();
1580 case Type::kMatrix_Kind:
1581 return type.columns() * type.rows();
1582 default:
1583 return 1;
1584 }
1585}
1586
1587std::unique_ptr<Expression> IRGenerator::convertCompoundConstructor(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001588 int offset,
Ethan Nicholas84645e32017-02-09 13:57:14 -05001589 const Type& type,
1590 std::vector<std::unique_ptr<Expression>> args) {
1591 ASSERT(type.kind() == Type::kVector_Kind || type.kind() == Type::kMatrix_Kind);
1592 if (type.kind() == Type::kMatrix_Kind && args.size() == 1 &&
1593 args[0]->fType.kind() == Type::kMatrix_Kind) {
1594 // matrix from matrix is always legal
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001595 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
Ethan Nicholas84645e32017-02-09 13:57:14 -05001596 }
1597 int actual = 0;
1598 int expected = type.rows() * type.columns();
1599 if (args.size() != 1 || expected != component_count(args[0]->fType) ||
1600 type.componentType().isNumber() != args[0]->fType.componentType().isNumber()) {
ethannicholas5961bc92016-10-12 06:39:56 -07001601 for (size_t i = 0; i < args.size(); i++) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001602 if (args[i]->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00001603 if (type.componentType().isNumber() !=
1604 args[i]->fType.componentType().isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001605 fErrors.error(offset, "'" + args[i]->fType.description() + "' is not a valid "
1606 "parameter to '" + type.description() +
1607 "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00001608 return nullptr;
1609 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05001610 actual += args[i]->fType.columns();
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00001611 } else if (args[i]->fType.kind() == Type::kScalar_Kind) {
1612 actual += 1;
1613 if (type.kind() != Type::kScalar_Kind) {
1614 args[i] = this->coerce(std::move(args[i]), type.componentType());
1615 if (!args[i]) {
1616 return nullptr;
1617 }
1618 }
1619 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001620 fErrors.error(offset, "'" + args[i]->fType.description() + "' is not a valid "
1621 "parameter to '" + type.description() + "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00001622 return nullptr;
1623 }
1624 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05001625 if (actual != 1 && actual != expected) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001626 fErrors.error(offset, "invalid arguments to '" + type.description() +
1627 "' constructor (expected " + to_string(expected) +
1628 " scalars, but found " + to_string(actual) + ")");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00001629 return nullptr;
1630 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001631 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001632 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
ethannicholasb3058bd2016-07-01 08:22:01 -07001633}
1634
Ethan Nicholas84645e32017-02-09 13:57:14 -05001635std::unique_ptr<Expression> IRGenerator::convertConstructor(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001636 int offset,
Ethan Nicholas84645e32017-02-09 13:57:14 -05001637 const Type& type,
1638 std::vector<std::unique_ptr<Expression>> args) {
1639 // FIXME: add support for structs
1640 Type::Kind kind = type.kind();
1641 if (args.size() == 1 && args[0]->fType == type) {
1642 // argument is already the right type, just return it
1643 return std::move(args[0]);
1644 }
1645 if (type.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001646 return this->convertNumberConstructor(offset, type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05001647 } else if (kind == Type::kArray_Kind) {
1648 const Type& base = type.componentType();
1649 for (size_t i = 0; i < args.size(); i++) {
1650 args[i] = this->coerce(std::move(args[i]), base);
1651 if (!args[i]) {
1652 return nullptr;
1653 }
1654 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001655 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
Ethan Nicholas84645e32017-02-09 13:57:14 -05001656 } else if (kind == Type::kVector_Kind || kind == Type::kMatrix_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001657 return this->convertCompoundConstructor(offset, type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05001658 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001659 fErrors.error(offset, "cannot construct '" + type.description() + "'");
Ethan Nicholas84645e32017-02-09 13:57:14 -05001660 return nullptr;
1661 }
1662}
1663
ethannicholasb3058bd2016-07-01 08:22:01 -07001664std::unique_ptr<Expression> IRGenerator::convertPrefixExpression(
1665 const ASTPrefixExpression& expression) {
1666 std::unique_ptr<Expression> base = this->convertExpression(*expression.fOperand);
1667 if (!base) {
1668 return nullptr;
1669 }
1670 switch (expression.fOperator) {
1671 case Token::PLUS:
ethannicholasd598f792016-07-25 10:08:54 -07001672 if (!base->fType.isNumber() && base->fType.kind() != Type::kVector_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001673 fErrors.error(expression.fOffset,
ethannicholasd598f792016-07-25 10:08:54 -07001674 "'+' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001675 return nullptr;
1676 }
1677 return base;
1678 case Token::MINUS:
ethannicholasd598f792016-07-25 10:08:54 -07001679 if (!base->fType.isNumber() && base->fType.kind() != Type::kVector_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001680 fErrors.error(expression.fOffset,
ethannicholasd598f792016-07-25 10:08:54 -07001681 "'-' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001682 return nullptr;
1683 }
1684 if (base->fKind == Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001685 return std::unique_ptr<Expression>(new IntLiteral(fContext, base->fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -07001686 -((IntLiteral&) *base).fValue));
1687 }
1688 if (base->fKind == Expression::kFloatLiteral_Kind) {
1689 double value = -((FloatLiteral&) *base).fValue;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001690 return std::unique_ptr<Expression>(new FloatLiteral(fContext, base->fOffset,
ethannicholasd598f792016-07-25 10:08:54 -07001691 value));
ethannicholasb3058bd2016-07-01 08:22:01 -07001692 }
1693 return std::unique_ptr<Expression>(new PrefixExpression(Token::MINUS, std::move(base)));
1694 case Token::PLUSPLUS:
ethannicholasd598f792016-07-25 10:08:54 -07001695 if (!base->fType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001696 fErrors.error(expression.fOffset,
1697 String("'") + Compiler::OperatorName(expression.fOperator) +
ethannicholasd598f792016-07-25 10:08:54 -07001698 "' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001699 return nullptr;
1700 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001701 this->markWrittenTo(*base, true);
ethannicholasb3058bd2016-07-01 08:22:01 -07001702 break;
Ethan Nicholas11d53972016-11-28 11:23:23 -05001703 case Token::MINUSMINUS:
ethannicholasd598f792016-07-25 10:08:54 -07001704 if (!base->fType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001705 fErrors.error(expression.fOffset,
1706 String("'") + Compiler::OperatorName(expression.fOperator) +
ethannicholasd598f792016-07-25 10:08:54 -07001707 "' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001708 return nullptr;
1709 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001710 this->markWrittenTo(*base, true);
ethannicholasb3058bd2016-07-01 08:22:01 -07001711 break;
ethannicholas5961bc92016-10-12 06:39:56 -07001712 case Token::LOGICALNOT:
ethannicholasd598f792016-07-25 10:08:54 -07001713 if (base->fType != *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001714 fErrors.error(expression.fOffset,
1715 String("'") + Compiler::OperatorName(expression.fOperator) +
ethannicholasd598f792016-07-25 10:08:54 -07001716 "' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001717 return nullptr;
1718 }
ethannicholas08a92112016-11-09 13:26:45 -08001719 if (base->fKind == Expression::kBoolLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001720 return std::unique_ptr<Expression>(new BoolLiteral(fContext, base->fOffset,
ethannicholas08a92112016-11-09 13:26:45 -08001721 !((BoolLiteral&) *base).fValue));
1722 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001723 break;
ethannicholas5961bc92016-10-12 06:39:56 -07001724 case Token::BITWISENOT:
1725 if (base->fType != *fContext.fInt_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001726 fErrors.error(expression.fOffset,
1727 String("'") + Compiler::OperatorName(expression.fOperator) +
ethannicholas5961bc92016-10-12 06:39:56 -07001728 "' cannot operate on '" + base->fType.description() + "'");
1729 return nullptr;
1730 }
1731 break;
Ethan Nicholas11d53972016-11-28 11:23:23 -05001732 default:
ethannicholasb3058bd2016-07-01 08:22:01 -07001733 ABORT("unsupported prefix operator\n");
1734 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001735 return std::unique_ptr<Expression>(new PrefixExpression(expression.fOperator,
ethannicholasb3058bd2016-07-01 08:22:01 -07001736 std::move(base)));
1737}
1738
1739std::unique_ptr<Expression> IRGenerator::convertIndex(std::unique_ptr<Expression> base,
1740 const ASTExpression& index) {
Ethan Nicholas50afc172017-02-16 14:49:57 -05001741 if (base->fKind == Expression::kTypeReference_Kind) {
1742 if (index.fKind == ASTExpression::kInt_Kind) {
1743 const Type& oldType = ((TypeReference&) *base).fValue;
1744 int64_t size = ((const ASTIntLiteral&) index).fValue;
1745 Type* newType = new Type(oldType.name() + "[" + to_string(size) + "]",
1746 Type::kArray_Kind, oldType, size);
1747 fSymbolTable->takeOwnership(newType);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001748 return std::unique_ptr<Expression>(new TypeReference(fContext, base->fOffset,
Ethan Nicholas50afc172017-02-16 14:49:57 -05001749 *newType));
1750
1751 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001752 fErrors.error(base->fOffset, "array size must be a constant");
Ethan Nicholas50afc172017-02-16 14:49:57 -05001753 return nullptr;
1754 }
1755 }
ethannicholas5961bc92016-10-12 06:39:56 -07001756 if (base->fType.kind() != Type::kArray_Kind && base->fType.kind() != Type::kMatrix_Kind &&
1757 base->fType.kind() != Type::kVector_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001758 fErrors.error(base->fOffset, "expected array, but found '" + base->fType.description() +
1759 "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001760 return nullptr;
1761 }
1762 std::unique_ptr<Expression> converted = this->convertExpression(index);
1763 if (!converted) {
1764 return nullptr;
1765 }
ethannicholas5961bc92016-10-12 06:39:56 -07001766 if (converted->fType != *fContext.fUInt_Type) {
1767 converted = this->coerce(std::move(converted), *fContext.fInt_Type);
1768 if (!converted) {
1769 return nullptr;
1770 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001771 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001772 return std::unique_ptr<Expression>(new IndexExpression(fContext, std::move(base),
ethannicholasd598f792016-07-25 10:08:54 -07001773 std::move(converted)));
ethannicholasb3058bd2016-07-01 08:22:01 -07001774}
1775
1776std::unique_ptr<Expression> IRGenerator::convertField(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001777 StringFragment field) {
ethannicholasd598f792016-07-25 10:08:54 -07001778 auto fields = base->fType.fields();
ethannicholasb3058bd2016-07-01 08:22:01 -07001779 for (size_t i = 0; i < fields.size(); i++) {
1780 if (fields[i].fName == field) {
1781 return std::unique_ptr<Expression>(new FieldAccess(std::move(base), (int) i));
1782 }
1783 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001784 fErrors.error(base->fOffset, "type '" + base->fType.description() + "' does not have a "
1785 "field named '" + field + "");
ethannicholasb3058bd2016-07-01 08:22:01 -07001786 return nullptr;
1787}
1788
1789std::unique_ptr<Expression> IRGenerator::convertSwizzle(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001790 StringFragment fields) {
ethannicholasd598f792016-07-25 10:08:54 -07001791 if (base->fType.kind() != Type::kVector_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001792 fErrors.error(base->fOffset, "cannot swizzle type '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001793 return nullptr;
1794 }
1795 std::vector<int> swizzleComponents;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001796 for (size_t i = 0; i < fields.fLength; i++) {
Ethan Nicholas9e1138d2016-11-21 10:39:35 -05001797 switch (fields[i]) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001798 case 'x': // fall through
1799 case 'r': // fall through
Ethan Nicholas11d53972016-11-28 11:23:23 -05001800 case 's':
ethannicholasb3058bd2016-07-01 08:22:01 -07001801 swizzleComponents.push_back(0);
1802 break;
1803 case 'y': // fall through
1804 case 'g': // fall through
1805 case 't':
ethannicholasd598f792016-07-25 10:08:54 -07001806 if (base->fType.columns() >= 2) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001807 swizzleComponents.push_back(1);
1808 break;
1809 }
1810 // fall through
1811 case 'z': // fall through
1812 case 'b': // fall through
Ethan Nicholas11d53972016-11-28 11:23:23 -05001813 case 'p':
ethannicholasd598f792016-07-25 10:08:54 -07001814 if (base->fType.columns() >= 3) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001815 swizzleComponents.push_back(2);
1816 break;
1817 }
1818 // fall through
1819 case 'w': // fall through
1820 case 'a': // fall through
1821 case 'q':
ethannicholasd598f792016-07-25 10:08:54 -07001822 if (base->fType.columns() >= 4) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001823 swizzleComponents.push_back(3);
1824 break;
1825 }
1826 // fall through
1827 default:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001828 fErrors.error(base->fOffset, String::printf("invalid swizzle component '%c'",
1829 fields[i]));
ethannicholasb3058bd2016-07-01 08:22:01 -07001830 return nullptr;
1831 }
1832 }
1833 ASSERT(swizzleComponents.size() > 0);
1834 if (swizzleComponents.size() > 4) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001835 fErrors.error(base->fOffset, "too many components in swizzle mask '" + fields + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001836 return nullptr;
1837 }
ethannicholasd598f792016-07-25 10:08:54 -07001838 return std::unique_ptr<Expression>(new Swizzle(fContext, std::move(base), swizzleComponents));
ethannicholasb3058bd2016-07-01 08:22:01 -07001839}
1840
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001841std::unique_ptr<Expression> IRGenerator::getCap(int offset, String name) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001842 auto found = fCapsMap.find(name);
1843 if (found == fCapsMap.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001844 fErrors.error(offset, "unknown capability flag '" + name + "'");
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001845 return nullptr;
1846 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001847 String fullName = "sk_Caps." + name;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001848 return std::unique_ptr<Expression>(new Setting(offset, fullName,
1849 found->second.literal(fContext, offset)));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001850}
1851
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001852std::unique_ptr<Expression> IRGenerator::getArg(int offset, String name) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001853 auto found = fSettings->fArgs.find(name);
1854 if (found == fSettings->fArgs.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001855 fErrors.error(offset, "unknown argument '" + name + "'");
Ethan Nicholas762466e2017-06-29 10:03:38 -04001856 return nullptr;
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001857 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001858 String fullName = "sk_Args." + name;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001859 return std::unique_ptr<Expression>(new Setting(offset,
Ethan Nicholas762466e2017-06-29 10:03:38 -04001860 fullName,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001861 found->second.literal(fContext, offset)));
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001862}
1863
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001864std::unique_ptr<Expression> IRGenerator::convertTypeField(int offset, const Type& type,
1865 StringFragment field) {
1866 std::unique_ptr<Expression> result;
1867 for (const auto& e : *fProgramElements) {
1868 if (e->fKind == ProgramElement::kEnum_Kind && type.name() == ((Enum&) *e).fTypeName) {
1869 std::shared_ptr<SymbolTable> old = fSymbolTable;
1870 fSymbolTable = ((Enum&) *e).fSymbols;
1871 result = convertIdentifier(ASTIdentifier(offset, field));
1872 fSymbolTable = old;
1873 }
1874 }
1875 if (!result) {
1876 fErrors.error(offset, "type '" + type.fName + "' does not have a field named '" + field +
1877 "'");
1878 }
1879 return result;
1880}
1881
ethannicholasb3058bd2016-07-01 08:22:01 -07001882std::unique_ptr<Expression> IRGenerator::convertSuffixExpression(
1883 const ASTSuffixExpression& expression) {
1884 std::unique_ptr<Expression> base = this->convertExpression(*expression.fBase);
1885 if (!base) {
1886 return nullptr;
1887 }
1888 switch (expression.fSuffix->fKind) {
ethannicholas5961bc92016-10-12 06:39:56 -07001889 case ASTSuffix::kIndex_Kind: {
1890 const ASTExpression* expr = ((ASTIndexSuffix&) *expression.fSuffix).fExpression.get();
1891 if (expr) {
1892 return this->convertIndex(std::move(base), *expr);
1893 } else if (base->fKind == Expression::kTypeReference_Kind) {
1894 const Type& oldType = ((TypeReference&) *base).fValue;
Ethan Nicholas11d53972016-11-28 11:23:23 -05001895 Type* newType = new Type(oldType.name() + "[]", Type::kArray_Kind, oldType,
ethannicholas5961bc92016-10-12 06:39:56 -07001896 -1);
1897 fSymbolTable->takeOwnership(newType);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001898 return std::unique_ptr<Expression>(new TypeReference(fContext, base->fOffset,
ethannicholas5961bc92016-10-12 06:39:56 -07001899 *newType));
1900 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001901 fErrors.error(expression.fOffset, "'[]' must follow a type name");
ethannicholasa54401d2016-10-14 08:37:32 -07001902 return nullptr;
ethannicholas5961bc92016-10-12 06:39:56 -07001903 }
1904 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001905 case ASTSuffix::kCall_Kind: {
1906 auto rawArguments = &((ASTCallSuffix&) *expression.fSuffix).fArguments;
1907 std::vector<std::unique_ptr<Expression>> arguments;
1908 for (size_t i = 0; i < rawArguments->size(); i++) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001909 std::unique_ptr<Expression> converted =
ethannicholasb3058bd2016-07-01 08:22:01 -07001910 this->convertExpression(*(*rawArguments)[i]);
1911 if (!converted) {
1912 return nullptr;
1913 }
1914 arguments.push_back(std::move(converted));
1915 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001916 return this->call(expression.fOffset, std::move(base), std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07001917 }
1918 case ASTSuffix::kField_Kind: {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001919 StringFragment field = ((ASTFieldSuffix&) *expression.fSuffix).fField;
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001920 if (base->fType == *fContext.fSkCaps_Type) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001921 return this->getCap(expression.fOffset, field);
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001922 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001923 if (base->fType == *fContext.fSkArgs_Type) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001924 return this->getArg(expression.fOffset, field);
1925 }
1926 if (base->fKind == Expression::kTypeReference_Kind) {
1927 return this->convertTypeField(base->fOffset, ((TypeReference&) *base).fValue,
1928 field);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001929 }
ethannicholasd598f792016-07-25 10:08:54 -07001930 switch (base->fType.kind()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001931 case Type::kVector_Kind:
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001932 return this->convertSwizzle(std::move(base), field);
ethannicholasb3058bd2016-07-01 08:22:01 -07001933 case Type::kStruct_Kind:
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001934 return this->convertField(std::move(base), field);
ethannicholasb3058bd2016-07-01 08:22:01 -07001935 default:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001936 fErrors.error(base->fOffset, "cannot swizzle value of type '" +
1937 base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001938 return nullptr;
1939 }
1940 }
1941 case ASTSuffix::kPostIncrement_Kind:
ethannicholasd598f792016-07-25 10:08:54 -07001942 if (!base->fType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001943 fErrors.error(expression.fOffset,
ethannicholasd598f792016-07-25 10:08:54 -07001944 "'++' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001945 return nullptr;
1946 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001947 this->markWrittenTo(*base, true);
Ethan Nicholas11d53972016-11-28 11:23:23 -05001948 return std::unique_ptr<Expression>(new PostfixExpression(std::move(base),
ethannicholasb3058bd2016-07-01 08:22:01 -07001949 Token::PLUSPLUS));
1950 case ASTSuffix::kPostDecrement_Kind:
ethannicholasd598f792016-07-25 10:08:54 -07001951 if (!base->fType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001952 fErrors.error(expression.fOffset,
ethannicholasd598f792016-07-25 10:08:54 -07001953 "'--' cannot operate on '" + base->fType.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001954 return nullptr;
1955 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001956 this->markWrittenTo(*base, true);
Ethan Nicholas11d53972016-11-28 11:23:23 -05001957 return std::unique_ptr<Expression>(new PostfixExpression(std::move(base),
ethannicholasb3058bd2016-07-01 08:22:01 -07001958 Token::MINUSMINUS));
1959 default:
1960 ABORT("unsupported suffix operator");
1961 }
1962}
1963
1964void IRGenerator::checkValid(const Expression& expr) {
1965 switch (expr.fKind) {
1966 case Expression::kFunctionReference_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001967 fErrors.error(expr.fOffset, "expected '(' to begin function call");
ethannicholasb3058bd2016-07-01 08:22:01 -07001968 break;
1969 case Expression::kTypeReference_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001970 fErrors.error(expr.fOffset, "expected '(' to begin constructor invocation");
ethannicholasb3058bd2016-07-01 08:22:01 -07001971 break;
1972 default:
ethannicholasea4567c2016-10-17 11:24:37 -07001973 if (expr.fType == *fContext.fInvalid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001974 fErrors.error(expr.fOffset, "invalid expression");
ethannicholasea4567c2016-10-17 11:24:37 -07001975 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001976 }
1977}
1978
ethannicholasb3058bd2016-07-01 08:22:01 -07001979static bool has_duplicates(const Swizzle& swizzle) {
1980 int bits = 0;
1981 for (int idx : swizzle.fComponents) {
1982 ASSERT(idx >= 0 && idx <= 3);
1983 int bit = 1 << idx;
1984 if (bits & bit) {
1985 return true;
1986 }
1987 bits |= bit;
1988 }
1989 return false;
1990}
1991
Ethan Nicholas86a43402017-01-19 13:32:00 -05001992void IRGenerator::markWrittenTo(const Expression& expr, bool readWrite) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001993 switch (expr.fKind) {
1994 case Expression::kVariableReference_Kind: {
ethannicholasd598f792016-07-25 10:08:54 -07001995 const Variable& var = ((VariableReference&) expr).fVariable;
ethannicholasb3058bd2016-07-01 08:22:01 -07001996 if (var.fModifiers.fFlags & (Modifiers::kConst_Flag | Modifiers::kUniform_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001997 fErrors.error(expr.fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -07001998 "cannot modify immutable variable '" + var.fName + "'");
1999 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05002000 ((VariableReference&) expr).setRefKind(readWrite ? VariableReference::kReadWrite_RefKind
2001 : VariableReference::kWrite_RefKind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002002 break;
2003 }
2004 case Expression::kFieldAccess_Kind:
Ethan Nicholas86a43402017-01-19 13:32:00 -05002005 this->markWrittenTo(*((FieldAccess&) expr).fBase, readWrite);
ethannicholasb3058bd2016-07-01 08:22:01 -07002006 break;
2007 case Expression::kSwizzle_Kind:
2008 if (has_duplicates((Swizzle&) expr)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002009 fErrors.error(expr.fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -07002010 "cannot write to the same swizzle field more than once");
2011 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05002012 this->markWrittenTo(*((Swizzle&) expr).fBase, readWrite);
ethannicholasb3058bd2016-07-01 08:22:01 -07002013 break;
2014 case Expression::kIndex_Kind:
Ethan Nicholas86a43402017-01-19 13:32:00 -05002015 this->markWrittenTo(*((IndexExpression&) expr).fBase, readWrite);
ethannicholasb3058bd2016-07-01 08:22:01 -07002016 break;
2017 default:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002018 fErrors.error(expr.fOffset, "cannot assign to '" + expr.description() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002019 break;
2020 }
2021}
2022
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002023void IRGenerator::convertProgram(const char* text,
2024 size_t length,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002025 SymbolTable& types,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002026 std::vector<std::unique_ptr<ProgramElement>>* out) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002027 fProgramElements = out;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002028 Parser parser(text, length, types, fErrors);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002029 std::vector<std::unique_ptr<ASTDeclaration>> parsed = parser.file();
2030 if (fErrors.errorCount()) {
2031 return;
2032 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002033 for (size_t i = 0; i < parsed.size(); i++) {
2034 ASTDeclaration& decl = *parsed[i];
2035 switch (decl.fKind) {
2036 case ASTDeclaration::kVar_Kind: {
2037 std::unique_ptr<VarDeclarations> s = this->convertVarDeclarations(
2038 (ASTVarDeclarations&) decl,
2039 Variable::kGlobal_Storage);
2040 if (s) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002041 fProgramElements->push_back(std::move(s));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002042 }
2043 break;
2044 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002045 case ASTDeclaration::kEnum_Kind: {
2046 this->convertEnum((ASTEnum&) decl);
2047 break;
2048 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002049 case ASTDeclaration::kFunction_Kind: {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002050 this->convertFunction((ASTFunction&) decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002051 break;
2052 }
2053 case ASTDeclaration::kModifiers_Kind: {
2054 std::unique_ptr<ModifiersDeclaration> f = this->convertModifiersDeclaration(
2055 (ASTModifiersDeclaration&) decl);
2056 if (f) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002057 fProgramElements->push_back(std::move(f));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002058 }
2059 break;
2060 }
2061 case ASTDeclaration::kInterfaceBlock_Kind: {
2062 std::unique_ptr<InterfaceBlock> i = this->convertInterfaceBlock(
2063 (ASTInterfaceBlock&) decl);
2064 if (i) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002065 fProgramElements->push_back(std::move(i));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002066 }
2067 break;
2068 }
2069 case ASTDeclaration::kExtension_Kind: {
2070 std::unique_ptr<Extension> e = this->convertExtension((ASTExtension&) decl);
2071 if (e) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002072 fProgramElements->push_back(std::move(e));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002073 }
2074 break;
2075 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04002076 case ASTDeclaration::kSection_Kind: {
2077 std::unique_ptr<Section> s = this->convertSection((ASTSection&) decl);
2078 if (s) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002079 fProgramElements->push_back(std::move(s));
Ethan Nicholas762466e2017-06-29 10:03:38 -04002080 }
2081 break;
2082 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002083 default:
2084 ABORT("unsupported declaration: %s\n", decl.description().c_str());
2085 }
2086 }
2087}
2088
2089
ethannicholasb3058bd2016-07-01 08:22:01 -07002090}