blob: b636b278ec46cfb744af6acceeb312fcef09c47e [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLIRGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -07009
10#include "limits.h"
John Stiles44e96be2020-08-31 13:16:04 -040011#include <iterator>
John Stilesfbd050b2020-08-03 13:21:46 -040012#include <memory>
Ethan Nicholasaf197692017-02-27 13:26:45 -050013#include <unordered_set>
ethannicholasb3058bd2016-07-01 08:22:01 -070014
Ethan Nicholas6e0fa402020-08-20 14:08:23 -040015#include "src/sksl/SkSLAnalysis.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050016#include "src/sksl/SkSLCompiler.h"
17#include "src/sksl/SkSLParser.h"
Brian Osman3000d6b2020-07-31 15:57:28 -040018#include "src/sksl/SkSLUtil.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/ir/SkSLBinaryExpression.h"
20#include "src/sksl/ir/SkSLBoolLiteral.h"
21#include "src/sksl/ir/SkSLBreakStatement.h"
22#include "src/sksl/ir/SkSLConstructor.h"
23#include "src/sksl/ir/SkSLContinueStatement.h"
24#include "src/sksl/ir/SkSLDiscardStatement.h"
25#include "src/sksl/ir/SkSLDoStatement.h"
26#include "src/sksl/ir/SkSLEnum.h"
27#include "src/sksl/ir/SkSLExpressionStatement.h"
Ethan Nicholas9e6a3932019-05-17 16:31:21 -040028#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Ethan Nicholas91164d12019-05-15 15:29:54 -040029#include "src/sksl/ir/SkSLExternalValueReference.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050030#include "src/sksl/ir/SkSLField.h"
31#include "src/sksl/ir/SkSLFieldAccess.h"
32#include "src/sksl/ir/SkSLFloatLiteral.h"
33#include "src/sksl/ir/SkSLForStatement.h"
34#include "src/sksl/ir/SkSLFunctionCall.h"
35#include "src/sksl/ir/SkSLFunctionDeclaration.h"
36#include "src/sksl/ir/SkSLFunctionDefinition.h"
37#include "src/sksl/ir/SkSLFunctionReference.h"
38#include "src/sksl/ir/SkSLIfStatement.h"
39#include "src/sksl/ir/SkSLIndexExpression.h"
40#include "src/sksl/ir/SkSLIntLiteral.h"
41#include "src/sksl/ir/SkSLInterfaceBlock.h"
42#include "src/sksl/ir/SkSLLayout.h"
Chris Daltonb0fd4b12019-10-29 13:41:22 -060043#include "src/sksl/ir/SkSLNop.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050044#include "src/sksl/ir/SkSLNullLiteral.h"
45#include "src/sksl/ir/SkSLPostfixExpression.h"
46#include "src/sksl/ir/SkSLPrefixExpression.h"
47#include "src/sksl/ir/SkSLReturnStatement.h"
48#include "src/sksl/ir/SkSLSetting.h"
49#include "src/sksl/ir/SkSLSwitchCase.h"
50#include "src/sksl/ir/SkSLSwitchStatement.h"
51#include "src/sksl/ir/SkSLSwizzle.h"
52#include "src/sksl/ir/SkSLTernaryExpression.h"
53#include "src/sksl/ir/SkSLUnresolvedFunction.h"
54#include "src/sksl/ir/SkSLVarDeclarations.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050055#include "src/sksl/ir/SkSLVariable.h"
56#include "src/sksl/ir/SkSLVariableReference.h"
57#include "src/sksl/ir/SkSLWhileStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070058
59namespace SkSL {
60
61class AutoSymbolTable {
62public:
Ethan Nicholas11d53972016-11-28 11:23:23 -050063 AutoSymbolTable(IRGenerator* ir)
ethannicholasb3058bd2016-07-01 08:22:01 -070064 : fIR(ir)
65 , fPrevious(fIR->fSymbolTable) {
66 fIR->pushSymbolTable();
67 }
68
69 ~AutoSymbolTable() {
70 fIR->popSymbolTable();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -040071 SkASSERT(fPrevious == fIR->fSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -070072 }
73
74 IRGenerator* fIR;
75 std::shared_ptr<SymbolTable> fPrevious;
76};
77
ethannicholas22f939e2016-10-13 13:25:34 -070078class AutoLoopLevel {
79public:
Ethan Nicholas11d53972016-11-28 11:23:23 -050080 AutoLoopLevel(IRGenerator* ir)
ethannicholas22f939e2016-10-13 13:25:34 -070081 : fIR(ir) {
82 fIR->fLoopLevel++;
83 }
84
85 ~AutoLoopLevel() {
86 fIR->fLoopLevel--;
87 }
88
89 IRGenerator* fIR;
90};
91
Ethan Nicholasaf197692017-02-27 13:26:45 -050092class AutoSwitchLevel {
93public:
94 AutoSwitchLevel(IRGenerator* ir)
95 : fIR(ir) {
96 fIR->fSwitchLevel++;
97 }
98
99 ~AutoSwitchLevel() {
100 fIR->fSwitchLevel--;
101 }
102
103 IRGenerator* fIR;
104};
105
John Stiles4c412bc2020-10-13 11:19:41 -0400106class AutoDisableInline {
107public:
108 AutoDisableInline(IRGenerator* ir, bool canInline = false)
109 : fIR(ir) {
110 fOldCanInline = ir->fCanInline;
111 fIR->fCanInline &= canInline;
112 }
113
114 ~AutoDisableInline() {
115 fIR->fCanInline = fOldCanInline;
116 }
117
118 IRGenerator* fIR;
119 bool fOldCanInline;
120};
121
122IRGenerator::IRGenerator(const Context* context, Inliner* inliner, ErrorReporter& errorReporter)
John Stiles7b463002020-08-31 17:29:21 -0400123 : fContext(*context)
John Stiles4c412bc2020-10-13 11:19:41 -0400124 , fInliner(inliner)
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400125 , fErrors(errorReporter)
John Stiles4c412bc2020-10-13 11:19:41 -0400126 , fModifiers(new ModifiersPool()) {
127 SkASSERT(fInliner);
128}
ethannicholasb3058bd2016-07-01 08:22:01 -0700129
130void IRGenerator::pushSymbolTable() {
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400131 fSymbolTable.reset(new SymbolTable(std::move(fSymbolTable)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700132}
133
134void IRGenerator::popSymbolTable() {
135 fSymbolTable = fSymbolTable->fParent;
136}
137
John Stiles194b9b92020-09-15 15:37:24 -0400138static void fill_caps(const SkSL::ShaderCapsClass& caps,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400139 std::unordered_map<String, Program::Settings::Value>* capsMap) {
Brian Osman88cda172020-10-09 12:05:16 -0400140#define CAP(name) capsMap->insert({String(#name), Program::Settings::Value(caps.name())})
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500141 CAP(fbFetchSupport);
Brian Salomond4013302018-04-04 13:58:33 +0000142 CAP(fbFetchNeedsCustomOutput);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500143 CAP(flatInterpolationSupport);
144 CAP(noperspectiveInterpolationSupport);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500145 CAP(externalTextureSupport);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500146 CAP(mustEnableAdvBlendEqs);
147 CAP(mustEnableSpecificAdvBlendEqs);
148 CAP(mustDeclareFragmentShaderOutput);
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400149 CAP(mustDoOpBetweenFloorAndAbs);
Brian Salomonf8c187c2019-12-19 14:41:57 -0500150 CAP(mustGuardDivisionEvenAfterExplicitZeroCheck);
151 CAP(inBlendModesFailRandomlyForAllZeroVec);
Michael Ludwig24d438b2018-09-12 15:22:50 -0400152 CAP(atan2ImplementedAsAtanYOverX);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500153 CAP(canUseAnyFunctionInShader);
Chris Dalton47c8ed32017-11-15 18:27:09 -0700154 CAP(floatIs32Bits);
Ethan Nicholas07990de2017-07-18 09:47:43 -0400155 CAP(integerSupport);
John Stiles6f3015a2020-10-08 14:55:36 -0400156 CAP(builtinFMASupport);
157 CAP(builtinDeterminantSupport);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500158#undef CAP
159}
160
Ethan Nicholasfc994162019-06-06 10:04:27 -0400161std::unique_ptr<Extension> IRGenerator::convertExtension(int offset, StringFragment name) {
Brian Osman16f376f2020-09-02 12:30:59 -0400162 if (fKind != Program::kFragment_Kind &&
163 fKind != Program::kVertex_Kind &&
164 fKind != Program::kGeometry_Kind) {
165 fErrors.error(offset, "extensions are not allowed here");
166 return nullptr;
167 }
168
John Stilesfbd050b2020-08-03 13:21:46 -0400169 return std::make_unique<Extension>(offset, name);
ethannicholasb3058bd2016-07-01 08:22:01 -0700170}
171
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400172std::unique_ptr<ModifiersPool> IRGenerator::releaseModifiers() {
173 std::unique_ptr<ModifiersPool> result = std::move(fModifiers);
174 fModifiers = std::make_unique<ModifiersPool>();
175 return result;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400176}
177
Ethan Nicholas70728ef2020-05-28 07:09:00 -0400178std::unique_ptr<Statement> IRGenerator::convertSingleStatement(const ASTNode& statement) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700179 switch (statement.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400180 case ASTNode::Kind::kBlock:
181 return this->convertBlock(statement);
182 case ASTNode::Kind::kVarDeclarations:
183 return this->convertVarDeclarationStatement(statement);
184 case ASTNode::Kind::kIf:
185 return this->convertIf(statement);
186 case ASTNode::Kind::kFor:
187 return this->convertFor(statement);
188 case ASTNode::Kind::kWhile:
189 return this->convertWhile(statement);
190 case ASTNode::Kind::kDo:
191 return this->convertDo(statement);
192 case ASTNode::Kind::kSwitch:
193 return this->convertSwitch(statement);
194 case ASTNode::Kind::kReturn:
195 return this->convertReturn(statement);
196 case ASTNode::Kind::kBreak:
197 return this->convertBreak(statement);
198 case ASTNode::Kind::kContinue:
199 return this->convertContinue(statement);
200 case ASTNode::Kind::kDiscard:
201 return this->convertDiscard(statement);
202 default:
203 // it's an expression
204 std::unique_ptr<Statement> result = this->convertExpressionStatement(statement);
Ethan Nicholase6592142020-09-08 10:22:09 -0400205 if (fRTAdjust && fKind == Program::kGeometry_Kind) {
206 SkASSERT(result->kind() == Statement::Kind::kExpression);
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400207 Expression& expr = *result->as<ExpressionStatement>().expression();
Ethan Nicholase6592142020-09-08 10:22:09 -0400208 if (expr.kind() == Expression::Kind::kFunctionCall) {
John Stiles403a3632020-08-20 12:11:48 -0400209 FunctionCall& fc = expr.as<FunctionCall>();
Ethan Nicholased84b732020-10-08 11:45:44 -0400210 if (fc.function().isBuiltin() && fc.function().name() == "EmitVertex") {
Robert Phillipsfe8da172018-01-24 14:52:02 +0000211 std::vector<std::unique_ptr<Statement>> statements;
212 statements.push_back(getNormalizeSkPositionCode());
213 statements.push_back(std::move(result));
John Stilesfbd050b2020-08-03 13:21:46 -0400214 return std::make_unique<Block>(statement.fOffset, std::move(statements),
215 fSymbolTable);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000216 }
217 }
218 }
219 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700220 }
221}
222
Ethan Nicholas70728ef2020-05-28 07:09:00 -0400223std::unique_ptr<Statement> IRGenerator::convertStatement(const ASTNode& statement) {
224 std::vector<std::unique_ptr<Statement>> oldExtraStatements = std::move(fExtraStatements);
225 std::unique_ptr<Statement> result = this->convertSingleStatement(statement);
226 if (!result) {
227 fExtraStatements = std::move(oldExtraStatements);
228 return nullptr;
229 }
230 if (fExtraStatements.size()) {
231 fExtraStatements.push_back(std::move(result));
232 std::unique_ptr<Statement> block(new Block(-1, std::move(fExtraStatements), nullptr,
233 false));
234 fExtraStatements = std::move(oldExtraStatements);
235 return block;
236 }
237 fExtraStatements = std::move(oldExtraStatements);
238 return result;
239}
240
Ethan Nicholasfc994162019-06-06 10:04:27 -0400241std::unique_ptr<Block> IRGenerator::convertBlock(const ASTNode& block) {
242 SkASSERT(block.fKind == ASTNode::Kind::kBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700243 AutoSymbolTable table(this);
244 std::vector<std::unique_ptr<Statement>> statements;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400245 for (const auto& child : block) {
246 std::unique_ptr<Statement> statement = this->convertStatement(child);
ethannicholasb3058bd2016-07-01 08:22:01 -0700247 if (!statement) {
248 return nullptr;
249 }
250 statements.push_back(std::move(statement));
251 }
John Stilesfbd050b2020-08-03 13:21:46 -0400252 return std::make_unique<Block>(block.fOffset, std::move(statements), fSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -0700253}
254
Ethan Nicholasfc994162019-06-06 10:04:27 -0400255std::unique_ptr<Statement> IRGenerator::convertVarDeclarationStatement(const ASTNode& s) {
256 SkASSERT(s.fKind == ASTNode::Kind::kVarDeclarations);
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400257 auto decls = this->convertVarDeclarations(s, Variable::Storage::kLocal);
Brian Osmanc0213602020-10-06 14:43:32 -0400258 if (decls.empty()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700259 return nullptr;
260 }
Brian Osmanc0213602020-10-06 14:43:32 -0400261 if (decls.size() == 1) {
262 return std::move(decls.front());
263 } else {
264 return std::make_unique<Block>(s.fOffset, std::move(decls), /*symbols=*/nullptr,
265 /*isScope=*/false);
266 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700267}
268
Brian Osmanc0213602020-10-06 14:43:32 -0400269std::vector<std::unique_ptr<Statement>> IRGenerator::convertVarDeclarations(
270 const ASTNode& decls, Variable::Storage storage) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400271 SkASSERT(decls.fKind == ASTNode::Kind::kVarDeclarations);
John Stilesf621e232020-08-25 13:33:02 -0400272 auto declarationsIter = decls.begin();
273 const Modifiers& modifiers = declarationsIter++->getModifiers();
274 const ASTNode& rawType = *(declarationsIter++);
Brian Osmanc0213602020-10-06 14:43:32 -0400275 std::vector<std::unique_ptr<Statement>> varDecls;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400276 const Type* baseType = this->convertType(rawType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700277 if (!baseType) {
Brian Osmanc0213602020-10-06 14:43:32 -0400278 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700279 }
Brian Osman82329002020-07-21 09:39:27 -0400280 if (baseType->nonnullable() == *fContext.fFragmentProcessor_Type &&
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400281 storage != Variable::Storage::kGlobal) {
Brian Osman82329002020-07-21 09:39:27 -0400282 fErrors.error(decls.fOffset,
283 "variables of type '" + baseType->displayName() + "' must be global");
284 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500285 if (fKind != Program::kFragmentProcessor_Kind) {
286 if ((modifiers.fFlags & Modifiers::kIn_Flag) &&
Ethan Nicholase6592142020-09-08 10:22:09 -0400287 baseType->typeKind() == Type::TypeKind::kMatrix) {
Brian Osman2fe83fe2019-12-16 13:17:59 -0500288 fErrors.error(decls.fOffset, "'in' variables may not have matrix type");
289 }
Brian Osman088913a2019-12-19 15:44:56 -0500290 if ((modifiers.fFlags & Modifiers::kIn_Flag) &&
291 (modifiers.fFlags & Modifiers::kUniform_Flag)) {
292 fErrors.error(decls.fOffset,
293 "'in uniform' variables only permitted within fragment processors");
294 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500295 if (modifiers.fLayout.fWhen.fLength) {
296 fErrors.error(decls.fOffset, "'when' is only permitted within fragment processors");
297 }
298 if (modifiers.fLayout.fFlags & Layout::kTracked_Flag) {
299 fErrors.error(decls.fOffset, "'tracked' is only permitted within fragment processors");
300 }
301 if (modifiers.fLayout.fCType != Layout::CType::kDefault) {
302 fErrors.error(decls.fOffset, "'ctype' is only permitted within fragment processors");
303 }
304 if (modifiers.fLayout.fKey) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400305 fErrors.error(decls.fOffset, "'key' is only permitted within fragment processors");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400306 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500307 }
Brian Osmana4b91692020-08-10 14:26:16 -0400308 if (fKind == Program::kPipelineStage_Kind) {
309 if ((modifiers.fFlags & Modifiers::kIn_Flag) &&
310 baseType->nonnullable() != *fContext.fFragmentProcessor_Type) {
311 fErrors.error(decls.fOffset, "'in' variables not permitted in runtime effects");
312 }
313 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500314 if (modifiers.fLayout.fKey && (modifiers.fFlags & Modifiers::kUniform_Flag)) {
315 fErrors.error(decls.fOffset, "'key' is not permitted on 'uniform' variables");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400316 }
Brian Osmanf59a9612020-04-15 14:18:13 -0400317 if (modifiers.fLayout.fMarker.fLength) {
318 if (fKind != Program::kPipelineStage_Kind) {
319 fErrors.error(decls.fOffset, "'marker' is only permitted in runtime effects");
320 }
321 if (!(modifiers.fFlags & Modifiers::kUniform_Flag)) {
322 fErrors.error(decls.fOffset, "'marker' is only permitted on 'uniform' variables");
323 }
324 if (*baseType != *fContext.fFloat4x4_Type) {
325 fErrors.error(decls.fOffset, "'marker' is only permitted on float4x4 variables");
326 }
327 }
Brian Osmanb32d66b2020-04-30 17:12:03 -0400328 if (modifiers.fLayout.fFlags & Layout::kSRGBUnpremul_Flag) {
329 if (fKind != Program::kPipelineStage_Kind) {
330 fErrors.error(decls.fOffset, "'srgb_unpremul' is only permitted in runtime effects");
331 }
332 if (!(modifiers.fFlags & Modifiers::kUniform_Flag)) {
333 fErrors.error(decls.fOffset,
334 "'srgb_unpremul' is only permitted on 'uniform' variables");
335 }
336 auto validColorXformType = [](const Type& t) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400337 return t.typeKind() == Type::TypeKind::kVector && t.componentType().isFloat() &&
Brian Osmanb32d66b2020-04-30 17:12:03 -0400338 (t.columns() == 3 || t.columns() == 4);
339 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400340 if (!validColorXformType(*baseType) && !(baseType->typeKind() == Type::TypeKind::kArray &&
Brian Osmanb32d66b2020-04-30 17:12:03 -0400341 validColorXformType(baseType->componentType()))) {
342 fErrors.error(decls.fOffset,
343 "'srgb_unpremul' is only permitted on half3, half4, float3, or float4 "
344 "variables");
345 }
346 }
Brian Osman3c358422020-03-23 10:44:12 -0400347 if (modifiers.fFlags & Modifiers::kVarying_Flag) {
348 if (fKind != Program::kPipelineStage_Kind) {
349 fErrors.error(decls.fOffset, "'varying' is only permitted in runtime effects");
350 }
351 if (!baseType->isFloat() &&
Ethan Nicholase6592142020-09-08 10:22:09 -0400352 !(baseType->typeKind() == Type::TypeKind::kVector &&
353 baseType->componentType().isFloat())) {
Brian Osman3c358422020-03-23 10:44:12 -0400354 fErrors.error(decls.fOffset, "'varying' must be float scalar or vector");
355 }
356 }
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400357 int permitted = Modifiers::kConst_Flag;
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400358 if (storage == Variable::Storage::kGlobal) {
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400359 permitted |= Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag |
360 Modifiers::kFlat_Flag | Modifiers::kVarying_Flag |
361 Modifiers::kNoPerspective_Flag | Modifiers::kPLS_Flag |
362 Modifiers::kPLSIn_Flag | Modifiers::kPLSOut_Flag |
363 Modifiers::kRestrict_Flag | Modifiers::kVolatile_Flag |
364 Modifiers::kReadOnly_Flag | Modifiers::kWriteOnly_Flag |
365 Modifiers::kCoherent_Flag | Modifiers::kBuffer_Flag;
366 }
367 this->checkModifiers(decls.fOffset, modifiers, permitted);
John Stilesf621e232020-08-25 13:33:02 -0400368 for (; declarationsIter != decls.end(); ++declarationsIter) {
369 const ASTNode& varDecl = *declarationsIter;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400370 if (modifiers.fLayout.fLocation == 0 && modifiers.fLayout.fIndex == 0 &&
371 (modifiers.fFlags & Modifiers::kOut_Flag) && fKind == Program::kFragment_Kind &&
372 varDecl.getVarData().fName != "sk_FragColor") {
373 fErrors.error(varDecl.fOffset,
Ethan Nicholas6c942712018-03-16 09:45:11 -0400374 "out location=0, index=0 is reserved for sk_FragColor");
375 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400376 const ASTNode::VarData& varData = varDecl.getVarData();
ethannicholasd598f792016-07-25 10:08:54 -0700377 const Type* type = baseType;
ethannicholas14fe8cc2016-09-07 13:37:16 -0700378 std::vector<std::unique_ptr<Expression>> sizes;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400379 auto iter = varDecl.begin();
380 for (size_t i = 0; i < varData.fSizeCount; ++i, ++iter) {
381 const ASTNode& rawSize = *iter;
ethannicholas14fe8cc2016-09-07 13:37:16 -0700382 if (rawSize) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400383 auto size = this->coerce(this->convertExpression(rawSize), *fContext.fInt_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700384 if (!size) {
Brian Osmanc0213602020-10-06 14:43:32 -0400385 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700386 }
Ethan Nicholase2c49992020-10-05 11:49:11 -0400387 String name(type->name());
Ethan Nicholas50afc172017-02-16 14:49:57 -0500388 int64_t count;
Ethan Nicholase6592142020-09-08 10:22:09 -0400389 if (size->kind() == Expression::Kind::kIntLiteral) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400390 count = size->as<IntLiteral>().value();
ethannicholasb3058bd2016-07-01 08:22:01 -0700391 if (count <= 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700392 fErrors.error(size->fOffset, "array size must be positive");
Brian Osmanc0213602020-10-06 14:43:32 -0400393 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700394 }
395 name += "[" + to_string(count) + "]";
396 } else {
Ethan Nicholas66d80062019-09-09 14:50:51 -0400397 fErrors.error(size->fOffset, "array size must be specified");
Brian Osmanc0213602020-10-06 14:43:32 -0400398 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700399 }
John Stiles3ae071e2020-08-05 15:29:29 -0400400 type = fSymbolTable->takeOwnershipOfSymbol(
Ethan Nicholase6592142020-09-08 10:22:09 -0400401 std::make_unique<Type>(name, Type::TypeKind::kArray, *type, (int)count));
ethannicholas14fe8cc2016-09-07 13:37:16 -0700402 sizes.push_back(std::move(size));
ethannicholasb3058bd2016-07-01 08:22:01 -0700403 } else {
John Stiles3ae071e2020-08-05 15:29:29 -0400404 type = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
Brian Osmane8c26082020-10-01 17:22:45 -0400405 type->name() + "[]", Type::TypeKind::kArray, *type, Type::kUnsizedArray));
ethannicholas14fe8cc2016-09-07 13:37:16 -0700406 sizes.push_back(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700407 }
408 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400409 auto var = std::make_unique<Variable>(varDecl.fOffset, fModifiers->handle(modifiers),
410 varData.fName, type, fIsBuiltinCode, storage);
Ethan Nicholase2c49992020-10-05 11:49:11 -0400411 if (var->name() == Compiler::RTADJUST_NAME) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400412 SkASSERT(!fRTAdjust);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400413 SkASSERT(var->type() == *fContext.fFloat4_Type);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000414 fRTAdjust = var.get();
415 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700416 std::unique_ptr<Expression> value;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400417 if (iter != varDecl.end()) {
418 value = this->convertExpression(*iter);
ethannicholasb3058bd2016-07-01 08:22:01 -0700419 if (!value) {
Brian Osmanc0213602020-10-06 14:43:32 -0400420 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700421 }
ethannicholasd598f792016-07-25 10:08:54 -0700422 value = this->coerce(std::move(value), *type);
Ethan Nicholas68dd2c12018-03-01 15:05:17 -0500423 if (!value) {
Brian Osmanc0213602020-10-06 14:43:32 -0400424 return {};
Ethan Nicholas68dd2c12018-03-01 15:05:17 -0500425 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400426 var->setInitialValue(value.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700427 }
Brian Osman8dbdf232020-10-12 14:40:24 -0400428 const Symbol* symbol = (*fSymbolTable)[var->name()];
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400429 if (symbol && storage == Variable::Storage::kGlobal && var->name() == "sk_FragColor") {
John Stilesce591b72020-08-27 11:47:30 -0400430 // Already defined, ignore.
ethannicholasf789b382016-08-03 12:43:36 -0700431 } else {
John Stilesb8cc6652020-10-08 09:12:07 -0400432 varDecls.push_back(std::make_unique<VarDeclaration>(
Brian Osmanc0213602020-10-06 14:43:32 -0400433 var.get(), baseType, std::move(sizes), std::move(value)));
John Stilesb8cc6652020-10-08 09:12:07 -0400434 fSymbolTable->add(std::move(var));
ethannicholasf789b382016-08-03 12:43:36 -0700435 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700436 }
Brian Osmanc0213602020-10-06 14:43:32 -0400437 return varDecls;
ethannicholasb3058bd2016-07-01 08:22:01 -0700438}
439
Ethan Nicholasfc994162019-06-06 10:04:27 -0400440std::unique_ptr<ModifiersDeclaration> IRGenerator::convertModifiersDeclaration(const ASTNode& m) {
Brian Osman16f376f2020-09-02 12:30:59 -0400441 if (fKind != Program::kFragment_Kind &&
442 fKind != Program::kVertex_Kind &&
443 fKind != Program::kGeometry_Kind) {
444 fErrors.error(m.fOffset, "layout qualifiers are not allowed here");
445 return nullptr;
446 }
447
Ethan Nicholasfc994162019-06-06 10:04:27 -0400448 SkASSERT(m.fKind == ASTNode::Kind::kModifiers);
449 Modifiers modifiers = m.getModifiers();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400450 if (modifiers.fLayout.fInvocations != -1) {
Ethan Nicholasf06576b2019-04-03 15:45:25 -0400451 if (fKind != Program::kGeometry_Kind) {
452 fErrors.error(m.fOffset, "'invocations' is only legal in geometry shaders");
453 return nullptr;
454 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400455 fInvocations = modifiers.fLayout.fInvocations;
Chris Daltonf1b47bb2017-10-06 11:57:51 -0600456 if (fSettings->fCaps && !fSettings->fCaps->gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400457 modifiers.fLayout.fInvocations = -1;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400458 Variable& invocationId = (*fSymbolTable)["sk_InvocationID"]->as<Variable>();
459 Modifiers modifiers = invocationId.modifiers();
460 modifiers.fFlags = 0;
461 modifiers.fLayout.fBuiltin = -1;
462 invocationId.setModifiersHandle(fModifiers->handle(modifiers));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400463 if (modifiers.fLayout.description() == "") {
464 return nullptr;
465 }
466 }
467 }
468 if (modifiers.fLayout.fMaxVertices != -1 && fInvocations > 0 && fSettings->fCaps &&
Chris Daltonf1b47bb2017-10-06 11:57:51 -0600469 !fSettings->fCaps->gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400470 modifiers.fLayout.fMaxVertices *= fInvocations;
471 }
Ethan Nicholas077050b2020-10-13 10:30:20 -0400472 return std::make_unique<ModifiersDeclaration>(fModifiers->handle(modifiers));
ethannicholas5961bc92016-10-12 06:39:56 -0700473}
474
John Stilesad2319f2020-09-02 15:01:47 -0400475std::unique_ptr<Statement> IRGenerator::convertIf(const ASTNode& n) {
476 SkASSERT(n.fKind == ASTNode::Kind::kIf);
477 auto iter = n.begin();
478 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
479 *fContext.fBool_Type);
480 if (!test) {
481 return nullptr;
482 }
483 std::unique_ptr<Statement> ifTrue = this->convertStatement(*(iter++));
484 if (!ifTrue) {
485 return nullptr;
486 }
John Stilesad2319f2020-09-02 15:01:47 -0400487 std::unique_ptr<Statement> ifFalse;
488 if (iter != n.end()) {
489 ifFalse = this->convertStatement(*(iter++));
490 if (!ifFalse) {
491 return nullptr;
492 }
John Stilesad2319f2020-09-02 15:01:47 -0400493 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400494 if (test->kind() == Expression::Kind::kBoolLiteral) {
John Stilesad2319f2020-09-02 15:01:47 -0400495 // static boolean value, fold down to a single branch
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400496 if (test->as<BoolLiteral>().value()) {
John Stilesad2319f2020-09-02 15:01:47 -0400497 return ifTrue;
498 } else if (ifFalse) {
499 return ifFalse;
500 } else {
501 // False & no else clause. Not an error, so don't return null!
John Stiles2ff97062020-09-02 15:02:01 -0400502 return std::make_unique<Nop>();
John Stilesad2319f2020-09-02 15:01:47 -0400503 }
504 }
John Stiles4c412bc2020-10-13 11:19:41 -0400505 auto ifStmt = std::make_unique<IfStatement>(n.fOffset, n.getBool(), std::move(test),
506 std::move(ifTrue), std::move(ifFalse));
507 fInliner->ensureScopedBlocks(ifStmt->ifTrue().get(), ifStmt.get());
508 fInliner->ensureScopedBlocks(ifStmt->ifFalse().get(), ifStmt.get());
509 return std::move(ifStmt);
John Stilesad2319f2020-09-02 15:01:47 -0400510}
511
Ethan Nicholasfc994162019-06-06 10:04:27 -0400512std::unique_ptr<Statement> IRGenerator::convertFor(const ASTNode& f) {
513 SkASSERT(f.fKind == ASTNode::Kind::kFor);
ethannicholas22f939e2016-10-13 13:25:34 -0700514 AutoLoopLevel level(this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700515 AutoSymbolTable table(this);
ethannicholas22f939e2016-10-13 13:25:34 -0700516 std::unique_ptr<Statement> initializer;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400517 auto iter = f.begin();
518 if (*iter) {
519 initializer = this->convertStatement(*iter);
ethannicholas22f939e2016-10-13 13:25:34 -0700520 if (!initializer) {
521 return nullptr;
522 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700523 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400524 ++iter;
ethannicholas22f939e2016-10-13 13:25:34 -0700525 std::unique_ptr<Expression> test;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400526 if (*iter) {
John Stiles4c412bc2020-10-13 11:19:41 -0400527 AutoDisableInline disableInline(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400528 test = this->coerce(this->convertExpression(*iter), *fContext.fBool_Type);
ethannicholas22f939e2016-10-13 13:25:34 -0700529 if (!test) {
530 return nullptr;
531 }
John Stiles4c412bc2020-10-13 11:19:41 -0400532
ethannicholasb3058bd2016-07-01 08:22:01 -0700533 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400534 ++iter;
ethannicholas22f939e2016-10-13 13:25:34 -0700535 std::unique_ptr<Expression> next;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400536 if (*iter) {
John Stiles4c412bc2020-10-13 11:19:41 -0400537 AutoDisableInline disableInline(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400538 next = this->convertExpression(*iter);
ethannicholas22f939e2016-10-13 13:25:34 -0700539 if (!next) {
540 return nullptr;
541 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700542 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400543 ++iter;
544 std::unique_ptr<Statement> statement = this->convertStatement(*iter);
ethannicholasb3058bd2016-07-01 08:22:01 -0700545 if (!statement) {
546 return nullptr;
547 }
John Stiles4c412bc2020-10-13 11:19:41 -0400548 auto forStmt = std::make_unique<ForStatement>(f.fOffset, std::move(initializer),
549 std::move(test), std::move(next),
550 std::move(statement), fSymbolTable);
551 fInliner->ensureScopedBlocks(forStmt->statement().get(), forStmt.get());
552 return std::move(forStmt);
ethannicholasb3058bd2016-07-01 08:22:01 -0700553}
554
Ethan Nicholasfc994162019-06-06 10:04:27 -0400555std::unique_ptr<Statement> IRGenerator::convertWhile(const ASTNode& w) {
556 SkASSERT(w.fKind == ASTNode::Kind::kWhile);
ethannicholas22f939e2016-10-13 13:25:34 -0700557 AutoLoopLevel level(this);
John Stiles4c412bc2020-10-13 11:19:41 -0400558 std::unique_ptr<Expression> test;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400559 auto iter = w.begin();
John Stiles4c412bc2020-10-13 11:19:41 -0400560 {
561 AutoDisableInline disableInline(this);
562 test = this->coerce(this->convertExpression(*(iter++)), *fContext.fBool_Type);
563 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700564 if (!test) {
565 return nullptr;
566 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400567 std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700568 if (!statement) {
569 return nullptr;
570 }
John Stiles4c412bc2020-10-13 11:19:41 -0400571 auto whileStmt = std::make_unique<WhileStatement>(w.fOffset, std::move(test),
572 std::move(statement));
573 fInliner->ensureScopedBlocks(whileStmt->statement().get(), whileStmt.get());
574 return std::move(whileStmt);
ethannicholasb3058bd2016-07-01 08:22:01 -0700575}
576
Ethan Nicholasfc994162019-06-06 10:04:27 -0400577std::unique_ptr<Statement> IRGenerator::convertDo(const ASTNode& d) {
578 SkASSERT(d.fKind == ASTNode::Kind::kDo);
ethannicholas22f939e2016-10-13 13:25:34 -0700579 AutoLoopLevel level(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400580 auto iter = d.begin();
581 std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
582 if (!statement) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700583 return nullptr;
584 }
John Stiles4c412bc2020-10-13 11:19:41 -0400585 std::unique_ptr<Expression> test;
586 {
587 AutoDisableInline disableInline(this);
588 test = this->coerce(this->convertExpression(*(iter++)), *fContext.fBool_Type);
589 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400590 if (!test) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700591 return nullptr;
592 }
John Stiles4c412bc2020-10-13 11:19:41 -0400593 auto doStmt = std::make_unique<DoStatement>(d.fOffset, std::move(statement), std::move(test));
594 fInliner->ensureScopedBlocks(doStmt->statement().get(), doStmt.get());
595 return std::move(doStmt);
ethannicholasb3058bd2016-07-01 08:22:01 -0700596}
597
Ethan Nicholasfc994162019-06-06 10:04:27 -0400598std::unique_ptr<Statement> IRGenerator::convertSwitch(const ASTNode& s) {
599 SkASSERT(s.fKind == ASTNode::Kind::kSwitch);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500600 AutoSwitchLevel level(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400601 auto iter = s.begin();
602 std::unique_ptr<Expression> value = this->convertExpression(*(iter++));
Ethan Nicholasaf197692017-02-27 13:26:45 -0500603 if (!value) {
604 return nullptr;
605 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400606 if (value->type() != *fContext.fUInt_Type &&
607 value->type().typeKind() != Type::TypeKind::kEnum) {
Ethan Nicholasaf197692017-02-27 13:26:45 -0500608 value = this->coerce(std::move(value), *fContext.fInt_Type);
609 if (!value) {
610 return nullptr;
611 }
612 }
613 AutoSymbolTable table(this);
614 std::unordered_set<int> caseValues;
615 std::vector<std::unique_ptr<SwitchCase>> cases;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400616 for (; iter != s.end(); ++iter) {
617 const ASTNode& c = *iter;
618 SkASSERT(c.fKind == ASTNode::Kind::kSwitchCase);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500619 std::unique_ptr<Expression> caseValue;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400620 auto childIter = c.begin();
621 if (*childIter) {
622 caseValue = this->convertExpression(*childIter);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500623 if (!caseValue) {
624 return nullptr;
625 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400626 caseValue = this->coerce(std::move(caseValue), value->type());
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500627 if (!caseValue) {
628 return nullptr;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500629 }
Brian Osman3e3db6c2020-08-14 09:42:12 -0400630 int64_t v = 0;
631 if (!this->getConstantInt(*caseValue, &v)) {
632 fErrors.error(caseValue->fOffset, "case value must be a constant integer");
Ethan Nicholasaf197692017-02-27 13:26:45 -0500633 return nullptr;
634 }
Ethan Nicholasaf197692017-02-27 13:26:45 -0500635 if (caseValues.find(v) != caseValues.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700636 fErrors.error(caseValue->fOffset, "duplicate case value");
Ethan Nicholasaf197692017-02-27 13:26:45 -0500637 }
638 caseValues.insert(v);
639 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400640 ++childIter;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500641 std::vector<std::unique_ptr<Statement>> statements;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400642 for (; childIter != c.end(); ++childIter) {
643 std::unique_ptr<Statement> converted = this->convertStatement(*childIter);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500644 if (!converted) {
645 return nullptr;
646 }
647 statements.push_back(std::move(converted));
648 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400649 cases.emplace_back(new SwitchCase(c.fOffset, std::move(caseValue),
Ethan Nicholasaf197692017-02-27 13:26:45 -0500650 std::move(statements)));
651 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400652 return std::unique_ptr<Statement>(new SwitchStatement(s.fOffset, s.getBool(),
Ethan Nicholasc432b0c2017-07-18 13:22:37 -0400653 std::move(value), std::move(cases),
654 fSymbolTable));
Ethan Nicholasaf197692017-02-27 13:26:45 -0500655}
656
Ethan Nicholasfc994162019-06-06 10:04:27 -0400657std::unique_ptr<Statement> IRGenerator::convertExpressionStatement(const ASTNode& s) {
658 std::unique_ptr<Expression> e = this->convertExpression(s);
ethannicholasb3058bd2016-07-01 08:22:01 -0700659 if (!e) {
660 return nullptr;
661 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700662 return std::unique_ptr<Statement>(new ExpressionStatement(std::move(e)));
663}
664
Ethan Nicholasfc994162019-06-06 10:04:27 -0400665std::unique_ptr<Statement> IRGenerator::convertReturn(const ASTNode& r) {
666 SkASSERT(r.fKind == ASTNode::Kind::kReturn);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400667 SkASSERT(fCurrentFunction);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000668 // early returns from a vertex main function will bypass the sk_Position normalization, so
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400669 // SkASSERT that we aren't doing that. It is of course possible to fix this by adding a
Robert Phillipsfe8da172018-01-24 14:52:02 +0000670 // normalization before each return, but it will probably never actually be necessary.
Ethan Nicholase2c49992020-10-05 11:49:11 -0400671 SkASSERT(Program::kVertex_Kind != fKind || !fRTAdjust || "main" != fCurrentFunction->name());
Ethan Nicholasfc994162019-06-06 10:04:27 -0400672 if (r.begin() != r.end()) {
673 std::unique_ptr<Expression> result = this->convertExpression(*r.begin());
ethannicholasb3058bd2016-07-01 08:22:01 -0700674 if (!result) {
675 return nullptr;
676 }
Ethan Nicholased84b732020-10-08 11:45:44 -0400677 if (fCurrentFunction->returnType() == *fContext.fVoid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700678 fErrors.error(result->fOffset, "may not return a value from a void function");
Brian Osman5eea6ae2020-09-09 16:05:18 -0400679 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -0700680 } else {
Ethan Nicholased84b732020-10-08 11:45:44 -0400681 result = this->coerce(std::move(result), fCurrentFunction->returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700682 if (!result) {
683 return nullptr;
684 }
685 }
686 return std::unique_ptr<Statement>(new ReturnStatement(std::move(result)));
687 } else {
Ethan Nicholased84b732020-10-08 11:45:44 -0400688 if (fCurrentFunction->returnType() != *fContext.fVoid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700689 fErrors.error(r.fOffset, "expected function to return '" +
Ethan Nicholased84b732020-10-08 11:45:44 -0400690 fCurrentFunction->returnType().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -0700691 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700692 return std::unique_ptr<Statement>(new ReturnStatement(r.fOffset));
ethannicholasb3058bd2016-07-01 08:22:01 -0700693 }
694}
695
Ethan Nicholasfc994162019-06-06 10:04:27 -0400696std::unique_ptr<Statement> IRGenerator::convertBreak(const ASTNode& b) {
697 SkASSERT(b.fKind == ASTNode::Kind::kBreak);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500698 if (fLoopLevel > 0 || fSwitchLevel > 0) {
John Stilesb61ee902020-09-21 12:26:59 -0400699 return std::make_unique<BreakStatement>(b.fOffset);
ethannicholas22f939e2016-10-13 13:25:34 -0700700 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700701 fErrors.error(b.fOffset, "break statement must be inside a loop or switch");
ethannicholas22f939e2016-10-13 13:25:34 -0700702 return nullptr;
703 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700704}
705
Ethan Nicholasfc994162019-06-06 10:04:27 -0400706std::unique_ptr<Statement> IRGenerator::convertContinue(const ASTNode& c) {
707 SkASSERT(c.fKind == ASTNode::Kind::kContinue);
ethannicholas22f939e2016-10-13 13:25:34 -0700708 if (fLoopLevel > 0) {
John Stilesb61ee902020-09-21 12:26:59 -0400709 return std::make_unique<ContinueStatement>(c.fOffset);
ethannicholas22f939e2016-10-13 13:25:34 -0700710 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700711 fErrors.error(c.fOffset, "continue statement must be inside a loop");
ethannicholas22f939e2016-10-13 13:25:34 -0700712 return nullptr;
713 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700714}
715
Ethan Nicholasfc994162019-06-06 10:04:27 -0400716std::unique_ptr<Statement> IRGenerator::convertDiscard(const ASTNode& d) {
717 SkASSERT(d.fKind == ASTNode::Kind::kDiscard);
John Stilesb61ee902020-09-21 12:26:59 -0400718 return std::make_unique<DiscardStatement>(d.fOffset);
ethannicholasb3058bd2016-07-01 08:22:01 -0700719}
720
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500721std::unique_ptr<Block> IRGenerator::applyInvocationIDWorkaround(std::unique_ptr<Block> main) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400722 Layout invokeLayout;
723 Modifiers invokeModifiers(invokeLayout, Modifiers::kHasSideEffects_Flag);
John Stilesb8cc6652020-10-08 09:12:07 -0400724 const FunctionDeclaration* invokeDecl =
Ethan Nicholased84b732020-10-08 11:45:44 -0400725 fSymbolTable->add(std::make_unique<FunctionDeclaration>(
726 /*offset=*/-1,
727 fModifiers->handle(invokeModifiers),
728 "_invoke",
729 std::vector<Variable*>(),
730 fContext.fVoid_Type.get(),
731 /*builtin=*/false));
John Stilesb9af7232020-08-20 15:57:48 -0400732 fProgramElements->push_back(std::make_unique<FunctionDefinition>(/*offset=*/-1,
733 *invokeDecl,
734 std::move(main)));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400735
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000736 std::vector<std::unique_ptr<VarDeclaration>> variables;
John Stilesb9af7232020-08-20 15:57:48 -0400737 const Variable* loopIdx = &(*fSymbolTable)["sk_InvocationID"]->as<Variable>();
John Stiles8e3b6be2020-10-13 11:14:08 -0400738 auto test = std::make_unique<BinaryExpression>(/*offset=*/-1,
739 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx),
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400740 Token::Kind::TK_LT,
John Stiles8e3b6be2020-10-13 11:14:08 -0400741 std::make_unique<IntLiteral>(fContext, /*offset=*/-1, fInvocations),
742 fContext.fBool_Type.get());
743 auto next = std::make_unique<PostfixExpression>(
744 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx,
745 VariableReference::RefKind::kReadWrite),
746 Token::Kind::TK_PLUSPLUS);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400747 ASTNode endPrimitiveID(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier, "EndPrimitive");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400748 std::unique_ptr<Expression> endPrimitive = this->convertExpression(endPrimitiveID);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400749 SkASSERT(endPrimitive);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400750
751 std::vector<std::unique_ptr<Statement>> loopBody;
752 std::vector<std::unique_ptr<Expression>> invokeArgs;
John Stiles8e3b6be2020-10-13 11:14:08 -0400753 loopBody.push_back(std::make_unique<ExpressionStatement>(this->call(
754 /*offset=*/-1, *invokeDecl,
755 ExpressionArray{})));
756 loopBody.push_back(std::make_unique<ExpressionStatement>(this->call(
757 /*offset=*/-1, std::move(endPrimitive),
758 ExpressionArray{})));
759 auto assignment = std::make_unique<BinaryExpression>(/*offset=*/-1,
760 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx,
761 VariableReference::RefKind::kWrite),
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400762 Token::Kind::TK_EQ,
John Stiles8e3b6be2020-10-13 11:14:08 -0400763 std::make_unique<IntLiteral>(fContext, /*offset=*/-1, /*value=*/0),
764 fContext.fInt_Type.get());
765 auto initializer = std::make_unique<ExpressionStatement>(std::move(assignment));
766 auto loop = std::make_unique<ForStatement>(/*offset=*/-1,
767 std::move(initializer),
768 std::move(test), std::move(next),
769 std::make_unique<Block>(-1, std::move(loopBody)),
770 fSymbolTable);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400771 std::vector<std::unique_ptr<Statement>> children;
772 children.push_back(std::move(loop));
John Stilesfbd050b2020-08-03 13:21:46 -0400773 return std::make_unique<Block>(-1, std::move(children));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400774}
775
Robert Phillipsfe8da172018-01-24 14:52:02 +0000776std::unique_ptr<Statement> IRGenerator::getNormalizeSkPositionCode() {
Brian Osman88cda172020-10-09 12:05:16 -0400777 const Variable* skPerVertex = nullptr;
778 if (const ProgramElement* perVertexDecl = fIntrinsics->find(Compiler::PERVERTEX_NAME)) {
779 SkASSERT(perVertexDecl->is<InterfaceBlock>());
780 skPerVertex = perVertexDecl->as<InterfaceBlock>().fVariable;
781 }
782
Ethan Nicholasb809efb2018-04-12 14:39:21 -0400783 // sk_Position = float4(sk_Position.xy * rtAdjust.xz + sk_Position.ww * rtAdjust.yw,
Robert Phillipsfe8da172018-01-24 14:52:02 +0000784 // 0,
785 // sk_Position.w);
Brian Osman88cda172020-10-09 12:05:16 -0400786 SkASSERT(skPerVertex && fRTAdjust);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000787 #define REF(var) std::unique_ptr<Expression>(\
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400788 new VariableReference(-1, var, VariableReference::RefKind::kRead))
Ethan Nicholas4fadce42020-07-30 13:29:30 -0400789 #define WREF(var) std::unique_ptr<Expression>(\
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400790 new VariableReference(-1, var, VariableReference::RefKind::kWrite))
Robert Phillipsfe8da172018-01-24 14:52:02 +0000791 #define FIELD(var, idx) std::unique_ptr<Expression>(\
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400792 new FieldAccess(REF(var), idx, FieldAccess::OwnerKind::kAnonymousInterfaceBlock))
Brian Osman88cda172020-10-09 12:05:16 -0400793 #define POS std::unique_ptr<Expression>(new FieldAccess(WREF(skPerVertex), 0, \
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400794 FieldAccess::OwnerKind::kAnonymousInterfaceBlock))
Robert Phillipsfe8da172018-01-24 14:52:02 +0000795 #define ADJUST (fRTAdjustInterfaceBlock ? \
796 FIELD(fRTAdjustInterfaceBlock, fRTAdjustFieldIndex) : \
797 REF(fRTAdjust))
Ethan Nicholasb809efb2018-04-12 14:39:21 -0400798 #define SWIZZLE(expr, ...) std::unique_ptr<Expression>(new Swizzle(fContext, expr, \
799 { __VA_ARGS__ }))
800 #define OP(left, op, right) std::unique_ptr<Expression>( \
801 new BinaryExpression(-1, left, op, right, \
Ethan Nicholas30d30222020-09-11 12:27:26 -0400802 fContext.fFloat2_Type.get()))
John Stiles8e3b6be2020-10-13 11:14:08 -0400803 ExpressionArray children;
804 children.reserve(3);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400805 children.push_back(OP(OP(SWIZZLE(POS, 0, 1), Token::Kind::TK_STAR, SWIZZLE(ADJUST, 0, 2)),
806 Token::Kind::TK_PLUS,
807 OP(SWIZZLE(POS, 3, 3), Token::Kind::TK_STAR, SWIZZLE(ADJUST, 1, 3))));
John Stiles8e3b6be2020-10-13 11:14:08 -0400808 children.push_back(std::make_unique<FloatLiteral>(fContext, /*offset=*/-1, /*value=*/0.0));
Robert Phillipsfe8da172018-01-24 14:52:02 +0000809 children.push_back(SWIZZLE(POS, 3));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400810 std::unique_ptr<Expression> result = OP(POS, Token::Kind::TK_EQ,
John Stiles8e3b6be2020-10-13 11:14:08 -0400811 std::make_unique<Constructor>(/*offset=*/-1,
812 fContext.fFloat4_Type.get(),
813 std::move(children)));
814 return std::make_unique<ExpressionStatement>(std::move(result));
Robert Phillipsfe8da172018-01-24 14:52:02 +0000815}
816
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400817template<typename T>
818class AutoClear {
819public:
820 AutoClear(T* container)
821 : fContainer(container) {
822 SkASSERT(container->empty());
823 }
824
825 ~AutoClear() {
826 fContainer->clear();
827 }
828
829private:
830 T* fContainer;
831};
832
John Stilesb8e010c2020-08-11 18:05:39 -0400833template <typename T> AutoClear(T* c) -> AutoClear<T>;
834
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400835void IRGenerator::checkModifiers(int offset, const Modifiers& modifiers, int permitted) {
836 int flags = modifiers.fFlags;
837 #define CHECK(flag, name) \
838 if (!flags) return; \
839 if (flags & flag) { \
840 if (!(permitted & flag)) { \
841 fErrors.error(offset, "'" name "' is not permitted here"); \
842 } \
843 flags &= ~flag; \
844 }
845 CHECK(Modifiers::kConst_Flag, "const")
846 CHECK(Modifiers::kIn_Flag, "in")
847 CHECK(Modifiers::kOut_Flag, "out")
848 CHECK(Modifiers::kUniform_Flag, "uniform")
849 CHECK(Modifiers::kFlat_Flag, "flat")
850 CHECK(Modifiers::kNoPerspective_Flag, "noperspective")
851 CHECK(Modifiers::kReadOnly_Flag, "readonly")
852 CHECK(Modifiers::kWriteOnly_Flag, "writeonly")
853 CHECK(Modifiers::kCoherent_Flag, "coherent")
854 CHECK(Modifiers::kVolatile_Flag, "volatile")
855 CHECK(Modifiers::kRestrict_Flag, "restrict")
856 CHECK(Modifiers::kBuffer_Flag, "buffer")
857 CHECK(Modifiers::kHasSideEffects_Flag, "sk_has_side_effects")
858 CHECK(Modifiers::kPLS_Flag, "__pixel_localEXT")
859 CHECK(Modifiers::kPLSIn_Flag, "__pixel_local_inEXT")
860 CHECK(Modifiers::kPLSOut_Flag, "__pixel_local_outEXT")
861 CHECK(Modifiers::kVarying_Flag, "varying")
Ethan Nicholasf3c8f5d2020-08-20 13:09:14 +0000862 CHECK(Modifiers::kInline_Flag, "inline")
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400863 SkASSERT(flags == 0);
864}
865
Ethan Nicholasfc994162019-06-06 10:04:27 -0400866void IRGenerator::convertFunction(const ASTNode& f) {
John Stilesb8e010c2020-08-11 18:05:39 -0400867 AutoClear clear(&fReferencedIntrinsics);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400868 auto iter = f.begin();
Brian Osmand8070392020-09-09 15:50:02 -0400869 const Type* returnType = this->convertType(*(iter++), /*allowVoid=*/true);
John Stilesb9af7232020-08-20 15:57:48 -0400870 if (returnType == nullptr) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400871 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700872 }
Brian Osman3000d6b2020-07-31 15:57:28 -0400873 auto type_is_allowed = [&](const Type* t) {
874#if defined(SKSL_STANDALONE)
875 return true;
876#else
877 GrSLType unusedSLType;
878 return fKind != Program::kPipelineStage_Kind ||
879 type_to_grsltype(fContext, *t, &unusedSLType);
880#endif
881 };
882 if (returnType->nonnullable() == *fContext.fFragmentProcessor_Type ||
883 !type_is_allowed(returnType)) {
Brian Osman82329002020-07-21 09:39:27 -0400884 fErrors.error(f.fOffset,
885 "functions may not return type '" + returnType->displayName() + "'");
886 return;
887 }
John Stilesb9af7232020-08-20 15:57:48 -0400888 const ASTNode::FunctionData& funcData = f.getFunctionData();
889 this->checkModifiers(f.fOffset, funcData.fModifiers, Modifiers::kHasSideEffects_Flag |
890 Modifiers::kInline_Flag);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400891 std::vector<Variable*> parameters;
John Stilesb9af7232020-08-20 15:57:48 -0400892 for (size_t i = 0; i < funcData.fParameterCount; ++i) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400893 const ASTNode& param = *(iter++);
894 SkASSERT(param.fKind == ASTNode::Kind::kParameter);
895 ASTNode::ParameterData pd = param.getParameterData();
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400896 this->checkModifiers(param.fOffset, pd.fModifiers, Modifiers::kIn_Flag |
897 Modifiers::kOut_Flag);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400898 auto paramIter = param.begin();
899 const Type* type = this->convertType(*(paramIter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700900 if (!type) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400901 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700902 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400903 for (int j = (int) pd.fSizeCount; j >= 1; j--) {
904 int size = (param.begin() + j)->getInt();
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400905 String name = type->name() + "[" + to_string(size) + "]";
John Stiles3ae071e2020-08-05 15:29:29 -0400906 type = fSymbolTable->takeOwnershipOfSymbol(
Ethan Nicholase6592142020-09-08 10:22:09 -0400907 std::make_unique<Type>(std::move(name), Type::TypeKind::kArray, *type, size));
ethannicholasb3058bd2016-07-01 08:22:01 -0700908 }
Brian Osman3000d6b2020-07-31 15:57:28 -0400909 // Only the (builtin) declarations of 'sample' are allowed to have FP parameters
910 if ((type->nonnullable() == *fContext.fFragmentProcessor_Type && !fIsBuiltinCode) ||
911 !type_is_allowed(type)) {
912 fErrors.error(param.fOffset,
913 "parameters of type '" + type->displayName() + "' not allowed");
914 return;
915 }
Brian Osman8dbdf232020-10-12 14:40:24 -0400916
917 Modifiers m = pd.fModifiers;
918 if (funcData.fName == "main" && (fKind == Program::kPipelineStage_Kind ||
919 fKind == Program::kFragmentProcessor_Kind)) {
920 if (i == 0) {
921 // We verify that the type is correct later, for now, if there is a parameter to
922 // a .fp or runtime-effect main(), it's supposed to be the coords:
923 m.fLayout.fBuiltin = SK_MAIN_COORDS_BUILTIN;
924 }
925 }
926
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400927 Variable* var = fSymbolTable->takeOwnershipOfSymbol(
Brian Osman8dbdf232020-10-12 14:40:24 -0400928 std::make_unique<Variable>(param.fOffset, fModifiers->handle(m), pd.fName, type,
929 fIsBuiltinCode, Variable::Storage::kParameter));
ethannicholasd598f792016-07-25 10:08:54 -0700930 parameters.push_back(var);
ethannicholasb3058bd2016-07-01 08:22:01 -0700931 }
932
Brian Osman767f4442020-08-13 16:59:48 -0400933 auto paramIsCoords = [&](int idx) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400934 return parameters[idx]->type() == *fContext.fFloat2_Type &&
Brian Osman8dbdf232020-10-12 14:40:24 -0400935 parameters[idx]->modifiers().fFlags == 0 &&
936 parameters[idx]->modifiers().fLayout.fBuiltin == SK_MAIN_COORDS_BUILTIN;
Brian Osman767f4442020-08-13 16:59:48 -0400937 };
Brian Osman767f4442020-08-13 16:59:48 -0400938
John Stilesb9af7232020-08-20 15:57:48 -0400939 if (funcData.fName == "main") {
Ethan Nicholas0d997662019-04-08 09:46:01 -0400940 switch (fKind) {
941 case Program::kPipelineStage_Kind: {
Brian Osman767f4442020-08-13 16:59:48 -0400942 // half4 main() -or- half4 main(float2)
943 bool valid = (*returnType == *fContext.fHalf4_Type) &&
944 ((parameters.size() == 0) ||
945 (parameters.size() == 1 && paramIsCoords(0)));
946 if (!valid) {
947 fErrors.error(f.fOffset, "pipeline stage 'main' must be declared "
948 "half4 main() or half4 main(float2)");
949 return;
950 }
951 break;
Brian Osman44820a92020-08-26 09:27:39 -0400952 }
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400953 case Program::kFragmentProcessor_Kind: {
Brian Osman44820a92020-08-26 09:27:39 -0400954 bool valid = (parameters.size() == 0) ||
955 (parameters.size() == 1 && paramIsCoords(0));
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400956 if (!valid) {
957 fErrors.error(f.fOffset, ".fp 'main' must be declared main() or main(float2)");
958 return;
959 }
960 break;
961 }
Ethan Nicholas746035a2019-04-23 13:31:09 -0400962 case Program::kGeneric_Kind:
Ethan Nicholas0d997662019-04-08 09:46:01 -0400963 break;
Ethan Nicholas0d997662019-04-08 09:46:01 -0400964 default:
965 if (parameters.size()) {
966 fErrors.error(f.fOffset, "shader 'main' must have zero parameters");
967 }
Ethan Nicholas00543112018-07-31 09:44:36 -0400968 }
969 }
970
ethannicholasb3058bd2016-07-01 08:22:01 -0700971 // find existing declaration
ethannicholasd598f792016-07-25 10:08:54 -0700972 const FunctionDeclaration* decl = nullptr;
John Stilesb9af7232020-08-20 15:57:48 -0400973 const Symbol* entry = (*fSymbolTable)[funcData.fName];
ethannicholasb3058bd2016-07-01 08:22:01 -0700974 if (entry) {
ethannicholasd598f792016-07-25 10:08:54 -0700975 std::vector<const FunctionDeclaration*> functions;
Ethan Nicholase6592142020-09-08 10:22:09 -0400976 switch (entry->kind()) {
977 case Symbol::Kind::kUnresolvedFunction:
Ethan Nicholasceb62142020-10-09 16:51:18 -0400978 functions = entry->as<UnresolvedFunction>().functions();
ethannicholasb3058bd2016-07-01 08:22:01 -0700979 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400980 case Symbol::Kind::kFunctionDeclaration:
John Stiles17c5b702020-08-18 10:40:03 -0400981 functions.push_back(&entry->as<FunctionDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -0700982 break;
983 default:
John Stilesb9af7232020-08-20 15:57:48 -0400984 fErrors.error(f.fOffset, "symbol '" + funcData.fName + "' was already defined");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400985 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700986 }
John Stilesb9af7232020-08-20 15:57:48 -0400987 for (const FunctionDeclaration* other : functions) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400988 SkASSERT(other->name() == funcData.fName);
Ethan Nicholased84b732020-10-08 11:45:44 -0400989 if (parameters.size() == other->parameters().size()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700990 bool match = true;
991 for (size_t i = 0; i < parameters.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400992 if (parameters[i]->type() != other->parameters()[i]->type()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700993 match = false;
994 break;
995 }
996 }
997 if (match) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400998 if (*returnType != other->returnType()) {
999 FunctionDeclaration newDecl(f.fOffset,
1000 fModifiers->handle(funcData.fModifiers),
1001 funcData.fName,
1002 parameters,
1003 returnType,
1004 fIsBuiltinCode);
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001005 fErrors.error(f.fOffset, "functions '" + newDecl.description() +
1006 "' and '" + other->description() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001007 "' differ only in return type");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001008 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001009 }
1010 decl = other;
1011 for (size_t i = 0; i < parameters.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001012 if (parameters[i]->modifiers() != other->parameters()[i]->modifiers()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001013 fErrors.error(f.fOffset, "modifiers on parameter " +
1014 to_string((uint64_t) i + 1) +
John Stilesb9af7232020-08-20 15:57:48 -04001015 " differ between declaration and definition");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001016 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001017 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001018 }
Ethan Nicholased84b732020-10-08 11:45:44 -04001019 if (other->definition() && !other->isBuiltin()) {
John Stilesb9af7232020-08-20 15:57:48 -04001020 fErrors.error(f.fOffset, "duplicate definition of " + other->description());
ethannicholasb3058bd2016-07-01 08:22:01 -07001021 }
1022 break;
1023 }
1024 }
1025 }
1026 }
1027 if (!decl) {
John Stilesb9af7232020-08-20 15:57:48 -04001028 // Conservatively assume all user-defined functions have side effects.
1029 Modifiers declModifiers = funcData.fModifiers;
1030 if (!fIsBuiltinCode) {
1031 declModifiers.fFlags |= Modifiers::kHasSideEffects_Flag;
1032 }
1033
1034 // Create a new declaration.
Ethan Nicholased84b732020-10-08 11:45:44 -04001035 decl = fSymbolTable->add(std::make_unique<FunctionDeclaration>(
1036 f.fOffset,
1037 fModifiers->handle(declModifiers),
1038 funcData.fName,
1039 parameters,
1040 returnType,
1041 fIsBuiltinCode));
ethannicholasb3058bd2016-07-01 08:22:01 -07001042 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001043 if (iter != f.end()) {
1044 // compile body
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001045 SkASSERT(!fCurrentFunction);
ethannicholasd598f792016-07-25 10:08:54 -07001046 fCurrentFunction = decl;
ethannicholasd598f792016-07-25 10:08:54 -07001047 std::shared_ptr<SymbolTable> old = fSymbolTable;
1048 AutoSymbolTable table(this);
Ethan Nicholased84b732020-10-08 11:45:44 -04001049 const std::vector<Variable*>& declParameters = decl->parameters();
ethannicholasd598f792016-07-25 10:08:54 -07001050 for (size_t i = 0; i < parameters.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001051 fSymbolTable->addWithoutOwnership(declParameters[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -07001052 }
John Stilesb9af7232020-08-20 15:57:48 -04001053 bool needInvocationIDWorkaround = fInvocations != -1 && funcData.fName == "main" &&
Chris Daltonf1b47bb2017-10-06 11:57:51 -06001054 fSettings->fCaps &&
1055 !fSettings->fCaps->gsInvocationsSupport();
Ethan Nicholasfc994162019-06-06 10:04:27 -04001056 std::unique_ptr<Block> body = this->convertBlock(*iter);
ethannicholasd598f792016-07-25 10:08:54 -07001057 fCurrentFunction = nullptr;
1058 if (!body) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001059 return;
1060 }
1061 if (needInvocationIDWorkaround) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001062 body = this->applyInvocationIDWorkaround(std::move(body));
ethannicholasd598f792016-07-25 10:08:54 -07001063 }
John Stilesb9af7232020-08-20 15:57:48 -04001064 if (Program::kVertex_Kind == fKind && funcData.fName == "main" && fRTAdjust) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001065 body->children().push_back(this->getNormalizeSkPositionCode());
Robert Phillipsfe8da172018-01-24 14:52:02 +00001066 }
John Stilesb8e010c2020-08-11 18:05:39 -04001067 auto result = std::make_unique<FunctionDefinition>(f.fOffset, *decl, std::move(body),
1068 std::move(fReferencedIntrinsics));
Ethan Nicholased84b732020-10-08 11:45:44 -04001069 decl->setDefinition(result.get());
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001070 result->fSource = &f;
1071 fProgramElements->push_back(std::move(result));
ethannicholasb3058bd2016-07-01 08:22:01 -07001072 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001073}
1074
Ethan Nicholasfc994162019-06-06 10:04:27 -04001075std::unique_ptr<InterfaceBlock> IRGenerator::convertInterfaceBlock(const ASTNode& intf) {
Brian Osman16f376f2020-09-02 12:30:59 -04001076 if (fKind != Program::kFragment_Kind &&
1077 fKind != Program::kVertex_Kind &&
1078 fKind != Program::kGeometry_Kind) {
1079 fErrors.error(intf.fOffset, "interface block is not allowed here");
1080 return nullptr;
1081 }
1082
Ethan Nicholasfc994162019-06-06 10:04:27 -04001083 SkASSERT(intf.fKind == ASTNode::Kind::kInterfaceBlock);
1084 ASTNode::InterfaceBlockData id = intf.getInterfaceBlockData();
ethannicholasb3058bd2016-07-01 08:22:01 -07001085 std::shared_ptr<SymbolTable> old = fSymbolTable;
Ethan Nicholas68dd2c12018-03-01 15:05:17 -05001086 this->pushSymbolTable();
1087 std::shared_ptr<SymbolTable> symbols = fSymbolTable;
ethannicholasb3058bd2016-07-01 08:22:01 -07001088 std::vector<Type::Field> fields;
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001089 bool haveRuntimeArray = false;
Robert Phillipsfe8da172018-01-24 14:52:02 +00001090 bool foundRTAdjust = false;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001091 auto iter = intf.begin();
1092 for (size_t i = 0; i < id.fDeclarationCount; ++i) {
Brian Osmanc0213602020-10-06 14:43:32 -04001093 std::vector<std::unique_ptr<Statement>> decls =
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001094 this->convertVarDeclarations(*(iter++), Variable::Storage::kInterfaceBlock);
Brian Osmanc0213602020-10-06 14:43:32 -04001095 if (decls.empty()) {
ethannicholas7effa7a2016-10-14 09:56:33 -07001096 return nullptr;
1097 }
Brian Osmanc0213602020-10-06 14:43:32 -04001098 for (const auto& decl : decls) {
1099 const VarDeclaration& vd = decl->as<VarDeclaration>();
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001100 if (haveRuntimeArray) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001101 fErrors.error(decl->fOffset,
Brian Osmanc0213602020-10-06 14:43:32 -04001102 "only the last entry in an interface block may be a runtime-sized "
1103 "array");
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001104 }
Robert Phillipsfe8da172018-01-24 14:52:02 +00001105 if (vd.fVar == fRTAdjust) {
1106 foundRTAdjust = true;
Ethan Nicholas30d30222020-09-11 12:27:26 -04001107 SkASSERT(vd.fVar->type() == *fContext.fFloat4_Type);
Robert Phillipsfe8da172018-01-24 14:52:02 +00001108 fRTAdjustFieldIndex = fields.size();
1109 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001110 fields.push_back(Type::Field(vd.fVar->modifiers(), vd.fVar->name(),
Brian Osmanc0213602020-10-06 14:43:32 -04001111 &vd.fVar->type()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001112 if (vd.fValue) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001113 fErrors.error(decl->fOffset,
Brian Osmanc0213602020-10-06 14:43:32 -04001114 "initializers are not permitted on interface block fields");
ethannicholasb3058bd2016-07-01 08:22:01 -07001115 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001116 if (vd.fVar->type().typeKind() == Type::TypeKind::kArray &&
Brian Osmane8c26082020-10-01 17:22:45 -04001117 vd.fVar->type().columns() == Type::kUnsizedArray) {
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001118 haveRuntimeArray = true;
1119 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001120 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001121 }
Ethan Nicholas68dd2c12018-03-01 15:05:17 -05001122 this->popSymbolTable();
John Stiles3ae071e2020-08-05 15:29:29 -04001123 const Type* type =
1124 old->takeOwnershipOfSymbol(std::make_unique<Type>(intf.fOffset, id.fTypeName, fields));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001125 std::vector<std::unique_ptr<Expression>> sizes;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001126 for (size_t i = 0; i < id.fSizeCount; ++i) {
1127 const ASTNode& size = *(iter++);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001128 if (size) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001129 std::unique_ptr<Expression> converted = this->convertExpression(size);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001130 if (!converted) {
1131 return nullptr;
1132 }
Ethan Nicholase2c49992020-10-05 11:49:11 -04001133 String name = type->name();
Ethan Nicholas50afc172017-02-16 14:49:57 -05001134 int64_t count;
Ethan Nicholase6592142020-09-08 10:22:09 -04001135 if (converted->kind() == Expression::Kind::kIntLiteral) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001136 count = converted->as<IntLiteral>().value();
Ethan Nicholas50afc172017-02-16 14:49:57 -05001137 if (count <= 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001138 fErrors.error(converted->fOffset, "array size must be positive");
Ethan Nicholas66d80062019-09-09 14:50:51 -04001139 return nullptr;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001140 }
1141 name += "[" + to_string(count) + "]";
1142 } else {
Ethan Nicholas66d80062019-09-09 14:50:51 -04001143 fErrors.error(intf.fOffset, "array size must be specified");
1144 return nullptr;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001145 }
John Stiles3ae071e2020-08-05 15:29:29 -04001146 type = symbols->takeOwnershipOfSymbol(
Ethan Nicholase6592142020-09-08 10:22:09 -04001147 std::make_unique<Type>(name, Type::TypeKind::kArray, *type, (int)count));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001148 sizes.push_back(std::move(converted));
1149 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001150 String name = String(type->name()) + "[]";
Brian Osmane8c26082020-10-01 17:22:45 -04001151 type = symbols->takeOwnershipOfSymbol(std::make_unique<Type>(
1152 name, Type::TypeKind::kArray, *type, Type::kUnsizedArray));
1153 sizes.push_back(nullptr);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001154 }
1155 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001156 Variable* var = old->takeOwnershipOfSymbol(
John Stiles3ae071e2020-08-05 15:29:29 -04001157 std::make_unique<Variable>(intf.fOffset,
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001158 fModifiers->handle(id.fModifiers),
John Stiles3ae071e2020-08-05 15:29:29 -04001159 id.fInstanceName.fLength ? id.fInstanceName : id.fTypeName,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001160 type,
Brian Osman3887a012020-09-30 13:22:27 -04001161 fIsBuiltinCode,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001162 Variable::Storage::kGlobal));
Robert Phillipsfe8da172018-01-24 14:52:02 +00001163 if (foundRTAdjust) {
1164 fRTAdjustInterfaceBlock = var;
1165 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001166 if (id.fInstanceName.fLength) {
John Stilesb8cc6652020-10-08 09:12:07 -04001167 old->addWithoutOwnership(var);
ethannicholasb3058bd2016-07-01 08:22:01 -07001168 } else {
1169 for (size_t i = 0; i < fields.size(); i++) {
John Stilesb8cc6652020-10-08 09:12:07 -04001170 old->add(std::make_unique<Field>(intf.fOffset, var, (int)i));
ethannicholasb3058bd2016-07-01 08:22:01 -07001171 }
1172 }
John Stilesfbd050b2020-08-03 13:21:46 -04001173 return std::make_unique<InterfaceBlock>(intf.fOffset,
1174 var,
1175 id.fTypeName,
1176 id.fInstanceName,
1177 std::move(sizes),
1178 symbols);
ethannicholasb3058bd2016-07-01 08:22:01 -07001179}
1180
Brian Osman3e3db6c2020-08-14 09:42:12 -04001181bool IRGenerator::getConstantInt(const Expression& value, int64_t* out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001182 switch (value.kind()) {
1183 case Expression::Kind::kIntLiteral:
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001184 *out = value.as<IntLiteral>().value();
Brian Osman3e3db6c2020-08-14 09:42:12 -04001185 return true;
Ethan Nicholase6592142020-09-08 10:22:09 -04001186 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001187 const Variable& var = *value.as<VariableReference>().variable();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001188 return (var.modifiers().fFlags & Modifiers::kConst_Flag) &&
1189 var.initialValue() && this->getConstantInt(*var.initialValue(), out);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001190 }
1191 default:
Brian Osman3e3db6c2020-08-14 09:42:12 -04001192 return false;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001193 }
1194}
1195
Ethan Nicholasfc994162019-06-06 10:04:27 -04001196void IRGenerator::convertEnum(const ASTNode& e) {
Brian Osman16f376f2020-09-02 12:30:59 -04001197 if (fKind == Program::kPipelineStage_Kind) {
1198 fErrors.error(e.fOffset, "enum is not allowed here");
1199 return;
1200 }
1201
Ethan Nicholasfc994162019-06-06 10:04:27 -04001202 SkASSERT(e.fKind == ASTNode::Kind::kEnum);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001203 int64_t currentValue = 0;
1204 Layout layout;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001205 ASTNode enumType(e.fNodes, e.fOffset, ASTNode::Kind::kType,
1206 ASTNode::TypeData(e.getString(), false, false));
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001207 const Type* type = this->convertType(enumType);
1208 Modifiers modifiers(layout, Modifiers::kConst_Flag);
Brian Osman1313d1a2020-09-08 10:34:30 -04001209 std::shared_ptr<SymbolTable> oldTable = fSymbolTable;
1210 fSymbolTable = std::make_shared<SymbolTable>(fSymbolTable);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001211 for (auto iter = e.begin(); iter != e.end(); ++iter) {
1212 const ASTNode& child = *iter;
1213 SkASSERT(child.fKind == ASTNode::Kind::kEnumCase);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001214 std::unique_ptr<Expression> value;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001215 if (child.begin() != child.end()) {
1216 value = this->convertExpression(*child.begin());
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001217 if (!value) {
Brian Osman1313d1a2020-09-08 10:34:30 -04001218 fSymbolTable = oldTable;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001219 return;
1220 }
Brian Osman3e3db6c2020-08-14 09:42:12 -04001221 if (!this->getConstantInt(*value, &currentValue)) {
1222 fErrors.error(value->fOffset, "enum value must be a constant integer");
Brian Osman1313d1a2020-09-08 10:34:30 -04001223 fSymbolTable = oldTable;
Brian Osman3e3db6c2020-08-14 09:42:12 -04001224 return;
1225 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001226 }
1227 value = std::unique_ptr<Expression>(new IntLiteral(fContext, e.fOffset, currentValue));
1228 ++currentValue;
John Stilesb8cc6652020-10-08 09:12:07 -04001229 fSymbolTable->add(std::make_unique<Variable>(e.fOffset, fModifiers->handle(modifiers),
1230 child.getString(), type, fIsBuiltinCode,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001231 Variable::Storage::kGlobal, value.get()));
Brian Osman3e3db6c2020-08-14 09:42:12 -04001232 fSymbolTable->takeOwnershipOfIRNode(std::move(value));
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001233 }
Brian Osman1313d1a2020-09-08 10:34:30 -04001234 // Now we orphanize the Enum's symbol table, so that future lookups in it are strict
1235 fSymbolTable->fParent = nullptr;
Brian Osman3e3db6c2020-08-14 09:42:12 -04001236 fProgramElements->push_back(std::unique_ptr<ProgramElement>(
1237 new Enum(e.fOffset, e.getString(), fSymbolTable, fIsBuiltinCode)));
Brian Osman1313d1a2020-09-08 10:34:30 -04001238 fSymbolTable = oldTable;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001239}
1240
Brian Osmand8070392020-09-09 15:50:02 -04001241const Type* IRGenerator::convertType(const ASTNode& type, bool allowVoid) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001242 ASTNode::TypeData td = type.getTypeData();
1243 const Symbol* result = (*fSymbolTable)[td.fName];
Brian Osmand8070392020-09-09 15:50:02 -04001244 if (result && result->is<Type>()) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001245 if (td.fIsNullable) {
John Stiles17c5b702020-08-18 10:40:03 -04001246 if (result->as<Type>() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001247 if (type.begin() != type.end()) {
1248 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be used in "
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001249 "an array");
1250 }
John Stiles3ae071e2020-08-05 15:29:29 -04001251 result = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
Ethan Nicholase2c49992020-10-05 11:49:11 -04001252 String(result->name()) + "?", Type::TypeKind::kNullable,
1253 result->as<Type>()));
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001254 } else {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001255 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be nullable");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001256 }
1257 }
Brian Osmand8070392020-09-09 15:50:02 -04001258 if (result->as<Type>() == *fContext.fVoid_Type) {
1259 if (!allowVoid) {
1260 fErrors.error(type.fOffset, "type '" + td.fName + "' not allowed in this context");
1261 return nullptr;
1262 }
1263 if (type.begin() != type.end()) {
1264 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be used in an array");
1265 return nullptr;
1266 }
1267 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001268 for (const auto& size : type) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001269 String name(result->name());
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001270 name += "[";
Ethan Nicholasfc994162019-06-06 10:04:27 -04001271 if (size) {
1272 name += to_string(size.getInt());
Ethan Nicholas50afc172017-02-16 14:49:57 -05001273 }
1274 name += "]";
Brian Osmane8c26082020-10-01 17:22:45 -04001275 result = fSymbolTable->takeOwnershipOfSymbol(
1276 std::make_unique<Type>(name, Type::TypeKind::kArray, result->as<Type>(),
1277 size ? size.getInt() : Type::kUnsizedArray));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001278 }
John Stiles17c5b702020-08-18 10:40:03 -04001279 return &result->as<Type>();
ethannicholasb3058bd2016-07-01 08:22:01 -07001280 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001281 fErrors.error(type.fOffset, "unknown type '" + td.fName + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001282 return nullptr;
1283}
1284
Ethan Nicholasfc994162019-06-06 10:04:27 -04001285std::unique_ptr<Expression> IRGenerator::convertExpression(const ASTNode& expr) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001286 switch (expr.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001287 case ASTNode::Kind::kBinary:
1288 return this->convertBinaryExpression(expr);
1289 case ASTNode::Kind::kBool:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001290 return std::unique_ptr<Expression>(new BoolLiteral(fContext, expr.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04001291 expr.getBool()));
1292 case ASTNode::Kind::kCall:
1293 return this->convertCallExpression(expr);
1294 case ASTNode::Kind::kField:
1295 return this->convertFieldExpression(expr);
1296 case ASTNode::Kind::kFloat:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001297 return std::unique_ptr<Expression>(new FloatLiteral(fContext, expr.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04001298 expr.getFloat()));
1299 case ASTNode::Kind::kIdentifier:
1300 return this->convertIdentifier(expr);
1301 case ASTNode::Kind::kIndex:
1302 return this->convertIndexExpression(expr);
1303 case ASTNode::Kind::kInt:
1304 return std::unique_ptr<Expression>(new IntLiteral(fContext, expr.fOffset,
1305 expr.getInt()));
1306 case ASTNode::Kind::kNull:
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001307 return std::unique_ptr<Expression>(new NullLiteral(fContext, expr.fOffset));
Ethan Nicholasfc994162019-06-06 10:04:27 -04001308 case ASTNode::Kind::kPostfix:
1309 return this->convertPostfixExpression(expr);
1310 case ASTNode::Kind::kPrefix:
1311 return this->convertPrefixExpression(expr);
Brian Osman6518d772020-09-10 16:50:06 -04001312 case ASTNode::Kind::kScope:
1313 return this->convertScopeExpression(expr);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001314 case ASTNode::Kind::kTernary:
1315 return this->convertTernaryExpression(expr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001316 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001317#ifdef SK_DEBUG
Ethan Nicholasfc994162019-06-06 10:04:27 -04001318 ABORT("unsupported expression: %s\n", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001319#endif
1320 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001321 }
1322}
1323
Ethan Nicholasfc994162019-06-06 10:04:27 -04001324std::unique_ptr<Expression> IRGenerator::convertIdentifier(const ASTNode& identifier) {
1325 SkASSERT(identifier.fKind == ASTNode::Kind::kIdentifier);
1326 const Symbol* result = (*fSymbolTable)[identifier.getString()];
ethannicholasb3058bd2016-07-01 08:22:01 -07001327 if (!result) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001328 fErrors.error(identifier.fOffset, "unknown identifier '" + identifier.getString() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001329 return nullptr;
1330 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001331 switch (result->kind()) {
1332 case Symbol::Kind::kFunctionDeclaration: {
ethannicholasd598f792016-07-25 10:08:54 -07001333 std::vector<const FunctionDeclaration*> f = {
John Stiles17c5b702020-08-18 10:40:03 -04001334 &result->as<FunctionDeclaration>()
ethannicholasb3058bd2016-07-01 08:22:01 -07001335 };
John Stilesfbd050b2020-08-03 13:21:46 -04001336 return std::make_unique<FunctionReference>(fContext, identifier.fOffset, f);
ethannicholasb3058bd2016-07-01 08:22:01 -07001337 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001338 case Symbol::Kind::kUnresolvedFunction: {
John Stiles17c5b702020-08-18 10:40:03 -04001339 const UnresolvedFunction* f = &result->as<UnresolvedFunction>();
Ethan Nicholasceb62142020-10-09 16:51:18 -04001340 return std::make_unique<FunctionReference>(fContext, identifier.fOffset,
1341 f->functions());
ethannicholasb3058bd2016-07-01 08:22:01 -07001342 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001343 case Symbol::Kind::kVariable: {
John Stiles17c5b702020-08-18 10:40:03 -04001344 const Variable* var = &result->as<Variable>();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001345 const Modifiers& modifiers = var->modifiers();
1346 switch (modifiers.fLayout.fBuiltin) {
Ethan Nicholascd700e92018-08-24 16:43:57 -04001347 case SK_WIDTH_BUILTIN:
1348 fInputs.fRTWidth = true;
1349 break;
1350 case SK_HEIGHT_BUILTIN:
Greg Daniele6ab9982018-08-22 13:56:32 +00001351 fInputs.fRTHeight = true;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001352 break;
1353#ifndef SKSL_STANDALONE
1354 case SK_FRAGCOORD_BUILTIN:
Brian Osman9f313b62019-10-02 12:03:11 -04001355 fInputs.fFlipY = true;
1356 if (fSettings->fFlipY &&
1357 (!fSettings->fCaps ||
1358 !fSettings->fCaps->fragCoordConventionsExtensionString())) {
1359 fInputs.fRTHeight = true;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001360 }
Greg Daniele6ab9982018-08-22 13:56:32 +00001361#endif
Ethan Nicholascd700e92018-08-24 16:43:57 -04001362 }
Ethan Nicholas33c59ed2019-08-13 10:21:38 -04001363 if (fKind == Program::kFragmentProcessor_Kind &&
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001364 (modifiers.fFlags & Modifiers::kIn_Flag) &&
1365 !(modifiers.fFlags & Modifiers::kUniform_Flag) &&
1366 !modifiers.fLayout.fKey &&
1367 modifiers.fLayout.fBuiltin == -1 &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001368 var->type().nonnullable() != *fContext.fFragmentProcessor_Type &&
1369 var->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholas33c59ed2019-08-13 10:21:38 -04001370 bool valid = false;
1371 for (const auto& decl : fFile->root()) {
1372 if (decl.fKind == ASTNode::Kind::kSection) {
1373 ASTNode::SectionData section = decl.getSectionData();
1374 if (section.fName == "setData") {
1375 valid = true;
1376 break;
1377 }
1378 }
1379 }
1380 if (!valid) {
1381 fErrors.error(identifier.fOffset, "'in' variable must be either 'uniform' or "
1382 "'layout(key)', or there must be a custom "
1383 "@setData function");
1384 }
1385 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001386 // default to kRead_RefKind; this will be corrected later if the variable is written to
John Stilesfbd050b2020-08-03 13:21:46 -04001387 return std::make_unique<VariableReference>(identifier.fOffset,
Brian Osman79457ef2020-09-24 15:01:27 -04001388 var,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001389 VariableReference::RefKind::kRead);
ethannicholasb3058bd2016-07-01 08:22:01 -07001390 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001391 case Symbol::Kind::kField: {
John Stiles17c5b702020-08-18 10:40:03 -04001392 const Field* field = &result->as<Field>();
Brian Osman6a204db2020-10-08 09:29:02 -04001393 auto base = std::make_unique<VariableReference>(identifier.fOffset, &field->owner(),
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001394 VariableReference::RefKind::kRead);
Brian Osman6a204db2020-10-08 09:29:02 -04001395 return std::make_unique<FieldAccess>(std::move(base),
1396 field->fieldIndex(),
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001397 FieldAccess::OwnerKind::kAnonymousInterfaceBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -07001398 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001399 case Symbol::Kind::kType: {
John Stiles17c5b702020-08-18 10:40:03 -04001400 const Type* t = &result->as<Type>();
Ethan Nicholase6592142020-09-08 10:22:09 -04001401 return std::make_unique<TypeReference>(fContext, identifier.fOffset, t);
ethannicholasb3058bd2016-07-01 08:22:01 -07001402 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001403 case Symbol::Kind::kExternal: {
John Stiles17c5b702020-08-18 10:40:03 -04001404 const ExternalValue* r = &result->as<ExternalValue>();
John Stilesfbd050b2020-08-03 13:21:46 -04001405 return std::make_unique<ExternalValueReference>(identifier.fOffset, r);
Ethan Nicholas91164d12019-05-15 15:29:54 -04001406 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001407 default:
Ethan Nicholase6592142020-09-08 10:22:09 -04001408 ABORT("unsupported symbol type %d\n", (int) result->kind());
ethannicholasb3058bd2016-07-01 08:22:01 -07001409 }
Ethan Nicholasc0709392017-06-27 11:20:22 -04001410}
1411
Ethan Nicholasfc994162019-06-06 10:04:27 -04001412std::unique_ptr<Section> IRGenerator::convertSection(const ASTNode& s) {
Brian Osman16f376f2020-09-02 12:30:59 -04001413 if (fKind != Program::kFragmentProcessor_Kind) {
1414 fErrors.error(s.fOffset, "syntax error");
1415 return nullptr;
1416 }
1417
Ethan Nicholasfc994162019-06-06 10:04:27 -04001418 ASTNode::SectionData section = s.getSectionData();
John Stilesfbd050b2020-08-03 13:21:46 -04001419 return std::make_unique<Section>(s.fOffset, section.fName, section.fArgument,
1420 section.fText);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001421}
1422
Ethan Nicholas11d53972016-11-28 11:23:23 -05001423std::unique_ptr<Expression> IRGenerator::coerce(std::unique_ptr<Expression> expr,
ethannicholasd598f792016-07-25 10:08:54 -07001424 const Type& type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001425 if (!expr) {
1426 return nullptr;
1427 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001428 if (expr->type() == type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001429 return expr;
1430 }
1431 this->checkValid(*expr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001432 if (expr->type() == *fContext.fInvalid_Type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001433 return nullptr;
1434 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001435 if (!expr->coercionCost(type).isPossible(fSettings->fAllowNarrowingConversions)) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001436 fErrors.error(expr->fOffset, "expected '" + type.displayName() + "', but found '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04001437 expr->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001438 return nullptr;
1439 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001440 if (type.typeKind() == Type::TypeKind::kScalar) {
John Stiles8e3b6be2020-10-13 11:14:08 -04001441 ExpressionArray args;
ethannicholasb3058bd2016-07-01 08:22:01 -07001442 args.push_back(std::move(expr));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001443 std::unique_ptr<Expression> ctor;
1444 if (type == *fContext.fFloatLiteral_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001445 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
1446 "float"));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001447 } else if (type == *fContext.fIntLiteral_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001448 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
1449 "int"));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001450 } else {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001451 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
Ethan Nicholase2c49992020-10-05 11:49:11 -04001452 type.name()));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001453 }
1454 if (!ctor) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001455 printf("error, null identifier: %s\n", String(type.name()).c_str());
Ethan Nicholase1f55022019-02-05 17:17:40 -05001456 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001457 SkASSERT(ctor);
John Stiles8e3b6be2020-10-13 11:14:08 -04001458 return this->call(/*offset=*/-1, std::move(ctor), std::move(args));
ethannicholasb3058bd2016-07-01 08:22:01 -07001459 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001460 if (expr->kind() == Expression::Kind::kNullLiteral) {
1461 SkASSERT(type.typeKind() == Type::TypeKind::kNullable);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001462 return std::unique_ptr<Expression>(new NullLiteral(expr->fOffset, &type));
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001463 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001464 ExpressionArray args;
ethannicholas5961bc92016-10-12 06:39:56 -07001465 args.push_back(std::move(expr));
John Stiles8e3b6be2020-10-13 11:14:08 -04001466 return std::make_unique<Constructor>(/*offset=*/-1, &type, std::move(args));
ethannicholasb3058bd2016-07-01 08:22:01 -07001467}
1468
ethannicholasf789b382016-08-03 12:43:36 -07001469static bool is_matrix_multiply(const Type& left, const Type& right) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001470 if (left.typeKind() == Type::TypeKind::kMatrix) {
1471 return right.typeKind() == Type::TypeKind::kMatrix ||
1472 right.typeKind() == Type::TypeKind::kVector;
ethannicholasf789b382016-08-03 12:43:36 -07001473 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001474 return left.typeKind() == Type::TypeKind::kVector &&
1475 right.typeKind() == Type::TypeKind::kMatrix;
ethannicholasf789b382016-08-03 12:43:36 -07001476}
ethannicholasea4567c2016-10-17 11:24:37 -07001477
ethannicholasb3058bd2016-07-01 08:22:01 -07001478/**
1479 * Determines the operand and result types of a binary expression. Returns true if the expression is
1480 * legal, false otherwise. If false, the values of the out parameters are undefined.
1481 */
Ethan Nicholas11d53972016-11-28 11:23:23 -05001482static bool determine_binary_type(const Context& context,
Brian Osman0acb5b52020-09-02 13:45:47 -04001483 bool allowNarrowing,
Ethan Nicholas11d53972016-11-28 11:23:23 -05001484 Token::Kind op,
1485 const Type& left,
1486 const Type& right,
ethannicholasd598f792016-07-25 10:08:54 -07001487 const Type** outLeftType,
1488 const Type** outRightType,
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001489 const Type** outResultType) {
1490 bool isLogical = false;
Brian Osmanbf2163f2020-09-16 16:21:40 -04001491 bool isBitwise = false;
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001492 bool validMatrixOrVectorOp = false;
1493 bool isAssignment = Compiler::IsAssignment(op);
1494
ethannicholasb3058bd2016-07-01 08:22:01 -07001495 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001496 case Token::Kind::TK_EQ:
ethannicholasea4567c2016-10-17 11:24:37 -07001497 *outLeftType = &left;
1498 *outRightType = &left;
1499 *outResultType = &left;
Brian Osman0acb5b52020-09-02 13:45:47 -04001500 return right.canCoerceTo(left, allowNarrowing);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001501 case Token::Kind::TK_EQEQ: // fall through
Brian Osman0acb5b52020-09-02 13:45:47 -04001502 case Token::Kind::TK_NEQ: {
1503 CoercionCost rightToLeft = right.coercionCost(left),
1504 leftToRight = left.coercionCost(right);
1505 if (rightToLeft < leftToRight) {
1506 if (rightToLeft.isPossible(allowNarrowing)) {
1507 *outLeftType = &left;
1508 *outRightType = &left;
1509 *outResultType = context.fBool_Type.get();
1510 return true;
1511 }
1512 } else {
1513 if (leftToRight.isPossible(allowNarrowing)) {
1514 *outLeftType = &right;
1515 *outRightType = &right;
1516 *outResultType = context.fBool_Type.get();
1517 return true;
1518 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001519 }
Ethan Nicholas23463002018-03-28 15:16:15 -04001520 return false;
Brian Osman0acb5b52020-09-02 13:45:47 -04001521 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001522 case Token::Kind::TK_LT: // fall through
1523 case Token::Kind::TK_GT: // fall through
1524 case Token::Kind::TK_LTEQ: // fall through
1525 case Token::Kind::TK_GTEQ:
ethannicholasb3058bd2016-07-01 08:22:01 -07001526 isLogical = true;
1527 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001528 case Token::Kind::TK_LOGICALOR: // fall through
1529 case Token::Kind::TK_LOGICALAND: // fall through
1530 case Token::Kind::TK_LOGICALXOR: // fall through
1531 case Token::Kind::TK_LOGICALOREQ: // fall through
1532 case Token::Kind::TK_LOGICALANDEQ: // fall through
1533 case Token::Kind::TK_LOGICALXOREQ:
ethannicholasd598f792016-07-25 10:08:54 -07001534 *outLeftType = context.fBool_Type.get();
1535 *outRightType = context.fBool_Type.get();
1536 *outResultType = context.fBool_Type.get();
Brian Osman0acb5b52020-09-02 13:45:47 -04001537 return left.canCoerceTo(*context.fBool_Type, allowNarrowing) &&
1538 right.canCoerceTo(*context.fBool_Type, allowNarrowing);
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001539 case Token::Kind::TK_STAREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001540 case Token::Kind::TK_STAR:
ethannicholasf789b382016-08-03 12:43:36 -07001541 if (is_matrix_multiply(left, right)) {
1542 // determine final component type
Brian Osman3ed22a92020-09-17 15:10:25 -04001543 if (determine_binary_type(context, allowNarrowing, op,
Brian Osman0acb5b52020-09-02 13:45:47 -04001544 left.componentType(), right.componentType(),
1545 outLeftType, outRightType, outResultType)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001546 *outLeftType = &(*outResultType)->toCompound(context, left.columns(),
Brian Salomon23356442018-11-30 15:33:19 -05001547 left.rows());
Ethan Nicholas11d53972016-11-28 11:23:23 -05001548 *outRightType = &(*outResultType)->toCompound(context, right.columns(),
Brian Salomon23356442018-11-30 15:33:19 -05001549 right.rows());
ethannicholasf789b382016-08-03 12:43:36 -07001550 int leftColumns = left.columns();
1551 int leftRows = left.rows();
1552 int rightColumns;
1553 int rightRows;
Ethan Nicholase6592142020-09-08 10:22:09 -04001554 if (right.typeKind() == Type::TypeKind::kVector) {
ethannicholasf789b382016-08-03 12:43:36 -07001555 // matrix * vector treats the vector as a column vector, so we need to
1556 // transpose it
1557 rightColumns = right.rows();
1558 rightRows = right.columns();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001559 SkASSERT(rightColumns == 1);
ethannicholasf789b382016-08-03 12:43:36 -07001560 } else {
1561 rightColumns = right.columns();
1562 rightRows = right.rows();
1563 }
1564 if (rightColumns > 1) {
1565 *outResultType = &(*outResultType)->toCompound(context, rightColumns,
1566 leftRows);
1567 } else {
1568 // result was a column vector, transpose it back to a row
1569 *outResultType = &(*outResultType)->toCompound(context, leftRows,
1570 rightColumns);
1571 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001572 if (isAssignment && ((*outResultType)->columns() != leftColumns ||
1573 (*outResultType)->rows() != leftRows)) {
1574 return false;
1575 }
ethannicholasf789b382016-08-03 12:43:36 -07001576 return leftColumns == rightRows;
1577 } else {
1578 return false;
1579 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001580 }
ethannicholasea4567c2016-10-17 11:24:37 -07001581 validMatrixOrVectorOp = true;
1582 break;
Brian Osmanbf2163f2020-09-16 16:21:40 -04001583 case Token::Kind::TK_SHLEQ:
1584 case Token::Kind::TK_SHREQ:
1585 case Token::Kind::TK_BITWISEANDEQ:
1586 case Token::Kind::TK_BITWISEOREQ:
1587 case Token::Kind::TK_BITWISEXOREQ:
1588 case Token::Kind::TK_SHL:
1589 case Token::Kind::TK_SHR:
1590 case Token::Kind::TK_BITWISEAND:
1591 case Token::Kind::TK_BITWISEOR:
1592 case Token::Kind::TK_BITWISEXOR:
1593 isBitwise = true;
1594 validMatrixOrVectorOp = true;
1595 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001596 case Token::Kind::TK_PLUSEQ:
1597 case Token::Kind::TK_MINUSEQ:
1598 case Token::Kind::TK_SLASHEQ:
1599 case Token::Kind::TK_PERCENTEQ:
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001600 case Token::Kind::TK_PLUS:
1601 case Token::Kind::TK_MINUS:
1602 case Token::Kind::TK_SLASH:
1603 case Token::Kind::TK_PERCENT:
ethannicholasea4567c2016-10-17 11:24:37 -07001604 validMatrixOrVectorOp = true;
1605 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001606 case Token::Kind::TK_COMMA:
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001607 *outLeftType = &left;
1608 *outRightType = &right;
1609 *outResultType = &right;
1610 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001611 default:
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001612 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001613 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001614
1615 bool leftIsVectorOrMatrix = left.typeKind() == Type::TypeKind::kVector ||
1616 left.typeKind() == Type::TypeKind::kMatrix,
1617 rightIsVectorOrMatrix = right.typeKind() == Type::TypeKind::kVector ||
1618 right.typeKind() == Type::TypeKind::kMatrix;
1619
1620 if (leftIsVectorOrMatrix && validMatrixOrVectorOp &&
1621 right.typeKind() == Type::TypeKind::kScalar) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001622 if (determine_binary_type(context, allowNarrowing, op, left.componentType(), right,
1623 outLeftType, outRightType, outResultType)) {
ethannicholasd598f792016-07-25 10:08:54 -07001624 *outLeftType = &(*outLeftType)->toCompound(context, left.columns(), left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001625 if (!isLogical) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001626 *outResultType =
1627 &(*outResultType)->toCompound(context, left.columns(), left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001628 }
1629 return true;
1630 }
1631 return false;
1632 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001633
1634 if (!isAssignment && rightIsVectorOrMatrix && validMatrixOrVectorOp &&
1635 left.typeKind() == Type::TypeKind::kScalar) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001636 if (determine_binary_type(context, allowNarrowing, op, left, right.componentType(),
1637 outLeftType, outRightType, outResultType)) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001638 *outRightType = &(*outRightType)->toCompound(context, right.columns(), right.rows());
1639 if (!isLogical) {
1640 *outResultType =
1641 &(*outResultType)->toCompound(context, right.columns(), right.rows());
1642 }
1643 return true;
1644 }
1645 return false;
1646 }
1647
Brian Osman0acb5b52020-09-02 13:45:47 -04001648 CoercionCost rightToLeftCost = right.coercionCost(left);
1649 CoercionCost leftToRightCost = isAssignment ? CoercionCost::Impossible()
1650 : left.coercionCost(right);
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001651
1652 if ((left.typeKind() == Type::TypeKind::kScalar &&
1653 right.typeKind() == Type::TypeKind::kScalar) ||
1654 (leftIsVectorOrMatrix && validMatrixOrVectorOp)) {
Brian Osmanbf2163f2020-09-16 16:21:40 -04001655 if (isBitwise) {
1656 const Type& leftNumberType(leftIsVectorOrMatrix ? left.componentType() : left);
1657 const Type& rightNumberType(rightIsVectorOrMatrix ? right.componentType() : right);
1658 if (!leftNumberType.isInteger() || !rightNumberType.isInteger()) {
1659 return false;
1660 }
1661 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001662 if (rightToLeftCost.isPossible(allowNarrowing) && rightToLeftCost < leftToRightCost) {
1663 // Right-to-Left conversion is possible and cheaper
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001664 *outLeftType = &left;
1665 *outRightType = &left;
1666 *outResultType = &left;
Brian Osman0acb5b52020-09-02 13:45:47 -04001667 } else if (leftToRightCost.isPossible(allowNarrowing)) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001668 // Left-to-Right conversion is possible (and at least as cheap as Right-to-Left)
1669 *outLeftType = &right;
1670 *outRightType = &right;
1671 *outResultType = &right;
1672 } else {
1673 return false;
1674 }
1675 if (isLogical) {
1676 *outResultType = context.fBool_Type.get();
1677 }
1678 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001679 }
1680 return false;
1681}
1682
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001683static std::unique_ptr<Expression> short_circuit_boolean(const Context& context,
1684 const Expression& left,
1685 Token::Kind op,
1686 const Expression& right) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001687 SkASSERT(left.kind() == Expression::Kind::kBoolLiteral);
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001688 bool leftVal = left.as<BoolLiteral>().value();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001689 if (op == Token::Kind::TK_LOGICALAND) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001690 // (true && expr) -> (expr) and (false && expr) -> (false)
1691 return leftVal ? right.clone()
1692 : std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, false));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001693 } else if (op == Token::Kind::TK_LOGICALOR) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001694 // (true || expr) -> (true) and (false || expr) -> (expr)
1695 return leftVal ? std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, true))
1696 : right.clone();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001697 } else if (op == Token::Kind::TK_LOGICALXOR) {
Noah Lavine334d0ba2019-12-18 23:03:49 -05001698 // (true ^^ expr) -> !(expr) and (false ^^ expr) -> (expr)
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001699 return leftVal ? std::unique_ptr<Expression>(new PrefixExpression(
1700 Token::Kind::TK_LOGICALNOT,
1701 right.clone()))
Noah Lavine334d0ba2019-12-18 23:03:49 -05001702 : right.clone();
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001703 } else {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001704 return nullptr;
1705 }
1706}
1707
ethannicholas08a92112016-11-09 13:26:45 -08001708std::unique_ptr<Expression> IRGenerator::constantFold(const Expression& left,
1709 Token::Kind op,
Ethan Nicholas86a43402017-01-19 13:32:00 -05001710 const Expression& right) const {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001711 // If the left side is a constant boolean literal, the right side does not need to be constant
1712 // for short circuit optimizations to allow the constant to be folded.
Ethan Nicholase6592142020-09-08 10:22:09 -04001713 if (left.kind() == Expression::Kind::kBoolLiteral && !right.isCompileTimeConstant()) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001714 return short_circuit_boolean(fContext, left, op, right);
Ethan Nicholase6592142020-09-08 10:22:09 -04001715 } else if (right.kind() == Expression::Kind::kBoolLiteral && !left.isCompileTimeConstant()) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001716 // There aren't side effects in SKSL within expressions, so (left OP right) is equivalent to
1717 // (right OP left) for short-circuit optimizations
1718 return short_circuit_boolean(fContext, right, op, left);
1719 }
1720
1721 // Other than the short-circuit cases above, constant folding requires both sides to be constant
Brian Osmanb6b95732020-06-30 11:44:27 -04001722 if (!left.isCompileTimeConstant() || !right.isCompileTimeConstant()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001723 return nullptr;
1724 }
ethannicholas08a92112016-11-09 13:26:45 -08001725 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
1726 // precision to calculate the results and hope the result makes sense. The plan is to move the
1727 // Skia caps into SkSL, so we have access to all of them including the precisions of the various
1728 // types, which will let us be more intelligent about this.
Ethan Nicholase6592142020-09-08 10:22:09 -04001729 if (left.kind() == Expression::Kind::kBoolLiteral &&
1730 right.kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001731 bool leftVal = left.as<BoolLiteral>().value();
1732 bool rightVal = right.as<BoolLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001733 bool result;
1734 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001735 case Token::Kind::TK_LOGICALAND: result = leftVal && rightVal; break;
1736 case Token::Kind::TK_LOGICALOR: result = leftVal || rightVal; break;
1737 case Token::Kind::TK_LOGICALXOR: result = leftVal ^ rightVal; break;
ethannicholas08a92112016-11-09 13:26:45 -08001738 default: return nullptr;
1739 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001740 return std::unique_ptr<Expression>(new BoolLiteral(fContext, left.fOffset, result));
ethannicholas08a92112016-11-09 13:26:45 -08001741 }
John Stilesfbd050b2020-08-03 13:21:46 -04001742 #define RESULT(t, op) std::make_unique<t ## Literal>(fContext, left.fOffset, \
1743 leftVal op rightVal)
1744 #define URESULT(t, op) std::make_unique<t ## Literal>(fContext, left.fOffset, \
1745 (uint32_t) leftVal op \
1746 (uint32_t) rightVal)
Ethan Nicholase6592142020-09-08 10:22:09 -04001747 if (left.kind() == Expression::Kind::kIntLiteral &&
1748 right.kind() == Expression::Kind::kIntLiteral) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001749 int64_t leftVal = left.as<IntLiteral>().value();
1750 int64_t rightVal = right.as<IntLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001751 switch (op) {
Ethan Nicholas66869e92020-04-30 09:27:54 -04001752 case Token::Kind::TK_PLUS: return URESULT(Int, +);
1753 case Token::Kind::TK_MINUS: return URESULT(Int, -);
1754 case Token::Kind::TK_STAR: return URESULT(Int, *);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001755 case Token::Kind::TK_SLASH:
Ethan Nicholas66869e92020-04-30 09:27:54 -04001756 if (leftVal == std::numeric_limits<int64_t>::min() && rightVal == -1) {
1757 fErrors.error(right.fOffset, "arithmetic overflow");
1758 return nullptr;
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001759 }
Ethan Nicholas66869e92020-04-30 09:27:54 -04001760 if (!rightVal) {
1761 fErrors.error(right.fOffset, "division by zero");
1762 return nullptr;
1763 }
1764 return RESULT(Int, /);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001765 case Token::Kind::TK_PERCENT:
Ethan Nicholas66869e92020-04-30 09:27:54 -04001766 if (leftVal == std::numeric_limits<int64_t>::min() && rightVal == -1) {
1767 fErrors.error(right.fOffset, "arithmetic overflow");
1768 return nullptr;
Ethan Nicholas2503ab62017-01-05 10:44:25 -05001769 }
Ethan Nicholas66869e92020-04-30 09:27:54 -04001770 if (!rightVal) {
1771 fErrors.error(right.fOffset, "division by zero");
1772 return nullptr;
1773 }
1774 return RESULT(Int, %);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001775 case Token::Kind::TK_BITWISEAND: return RESULT(Int, &);
1776 case Token::Kind::TK_BITWISEOR: return RESULT(Int, |);
1777 case Token::Kind::TK_BITWISEXOR: return RESULT(Int, ^);
1778 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
1779 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
1780 case Token::Kind::TK_GT: return RESULT(Bool, >);
1781 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
1782 case Token::Kind::TK_LT: return RESULT(Bool, <);
1783 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
1784 case Token::Kind::TK_SHL:
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001785 if (rightVal >= 0 && rightVal <= 31) {
Ethan Nicholase4489002020-04-29 14:00:14 -04001786 return URESULT(Int, <<);
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001787 }
1788 fErrors.error(right.fOffset, "shift value out of range");
1789 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001790 case Token::Kind::TK_SHR:
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001791 if (rightVal >= 0 && rightVal <= 31) {
Ethan Nicholase4489002020-04-29 14:00:14 -04001792 return URESULT(Int, >>);
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001793 }
1794 fErrors.error(right.fOffset, "shift value out of range");
1795 return nullptr;
1796
1797 default:
1798 return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001799 }
1800 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001801 if (left.kind() == Expression::Kind::kFloatLiteral &&
1802 right.kind() == Expression::Kind::kFloatLiteral) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001803 SKSL_FLOAT leftVal = left.as<FloatLiteral>().value();
1804 SKSL_FLOAT rightVal = right.as<FloatLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001805 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001806 case Token::Kind::TK_PLUS: return RESULT(Float, +);
1807 case Token::Kind::TK_MINUS: return RESULT(Float, -);
1808 case Token::Kind::TK_STAR: return RESULT(Float, *);
1809 case Token::Kind::TK_SLASH:
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001810 if (rightVal) {
1811 return RESULT(Float, /);
1812 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001813 fErrors.error(right.fOffset, "division by zero");
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001814 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001815 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
1816 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
1817 case Token::Kind::TK_GT: return RESULT(Bool, >);
1818 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
1819 case Token::Kind::TK_LT: return RESULT(Bool, <);
1820 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
1821 default: return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001822 }
1823 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001824 const Type& leftType = left.type();
1825 const Type& rightType = right.type();
1826 if (leftType.typeKind() == Type::TypeKind::kVector && leftType.componentType().isFloat() &&
1827 leftType == rightType) {
John Stiles8e3b6be2020-10-13 11:14:08 -04001828 ExpressionArray args;
1829 #define RETURN_VEC_COMPONENTWISE_RESULT(op) \
1830 for (int i = 0; i < leftType.columns(); i++) { \
1831 SKSL_FLOAT value = left.getFVecComponent(i) op right.getFVecComponent(i); \
1832 args.push_back(std::make_unique<FloatLiteral>(fContext, /*offset=*/-1, value)); \
1833 } \
1834 return std::make_unique<Constructor>(/*offset=*/-1, &leftType, std::move(args))
Ethan Nicholascb670962017-04-20 19:31:52 -04001835 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001836 case Token::Kind::TK_EQEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001837 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001838 left.compareConstant(fContext, right)));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001839 case Token::Kind::TK_NEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001840 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001841 !left.compareConstant(fContext, right)));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001842 case Token::Kind::TK_PLUS: RETURN_VEC_COMPONENTWISE_RESULT(+);
1843 case Token::Kind::TK_MINUS: RETURN_VEC_COMPONENTWISE_RESULT(-);
1844 case Token::Kind::TK_STAR: RETURN_VEC_COMPONENTWISE_RESULT(*);
1845 case Token::Kind::TK_SLASH:
Ethan Nicholas30d30222020-09-11 12:27:26 -04001846 for (int i = 0; i < leftType.columns(); i++) {
Ethan Nicholas4cf5fd92019-06-10 16:15:56 -04001847 SKSL_FLOAT rvalue = right.getFVecComponent(i);
1848 if (rvalue == 0.0) {
1849 fErrors.error(right.fOffset, "division by zero");
1850 return nullptr;
1851 }
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001852 SKSL_FLOAT value = left.getFVecComponent(i) / rvalue;
John Stiles8e3b6be2020-10-13 11:14:08 -04001853 args.push_back(std::make_unique<FloatLiteral>(fContext, /*offset=*/-1, value));
Ethan Nicholas4cf5fd92019-06-10 16:15:56 -04001854 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001855 return std::make_unique<Constructor>(/*offset=*/-1, &leftType, std::move(args));
Ethan Nicholase6592142020-09-08 10:22:09 -04001856 default:
1857 return nullptr;
Ethan Nicholascb670962017-04-20 19:31:52 -04001858 }
1859 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001860 if (leftType.typeKind() == Type::TypeKind::kMatrix &&
1861 rightType.typeKind() == Type::TypeKind::kMatrix &&
Ethan Nicholase6592142020-09-08 10:22:09 -04001862 left.kind() == right.kind()) {
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001863 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001864 case Token::Kind::TK_EQEQ:
John Stiles8e3b6be2020-10-13 11:14:08 -04001865 return std::make_unique<BoolLiteral>(fContext, /*offset=*/-1,
1866 left.compareConstant(fContext, right));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001867 case Token::Kind::TK_NEQ:
John Stiles8e3b6be2020-10-13 11:14:08 -04001868 return std::make_unique<BoolLiteral>(fContext, /*offset=*/-1,
1869 !left.compareConstant(fContext, right));
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001870 default:
1871 return nullptr;
1872 }
1873 }
ethannicholas08a92112016-11-09 13:26:45 -08001874 #undef RESULT
1875 return nullptr;
1876}
1877
Ethan Nicholasfc994162019-06-06 10:04:27 -04001878std::unique_ptr<Expression> IRGenerator::convertBinaryExpression(const ASTNode& expression) {
1879 SkASSERT(expression.fKind == ASTNode::Kind::kBinary);
1880 auto iter = expression.begin();
1881 std::unique_ptr<Expression> left = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07001882 if (!left) {
1883 return nullptr;
1884 }
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001885 Token::Kind op = expression.getToken().fKind;
John Stiles4c412bc2020-10-13 11:19:41 -04001886 std::unique_ptr<Expression> right;
1887 {
1888 // Can't inline the right side of a short-circuiting boolean, because our inlining
1889 // approach runs things out of order.
1890 AutoDisableInline disableInline(this, /*canInline=*/(op != Token::Kind::TK_LOGICALAND &&
1891 op != Token::Kind::TK_LOGICALOR));
1892 right = this->convertExpression(*(iter++));
1893 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001894 if (!right) {
1895 return nullptr;
1896 }
ethannicholasd598f792016-07-25 10:08:54 -07001897 const Type* leftType;
1898 const Type* rightType;
1899 const Type* resultType;
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001900 const Type* rawLeftType;
John Stilesd0e48402020-09-22 14:00:40 -04001901 if (left->is<IntLiteral>() && right->type().isInteger()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001902 rawLeftType = &right->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001903 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001904 rawLeftType = &left->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001905 }
1906 const Type* rawRightType;
John Stilesd0e48402020-09-22 14:00:40 -04001907 if (right->is<IntLiteral>() && left->type().isInteger()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001908 rawRightType = &left->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001909 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001910 rawRightType = &right->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001911 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001912 if (!determine_binary_type(fContext, fSettings->fAllowNarrowingConversions, op,
1913 *rawLeftType, *rawRightType, &leftType, &rightType, &resultType)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001914 fErrors.error(expression.fOffset, String("type mismatch: '") +
Ethan Nicholasfc994162019-06-06 10:04:27 -04001915 Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04001916 "' cannot operate on '" + left->type().displayName() +
1917 "', '" + right->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001918 return nullptr;
1919 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001920 if (Compiler::IsAssignment(op)) {
Ethan Nicholas4fadce42020-07-30 13:29:30 -04001921 if (!this->setRefKind(*left, op != Token::Kind::TK_EQ
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001922 ? VariableReference::RefKind::kReadWrite
1923 : VariableReference::RefKind::kWrite)) {
Ethan Nicholas4fadce42020-07-30 13:29:30 -04001924 return nullptr;
1925 }
ethannicholasea4567c2016-10-17 11:24:37 -07001926 }
1927 left = this->coerce(std::move(left), *leftType);
1928 right = this->coerce(std::move(right), *rightType);
1929 if (!left || !right) {
1930 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001931 }
John Stilesa008b0f2020-08-16 08:48:02 -04001932 std::unique_ptr<Expression> result = this->constantFold(*left, op, *right);
ethannicholas08a92112016-11-09 13:26:45 -08001933 if (!result) {
John Stilesd1c4dac2020-08-11 18:50:50 -04001934 result = std::make_unique<BinaryExpression>(expression.fOffset, std::move(left), op,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001935 std::move(right), resultType);
ethannicholas08a92112016-11-09 13:26:45 -08001936 }
1937 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07001938}
1939
Ethan Nicholasfc994162019-06-06 10:04:27 -04001940std::unique_ptr<Expression> IRGenerator::convertTernaryExpression(const ASTNode& node) {
1941 SkASSERT(node.fKind == ASTNode::Kind::kTernary);
1942 auto iter = node.begin();
1943 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
ethannicholasd598f792016-07-25 10:08:54 -07001944 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -07001945 if (!test) {
1946 return nullptr;
1947 }
John Stiles4c412bc2020-10-13 11:19:41 -04001948 std::unique_ptr<Expression> ifTrue;
1949 std::unique_ptr<Expression> ifFalse;
1950 {
1951 AutoDisableInline disableInline(this);
1952 ifTrue = this->convertExpression(*(iter++));
1953 if (!ifTrue) {
1954 return nullptr;
1955 }
1956 ifFalse = this->convertExpression(*(iter++));
1957 if (!ifFalse) {
1958 return nullptr;
1959 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001960 }
ethannicholasd598f792016-07-25 10:08:54 -07001961 const Type* trueType;
1962 const Type* falseType;
1963 const Type* resultType;
Brian Osman0acb5b52020-09-02 13:45:47 -04001964 if (!determine_binary_type(fContext, fSettings->fAllowNarrowingConversions,
1965 Token::Kind::TK_EQEQ, ifTrue->type(), ifFalse->type(),
1966 &trueType, &falseType, &resultType) ||
1967 trueType != falseType) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001968 fErrors.error(node.fOffset, "ternary operator result mismatch: '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04001969 ifTrue->type().displayName() + "', '" +
1970 ifFalse->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001971 return nullptr;
1972 }
Brian Osman82329002020-07-21 09:39:27 -04001973 if (trueType->nonnullable() == *fContext.fFragmentProcessor_Type) {
1974 fErrors.error(node.fOffset,
1975 "ternary expression of type '" + trueType->displayName() + "' not allowed");
1976 return nullptr;
1977 }
ethannicholasd598f792016-07-25 10:08:54 -07001978 ifTrue = this->coerce(std::move(ifTrue), *trueType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05001979 if (!ifTrue) {
1980 return nullptr;
1981 }
ethannicholasd598f792016-07-25 10:08:54 -07001982 ifFalse = this->coerce(std::move(ifFalse), *falseType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05001983 if (!ifFalse) {
1984 return nullptr;
1985 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001986 if (test->kind() == Expression::Kind::kBoolLiteral) {
ethannicholas08a92112016-11-09 13:26:45 -08001987 // static boolean test, just return one of the branches
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001988 if (test->as<BoolLiteral>().value()) {
ethannicholas08a92112016-11-09 13:26:45 -08001989 return ifTrue;
1990 } else {
1991 return ifFalse;
1992 }
1993 }
John Stiles8fa3b4e2020-09-02 11:27:23 -04001994 return std::make_unique<TernaryExpression>(node.fOffset,
1995 std::move(test),
1996 std::move(ifTrue),
1997 std::move(ifFalse));
ethannicholasb3058bd2016-07-01 08:22:01 -07001998}
1999
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002000void IRGenerator::copyIntrinsicIfNeeded(const FunctionDeclaration& function) {
Brian Osman00a8b5b2020-10-02 09:06:04 -04002001 if (const ProgramElement* found = fIntrinsics->findAndInclude(function.description())) {
Brian Osman2b469eb2020-09-21 11:32:10 -04002002 const FunctionDefinition& original = found->as<FunctionDefinition>();
John Stiles9878d9e2020-09-22 15:40:16 -04002003
2004 // Sort the referenced intrinsics into a consistent order; otherwise our output will become
2005 // non-deterministic.
2006 std::vector<const FunctionDeclaration*> intrinsics(original.fReferencedIntrinsics.begin(),
2007 original.fReferencedIntrinsics.end());
2008 std::sort(intrinsics.begin(), intrinsics.end(),
2009 [](const FunctionDeclaration* a, const FunctionDeclaration* b) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002010 if (a->isBuiltin() != b->isBuiltin()) {
2011 return a->isBuiltin() < b->isBuiltin();
John Stiles9878d9e2020-09-22 15:40:16 -04002012 }
2013 if (a->fOffset != b->fOffset) {
2014 return a->fOffset < b->fOffset;
2015 }
Ethan Nicholase2c49992020-10-05 11:49:11 -04002016 if (a->name() != b->name()) {
2017 return a->name() < b->name();
John Stiles9878d9e2020-09-22 15:40:16 -04002018 }
2019 return a->description() < b->description();
2020 });
2021 for (const FunctionDeclaration* f : intrinsics) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002022 this->copyIntrinsicIfNeeded(*f);
2023 }
2024 fProgramElements->push_back(original.clone());
2025 }
2026}
2027
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002028std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05002029 const FunctionDeclaration& function,
John Stiles8e3b6be2020-10-13 11:14:08 -04002030 ExpressionArray arguments) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002031 if (function.isBuiltin()) {
2032 if (function.definition()) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002033 fReferencedIntrinsics.insert(&function);
2034 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002035 if (!fIsBuiltinCode && fIntrinsics) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002036 this->copyIntrinsicIfNeeded(function);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05002037 }
2038 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002039 if (function.parameters().size() != arguments.size()) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002040 String msg = "call to '" + function.name() + "' expected " +
Ethan Nicholased84b732020-10-08 11:45:44 -04002041 to_string((uint64_t) function.parameters().size()) +
ethannicholasb3058bd2016-07-01 08:22:01 -07002042 " argument";
Ethan Nicholased84b732020-10-08 11:45:44 -04002043 if (function.parameters().size() != 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002044 msg += "s";
2045 }
ethannicholas5961bc92016-10-12 06:39:56 -07002046 msg += ", but found " + to_string((uint64_t) arguments.size());
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002047 fErrors.error(offset, msg);
ethannicholasb3058bd2016-07-01 08:22:01 -07002048 return nullptr;
2049 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002050 if (fKind == Program::kPipelineStage_Kind && !function.definition() && !function.isBuiltin()) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002051 String msg = "call to undefined function '" + function.name() + "'";
Brian Osman5f6b41e2020-03-09 11:53:24 -04002052 fErrors.error(offset, msg);
2053 return nullptr;
2054 }
John Stilesfa889112020-10-12 19:03:43 -04002055 FunctionDeclaration::ParamTypes types;
ethannicholas471e8942016-10-28 09:02:46 -07002056 const Type* returnType;
2057 if (!function.determineFinalTypes(arguments, &types, &returnType)) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002058 String msg = "no match for " + function.name() + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002059 String separator;
ethannicholas471e8942016-10-28 09:02:46 -07002060 for (size_t i = 0; i < arguments.size(); i++) {
2061 msg += separator;
2062 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -04002063 msg += arguments[i]->type().displayName();
ethannicholas471e8942016-10-28 09:02:46 -07002064 }
2065 msg += ")";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002066 fErrors.error(offset, msg);
ethannicholas471e8942016-10-28 09:02:46 -07002067 return nullptr;
2068 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002069 for (size_t i = 0; i < arguments.size(); i++) {
ethannicholas471e8942016-10-28 09:02:46 -07002070 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
ethannicholasea4567c2016-10-17 11:24:37 -07002071 if (!arguments[i]) {
2072 return nullptr;
2073 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002074 const Modifiers& paramModifiers = function.parameters()[i]->modifiers();
John Stiles978674a2020-09-23 15:24:51 -04002075 if (paramModifiers.fFlags & Modifiers::kOut_Flag) {
2076 if (!this->setRefKind(*arguments[i], paramModifiers.fFlags & Modifiers::kIn_Flag
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002077 ? VariableReference::RefKind::kReadWrite
2078 : VariableReference::RefKind::kPointer)) {
John Stiles978674a2020-09-23 15:24:51 -04002079 return nullptr;
2080 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002081 }
2082 }
John Stilesea9ab822020-08-31 09:55:04 -04002083
John Stiles4c412bc2020-10-13 11:19:41 -04002084 auto funcCall = std::make_unique<FunctionCall>(offset, returnType, &function,
2085 std::move(arguments));
2086 if (fCanInline &&
2087 fInliner->isSafeToInline(funcCall->function().definition()) &&
2088 !fInliner->isLargeFunction(funcCall->function().definition())) {
2089 Inliner::InlinedCall inlinedCall = fInliner->inlineCall(funcCall.get(), fSymbolTable.get(),
2090 fCurrentFunction);
2091 if (inlinedCall.fInlinedBody) {
2092 fExtraStatements.push_back(std::move(inlinedCall.fInlinedBody));
2093 }
2094 return std::move(inlinedCall.fReplacementExpr);
2095 }
2096
2097 return std::move(funcCall);
ethannicholasb3058bd2016-07-01 08:22:01 -07002098}
2099
2100/**
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002101 * Determines the cost of coercing the arguments of a function to the required types. Cost has no
Brian Osman0acb5b52020-09-02 13:45:47 -04002102 * particular meaning other than "lower costs are preferred". Returns CoercionCost::Impossible() if
2103 * the call is not valid.
ethannicholasb3058bd2016-07-01 08:22:01 -07002104 */
Brian Osman0acb5b52020-09-02 13:45:47 -04002105CoercionCost IRGenerator::callCost(const FunctionDeclaration& function,
John Stiles8e3b6be2020-10-13 11:14:08 -04002106 const ExpressionArray& arguments) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002107 if (function.parameters().size() != arguments.size()) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002108 return CoercionCost::Impossible();
ethannicholasb3058bd2016-07-01 08:22:01 -07002109 }
John Stilesfa889112020-10-12 19:03:43 -04002110 FunctionDeclaration::ParamTypes types;
ethannicholas471e8942016-10-28 09:02:46 -07002111 const Type* ignored;
2112 if (!function.determineFinalTypes(arguments, &types, &ignored)) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002113 return CoercionCost::Impossible();
ethannicholas471e8942016-10-28 09:02:46 -07002114 }
Brian Osman0acb5b52020-09-02 13:45:47 -04002115 CoercionCost total = CoercionCost::Free();
ethannicholasb3058bd2016-07-01 08:22:01 -07002116 for (size_t i = 0; i < arguments.size(); i++) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002117 total = total + arguments[i]->coercionCost(*types[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -07002118 }
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002119 return total;
ethannicholasb3058bd2016-07-01 08:22:01 -07002120}
2121
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002122std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05002123 std::unique_ptr<Expression> functionValue,
John Stiles8e3b6be2020-10-13 11:14:08 -04002124 ExpressionArray arguments) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002125 switch (functionValue->kind()) {
2126 case Expression::Kind::kTypeReference:
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002127 return this->convertConstructor(offset,
Ethan Nicholas5194a702020-10-12 11:12:12 -04002128 functionValue->as<TypeReference>().value(),
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002129 std::move(arguments));
Ethan Nicholase6592142020-09-08 10:22:09 -04002130 case Expression::Kind::kExternalValue: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002131 const ExternalValue& v = functionValue->as<ExternalValueReference>().value();
2132 if (!v.canCall()) {
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002133 fErrors.error(offset, "this external value is not a function");
2134 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002135 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002136 int count = v.callParameterCount();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002137 if (count != (int) arguments.size()) {
2138 fErrors.error(offset, "external function expected " + to_string(count) +
2139 " arguments, but found " + to_string((int) arguments.size()));
2140 return nullptr;
2141 }
2142 static constexpr int PARAMETER_MAX = 16;
2143 SkASSERT(count < PARAMETER_MAX);
2144 const Type* types[PARAMETER_MAX];
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002145 v.getCallParameterTypes(types);
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002146 for (int i = 0; i < count; ++i) {
2147 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
2148 if (!arguments[i]) {
2149 return nullptr;
2150 }
2151 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002152 return std::make_unique<ExternalFunctionCall>(offset, &v, std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07002153 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002154 case Expression::Kind::kFunctionReference: {
John Stilesce591b72020-08-27 11:47:30 -04002155 const FunctionReference& ref = functionValue->as<FunctionReference>();
Ethan Nicholas5194a702020-10-12 11:12:12 -04002156 const std::vector<const FunctionDeclaration*>& functions = ref.functions();
Brian Osman0acb5b52020-09-02 13:45:47 -04002157 CoercionCost bestCost = CoercionCost::Impossible();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002158 const FunctionDeclaration* best = nullptr;
Ethan Nicholas5194a702020-10-12 11:12:12 -04002159 if (functions.size() > 1) {
2160 for (const auto& f : functions) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002161 CoercionCost cost = this->callCost(*f, arguments);
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002162 if (cost < bestCost) {
2163 bestCost = cost;
2164 best = f;
2165 }
2166 }
2167 if (best) {
2168 return this->call(offset, *best, std::move(arguments));
2169 }
Ethan Nicholas5194a702020-10-12 11:12:12 -04002170 String msg = "no match for " + functions[0]->name() + "(";
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002171 String separator;
2172 for (size_t i = 0; i < arguments.size(); i++) {
2173 msg += separator;
2174 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -04002175 msg += arguments[i]->type().displayName();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002176 }
2177 msg += ")";
2178 fErrors.error(offset, msg);
2179 return nullptr;
2180 }
Ethan Nicholas5194a702020-10-12 11:12:12 -04002181 return this->call(offset, *functions[0], std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07002182 }
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002183 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002184 fErrors.error(offset, "not a function");
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002185 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002186 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002187}
2188
John Stiles8e3b6be2020-10-13 11:14:08 -04002189std::unique_ptr<Expression> IRGenerator::convertNumberConstructor(int offset,
2190 const Type& type,
2191 ExpressionArray args) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04002192 SkASSERT(type.isNumber());
Ethan Nicholas84645e32017-02-09 13:57:14 -05002193 if (args.size() != 1) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002194 fErrors.error(offset, "invalid arguments to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002195 "' constructor, (expected exactly 1 argument, but found " +
2196 to_string((uint64_t) args.size()) + ")");
ethannicholasb3058bd2016-07-01 08:22:01 -07002197 return nullptr;
2198 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002199 const Type& argType = args[0]->type();
2200 if (type == argType) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002201 return std::move(args[0]);
2202 }
John Stilesd0e48402020-09-22 14:00:40 -04002203 if (type.isFloat() && args.size() == 1 && args[0]->is<FloatLiteral>()) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002204 SKSL_FLOAT value = args[0]->as<FloatLiteral>().value();
John Stilesd0e48402020-09-22 14:00:40 -04002205 return std::make_unique<FloatLiteral>(offset, value, &type);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002206 }
John Stilesd0e48402020-09-22 14:00:40 -04002207 if (type.isFloat() && args.size() == 1 && args[0]->is<IntLiteral>()) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002208 int64_t value = args[0]->as<IntLiteral>().value();
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002209 return std::make_unique<FloatLiteral>(offset, (float)value, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002210 }
John Stilesd0e48402020-09-22 14:00:40 -04002211 if (args[0]->is<IntLiteral>() && (type == *fContext.fInt_Type ||
2212 type == *fContext.fUInt_Type)) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002213 return std::make_unique<IntLiteral>(offset, args[0]->as<IntLiteral>().value(), &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002214 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002215 if (argType == *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002216 std::unique_ptr<IntLiteral> zero(new IntLiteral(fContext, offset, 0));
2217 std::unique_ptr<IntLiteral> one(new IntLiteral(fContext, offset, 1));
John Stilesd0e48402020-09-22 14:00:40 -04002218 return std::make_unique<TernaryExpression>(offset, std::move(args[0]),
2219 this->coerce(std::move(one), type),
2220 this->coerce(std::move(zero), type));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002221 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002222 if (!argType.isNumber()) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002223 fErrors.error(offset, "invalid argument to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002224 "' constructor (expected a number or bool, but found '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002225 argType.displayName() + "')");
Ethan Nicholas84645e32017-02-09 13:57:14 -05002226 return nullptr;
2227 }
John Stilesd0e48402020-09-22 14:00:40 -04002228 return std::make_unique<Constructor>(offset, &type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002229}
2230
John Stiles36374402020-08-13 12:16:44 -04002231static int component_count(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002232 switch (type.typeKind()) {
2233 case Type::TypeKind::kVector:
Ethan Nicholas84645e32017-02-09 13:57:14 -05002234 return type.columns();
Ethan Nicholase6592142020-09-08 10:22:09 -04002235 case Type::TypeKind::kMatrix:
Ethan Nicholas84645e32017-02-09 13:57:14 -05002236 return type.columns() * type.rows();
2237 default:
2238 return 1;
2239 }
2240}
2241
John Stiles8e3b6be2020-10-13 11:14:08 -04002242std::unique_ptr<Expression> IRGenerator::convertCompoundConstructor(int offset,
2243 const Type& type,
2244 ExpressionArray args) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002245 SkASSERT(type.typeKind() == Type::TypeKind::kVector ||
2246 type.typeKind() == Type::TypeKind::kMatrix);
2247 if (type.typeKind() == Type::TypeKind::kMatrix && args.size() == 1 &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04002248 args[0]->type().typeKind() == Type::TypeKind::kMatrix) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002249 // matrix from matrix is always legal
Ethan Nicholas30d30222020-09-11 12:27:26 -04002250 return std::unique_ptr<Expression>(new Constructor(offset, &type, std::move(args)));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002251 }
2252 int actual = 0;
2253 int expected = type.rows() * type.columns();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002254 if (args.size() != 1 || expected != component_count(args[0]->type()) ||
2255 type.componentType().isNumber() != args[0]->type().componentType().isNumber()) {
ethannicholas5961bc92016-10-12 06:39:56 -07002256 for (size_t i = 0; i < args.size(); i++) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002257 const Type& argType = args[i]->type();
2258 if (argType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002259 if (type.componentType().isNumber() !=
Ethan Nicholas30d30222020-09-11 12:27:26 -04002260 argType.componentType().isNumber()) {
2261 fErrors.error(offset, "'" + argType.displayName() + "' is not a valid "
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002262 "parameter to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002263 "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002264 return nullptr;
2265 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002266 actual += argType.columns();
2267 } else if (argType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002268 actual += 1;
Ethan Nicholase6592142020-09-08 10:22:09 -04002269 if (type.typeKind() != Type::TypeKind::kScalar) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002270 args[i] = this->coerce(std::move(args[i]), type.componentType());
2271 if (!args[i]) {
2272 return nullptr;
2273 }
2274 }
2275 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002276 fErrors.error(offset, "'" + argType.displayName() + "' is not a valid "
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002277 "parameter to '" + type.displayName() + "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002278 return nullptr;
2279 }
2280 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05002281 if (actual != 1 && actual != expected) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002282 fErrors.error(offset, "invalid arguments to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002283 "' constructor (expected " + to_string(expected) +
2284 " scalars, but found " + to_string(actual) + ")");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002285 return nullptr;
2286 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002287 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002288 return std::unique_ptr<Expression>(new Constructor(offset, &type, std::move(args)));
ethannicholasb3058bd2016-07-01 08:22:01 -07002289}
2290
John Stiles8e3b6be2020-10-13 11:14:08 -04002291std::unique_ptr<Expression> IRGenerator::convertConstructor(int offset,
2292 const Type& type,
2293 ExpressionArray args) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002294 // FIXME: add support for structs
Ethan Nicholas30d30222020-09-11 12:27:26 -04002295 if (args.size() == 1 && args[0]->type() == type &&
Brian Osman82329002020-07-21 09:39:27 -04002296 type.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002297 // argument is already the right type, just return it
2298 return std::move(args[0]);
2299 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002300 Type::TypeKind kind = type.typeKind();
Ethan Nicholas84645e32017-02-09 13:57:14 -05002301 if (type.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002302 return this->convertNumberConstructor(offset, type, std::move(args));
Ethan Nicholase6592142020-09-08 10:22:09 -04002303 } else if (kind == Type::TypeKind::kArray) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002304 const Type& base = type.componentType();
2305 for (size_t i = 0; i < args.size(); i++) {
2306 args[i] = this->coerce(std::move(args[i]), base);
2307 if (!args[i]) {
2308 return nullptr;
2309 }
2310 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002311 return std::make_unique<Constructor>(offset, &type, std::move(args));
Ethan Nicholase6592142020-09-08 10:22:09 -04002312 } else if (kind == Type::TypeKind::kVector || kind == Type::TypeKind::kMatrix) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002313 return this->convertCompoundConstructor(offset, type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002314 } else {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002315 fErrors.error(offset, "cannot construct '" + type.displayName() + "'");
Ethan Nicholas84645e32017-02-09 13:57:14 -05002316 return nullptr;
2317 }
2318}
2319
Ethan Nicholasfc994162019-06-06 10:04:27 -04002320std::unique_ptr<Expression> IRGenerator::convertPrefixExpression(const ASTNode& expression) {
2321 SkASSERT(expression.fKind == ASTNode::Kind::kPrefix);
2322 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
ethannicholasb3058bd2016-07-01 08:22:01 -07002323 if (!base) {
2324 return nullptr;
2325 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002326 const Type& baseType = base->type();
Ethan Nicholasfc994162019-06-06 10:04:27 -04002327 switch (expression.getToken().fKind) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002328 case Token::Kind::TK_PLUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002329 if (!baseType.isNumber() && baseType.typeKind() != Type::TypeKind::kVector &&
2330 baseType != *fContext.fFloatLiteral_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002331 fErrors.error(expression.fOffset,
Ethan Nicholas30d30222020-09-11 12:27:26 -04002332 "'+' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002333 return nullptr;
2334 }
2335 return base;
John Stiles978674a2020-09-23 15:24:51 -04002336
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002337 case Token::Kind::TK_MINUS:
John Stiles978674a2020-09-23 15:24:51 -04002338 if (base->is<IntLiteral>()) {
2339 return std::make_unique<IntLiteral>(fContext, base->fOffset,
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002340 -base->as<IntLiteral>().value());
ethannicholasb3058bd2016-07-01 08:22:01 -07002341 }
John Stiles978674a2020-09-23 15:24:51 -04002342 if (base->is<FloatLiteral>()) {
2343 return std::make_unique<FloatLiteral>(fContext, base->fOffset,
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002344 -base->as<FloatLiteral>().value());
ethannicholasb3058bd2016-07-01 08:22:01 -07002345 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002346 if (!baseType.isNumber() && baseType.typeKind() != Type::TypeKind::kVector) {
Ethan Nicholase1f55022019-02-05 17:17:40 -05002347 fErrors.error(expression.fOffset,
Ethan Nicholas30d30222020-09-11 12:27:26 -04002348 "'-' cannot operate on '" + baseType.displayName() + "'");
Ethan Nicholase1f55022019-02-05 17:17:40 -05002349 return nullptr;
2350 }
John Stiles978674a2020-09-23 15:24:51 -04002351 return std::make_unique<PrefixExpression>(Token::Kind::TK_MINUS, std::move(base));
2352
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002353 case Token::Kind::TK_PLUSPLUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002354 if (!baseType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002355 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002356 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002357 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002358 return nullptr;
2359 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002360 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002361 return nullptr;
2362 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002363 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002364 case Token::Kind::TK_MINUSMINUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002365 if (!baseType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002366 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002367 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002368 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002369 return nullptr;
2370 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002371 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002372 return nullptr;
2373 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002374 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002375 case Token::Kind::TK_LOGICALNOT:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002376 if (baseType != *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002377 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002378 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002379 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002380 return nullptr;
2381 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002382 if (base->kind() == Expression::Kind::kBoolLiteral) {
John Stiles978674a2020-09-23 15:24:51 -04002383 return std::make_unique<BoolLiteral>(fContext, base->fOffset,
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002384 !base->as<BoolLiteral>().value());
ethannicholas08a92112016-11-09 13:26:45 -08002385 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002386 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002387 case Token::Kind::TK_BITWISENOT:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002388 if (baseType != *fContext.fInt_Type && baseType != *fContext.fUInt_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002389 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002390 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002391 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholas5961bc92016-10-12 06:39:56 -07002392 return nullptr;
2393 }
2394 break;
Ethan Nicholas11d53972016-11-28 11:23:23 -05002395 default:
ethannicholasb3058bd2016-07-01 08:22:01 -07002396 ABORT("unsupported prefix operator\n");
2397 }
John Stiles978674a2020-09-23 15:24:51 -04002398 return std::make_unique<PrefixExpression>(expression.getToken().fKind, std::move(base));
ethannicholasb3058bd2016-07-01 08:22:01 -07002399}
2400
2401std::unique_ptr<Expression> IRGenerator::convertIndex(std::unique_ptr<Expression> base,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002402 const ASTNode& index) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002403 if (base->kind() == Expression::Kind::kTypeReference) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002404 if (index.fKind == ASTNode::Kind::kInt) {
Ethan Nicholas5194a702020-10-12 11:12:12 -04002405 const Type& oldType = base->as<TypeReference>().value();
Ethan Nicholasfc994162019-06-06 10:04:27 -04002406 SKSL_INT size = index.getInt();
John Stiles3ae071e2020-08-05 15:29:29 -04002407 const Type* newType = fSymbolTable->takeOwnershipOfSymbol(
2408 std::make_unique<Type>(oldType.name() + "[" + to_string(size) + "]",
Ethan Nicholase6592142020-09-08 10:22:09 -04002409 Type::TypeKind::kArray, oldType, size));
2410 return std::make_unique<TypeReference>(fContext, base->fOffset, newType);
Ethan Nicholas50afc172017-02-16 14:49:57 -05002411
2412 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002413 fErrors.error(base->fOffset, "array size must be a constant");
Ethan Nicholas50afc172017-02-16 14:49:57 -05002414 return nullptr;
2415 }
2416 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002417 const Type& baseType = base->type();
2418 if (baseType.typeKind() != Type::TypeKind::kArray &&
2419 baseType.typeKind() != Type::TypeKind::kMatrix &&
2420 baseType.typeKind() != Type::TypeKind::kVector) {
2421 fErrors.error(base->fOffset, "expected array, but found '" + baseType.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002422 "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002423 return nullptr;
2424 }
2425 std::unique_ptr<Expression> converted = this->convertExpression(index);
2426 if (!converted) {
2427 return nullptr;
2428 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002429 if (converted->type() != *fContext.fUInt_Type) {
ethannicholas5961bc92016-10-12 06:39:56 -07002430 converted = this->coerce(std::move(converted), *fContext.fInt_Type);
2431 if (!converted) {
2432 return nullptr;
2433 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002434 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002435 return std::make_unique<IndexExpression>(fContext, std::move(base), std::move(converted));
ethannicholasb3058bd2016-07-01 08:22:01 -07002436}
2437
2438std::unique_ptr<Expression> IRGenerator::convertField(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002439 StringFragment field) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002440 if (base->kind() == Expression::Kind::kExternalValue) {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002441 const ExternalValue& ev = base->as<ExternalValueReference>().value();
Ethan Nicholas91164d12019-05-15 15:29:54 -04002442 ExternalValue* result = ev.getChild(String(field).c_str());
2443 if (!result) {
2444 fErrors.error(base->fOffset, "external value does not have a child named '" + field +
2445 "'");
2446 return nullptr;
2447 }
2448 return std::unique_ptr<Expression>(new ExternalValueReference(base->fOffset, result));
2449 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002450 const Type& baseType = base->type();
2451 auto fields = baseType.fields();
ethannicholasb3058bd2016-07-01 08:22:01 -07002452 for (size_t i = 0; i < fields.size(); i++) {
2453 if (fields[i].fName == field) {
2454 return std::unique_ptr<Expression>(new FieldAccess(std::move(base), (int) i));
2455 }
2456 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002457 fErrors.error(base->fOffset, "type '" + baseType.displayName() + "' does not have a field "
John Stiles68861e32020-09-25 16:02:07 -04002458 "named '" + field + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002459 return nullptr;
2460}
2461
Brian Osman25647672020-09-15 15:16:56 -04002462// Swizzles are complicated due to constant components. The most difficult case is a mask like
John Stiles6e49a372020-09-16 13:40:54 -04002463// '.x1w0'. A naive approach might turn that into 'float4(base.x, 1, base.w, 0)', but that evaluates
2464// 'base' twice. We instead group the swizzle mask ('xw') and constants ('1, 0') together and use a
Brian Osman25647672020-09-15 15:16:56 -04002465// secondary swizzle to put them back into the right order, so in this case we end up with
John Stiles6e49a372020-09-16 13:40:54 -04002466// 'float4(base.xw, 1, 0).xzyw'.
ethannicholasb3058bd2016-07-01 08:22:01 -07002467std::unique_ptr<Expression> IRGenerator::convertSwizzle(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002468 StringFragment fields) {
Brian Osman25647672020-09-15 15:16:56 -04002469 const int offset = base->fOffset;
Ethan Nicholas30d30222020-09-11 12:27:26 -04002470 const Type& baseType = base->type();
2471 if (baseType.typeKind() != Type::TypeKind::kVector && !baseType.isNumber()) {
Brian Osman25647672020-09-15 15:16:56 -04002472 fErrors.error(offset, "cannot swizzle value of type '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002473 return nullptr;
2474 }
Brian Osman25647672020-09-15 15:16:56 -04002475
2476 if (fields.fLength > 4) {
2477 fErrors.error(offset, "too many components in swizzle mask '" + fields + "'");
2478 return nullptr;
2479 }
2480
2481 std::vector<int> maskComponents;
John Stiles6e49a372020-09-16 13:40:54 -04002482 maskComponents.reserve(fields.fLength);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002483 for (size_t i = 0; i < fields.fLength; i++) {
Ethan Nicholas9e1138d2016-11-21 10:39:35 -05002484 switch (fields[i]) {
Ethan Nicholasac285b12019-02-12 16:05:18 -05002485 case '0':
Ethan Nicholasac285b12019-02-12 16:05:18 -05002486 case '1':
John Stiles6e49a372020-09-16 13:40:54 -04002487 // Skip over constant fields for now.
Ethan Nicholasac285b12019-02-12 16:05:18 -05002488 break;
Ethan Nicholase455f652019-09-13 12:52:55 -04002489 case 'x':
2490 case 'r':
Ethan Nicholas11d53972016-11-28 11:23:23 -05002491 case 's':
Ethan Nicholase455f652019-09-13 12:52:55 -04002492 case 'L':
Brian Osman25647672020-09-15 15:16:56 -04002493 maskComponents.push_back(0);
ethannicholasb3058bd2016-07-01 08:22:01 -07002494 break;
Ethan Nicholase455f652019-09-13 12:52:55 -04002495 case 'y':
2496 case 'g':
ethannicholasb3058bd2016-07-01 08:22:01 -07002497 case 't':
Ethan Nicholase455f652019-09-13 12:52:55 -04002498 case 'T':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002499 if (baseType.columns() >= 2) {
Brian Osman25647672020-09-15 15:16:56 -04002500 maskComponents.push_back(1);
ethannicholasb3058bd2016-07-01 08:22:01 -07002501 break;
2502 }
John Stiles30212b72020-06-11 17:55:07 -04002503 [[fallthrough]];
Ethan Nicholase455f652019-09-13 12:52:55 -04002504 case 'z':
2505 case 'b':
Ethan Nicholas11d53972016-11-28 11:23:23 -05002506 case 'p':
Ethan Nicholase455f652019-09-13 12:52:55 -04002507 case 'R':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002508 if (baseType.columns() >= 3) {
Brian Osman25647672020-09-15 15:16:56 -04002509 maskComponents.push_back(2);
ethannicholasb3058bd2016-07-01 08:22:01 -07002510 break;
2511 }
John Stiles30212b72020-06-11 17:55:07 -04002512 [[fallthrough]];
Ethan Nicholase455f652019-09-13 12:52:55 -04002513 case 'w':
2514 case 'a':
ethannicholasb3058bd2016-07-01 08:22:01 -07002515 case 'q':
Ethan Nicholase455f652019-09-13 12:52:55 -04002516 case 'B':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002517 if (baseType.columns() >= 4) {
Brian Osman25647672020-09-15 15:16:56 -04002518 maskComponents.push_back(3);
ethannicholasb3058bd2016-07-01 08:22:01 -07002519 break;
2520 }
John Stiles30212b72020-06-11 17:55:07 -04002521 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -07002522 default:
Brian Osman25647672020-09-15 15:16:56 -04002523 fErrors.error(offset, String::printf("invalid swizzle component '%c'", fields[i]));
ethannicholasb3058bd2016-07-01 08:22:01 -07002524 return nullptr;
2525 }
2526 }
Brian Osman25647672020-09-15 15:16:56 -04002527 if (maskComponents.empty()) {
2528 fErrors.error(offset, "swizzle must refer to base expression");
ethannicholasb3058bd2016-07-01 08:22:01 -07002529 return nullptr;
2530 }
Brian Osman25647672020-09-15 15:16:56 -04002531
2532 // First, we need a vector expression that is the non-constant portion of the swizzle, packed:
2533 // scalar.xxx -> type3(scalar)
2534 // scalar.x0x0 -> type2(scalar)
2535 // vector.zyx -> vector.zyx
2536 // vector.x0y0 -> vector.xy
2537 std::unique_ptr<Expression> expr;
Ethan Nicholas30d30222020-09-11 12:27:26 -04002538 if (baseType.isNumber()) {
John Stiles8e3b6be2020-10-13 11:14:08 -04002539 ExpressionArray scalarConstructorArgs;
Brian Osman25647672020-09-15 15:16:56 -04002540 scalarConstructorArgs.push_back(std::move(base));
2541 expr = std::make_unique<Constructor>(
2542 offset, &baseType.toCompound(fContext, maskComponents.size(), 1),
2543 std::move(scalarConstructorArgs));
2544 } else {
2545 expr = std::make_unique<Swizzle>(fContext, std::move(base), maskComponents);
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002546 }
Brian Osman25647672020-09-15 15:16:56 -04002547
John Stiles6e49a372020-09-16 13:40:54 -04002548 // If we have processed the entire swizzle, we're done.
2549 if (maskComponents.size() == fields.fLength) {
Brian Osman25647672020-09-15 15:16:56 -04002550 return expr;
2551 }
2552
2553 // Now we create a constructor that has the correct number of elements for the final swizzle,
John Stiles6e49a372020-09-16 13:40:54 -04002554 // with all fields at the start. It's not finished yet; constants we need will be added below.
2555 // scalar.x0x0 -> type4(type2(x), ...)
2556 // vector.y111 -> type4(vector.y, ...)
2557 // vector.z10x -> type4(vector.zx, ...)
Brian Osman25647672020-09-15 15:16:56 -04002558 //
John Stiles6e49a372020-09-16 13:40:54 -04002559 // We could create simpler IR in some cases by reordering here, if all fields are packed
Brian Osman25647672020-09-15 15:16:56 -04002560 // contiguously. The benefits are minor, so skip the optimization to keep the algorithm simple.
John Stiles6e49a372020-09-16 13:40:54 -04002561 // The constructor will have at most three arguments: { base value, constant 0, constant 1 }
John Stiles8e3b6be2020-10-13 11:14:08 -04002562 ExpressionArray constructorArgs;
John Stiles6e49a372020-09-16 13:40:54 -04002563 constructorArgs.reserve(3);
Brian Osman25647672020-09-15 15:16:56 -04002564 constructorArgs.push_back(std::move(expr));
John Stiles6e49a372020-09-16 13:40:54 -04002565
2566 // Apply another swizzle to shuffle the constants into the correct place. Any constant values we
2567 // need are also tacked on to the end of the constructor.
2568 // scalar.x0x0 -> type4(type2(x), 0).xyxy
2569 // vector.y111 -> type4(vector.y, 1).xyyy
2570 // vector.z10x -> type4(vector.zx, 1, 0).xzwy
Brian Osman25647672020-09-15 15:16:56 -04002571 const Type* numberType = baseType.isNumber() ? &baseType : &baseType.componentType();
John Stiles6e49a372020-09-16 13:40:54 -04002572 std::vector<int> swizzleComponents;
2573 swizzleComponents.reserve(fields.fLength);
2574 int maskFieldIdx = 0;
2575 int constantFieldIdx = maskComponents.size();
2576 int constantZeroIdx = -1, constantOneIdx = -1;
Brian Osman25647672020-09-15 15:16:56 -04002577
Brian Osman25647672020-09-15 15:16:56 -04002578 for (size_t i = 0; i < fields.fLength; i++) {
John Stiles6e49a372020-09-16 13:40:54 -04002579 switch (fields[i]) {
2580 case '0':
2581 if (constantZeroIdx == -1) {
John Stilesd0e48402020-09-22 14:00:40 -04002582 // Synthesize a 'type(0)' argument at the end of the constructor.
John Stiles8e3b6be2020-10-13 11:14:08 -04002583 auto zero = std::make_unique<Constructor>(offset, numberType,
2584 ExpressionArray{});
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002585 zero->arguments().push_back(std::make_unique<IntLiteral>(fContext, offset,
2586 /*fValue=*/0));
John Stilesd0e48402020-09-22 14:00:40 -04002587 constructorArgs.push_back(std::move(zero));
John Stiles6e49a372020-09-16 13:40:54 -04002588 constantZeroIdx = constantFieldIdx++;
2589 }
2590 swizzleComponents.push_back(constantZeroIdx);
2591 break;
2592 case '1':
2593 if (constantOneIdx == -1) {
John Stilesd0e48402020-09-22 14:00:40 -04002594 // Synthesize a 'type(1)' argument at the end of the constructor.
John Stiles8e3b6be2020-10-13 11:14:08 -04002595 auto one = std::make_unique<Constructor>(offset, numberType, ExpressionArray{});
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002596 one->arguments().push_back(std::make_unique<IntLiteral>(fContext, offset,
2597 /*fValue=*/1));
John Stilesd0e48402020-09-22 14:00:40 -04002598 constructorArgs.push_back(std::move(one));
John Stiles6e49a372020-09-16 13:40:54 -04002599 constantOneIdx = constantFieldIdx++;
2600 }
2601 swizzleComponents.push_back(constantOneIdx);
2602 break;
2603 default:
2604 // The non-constant fields are already in the expected order.
2605 swizzleComponents.push_back(maskFieldIdx++);
2606 break;
Brian Osman25647672020-09-15 15:16:56 -04002607 }
2608 }
2609
John Stiles6e49a372020-09-16 13:40:54 -04002610 expr = std::make_unique<Constructor>(offset,
2611 &numberType->toCompound(fContext, constantFieldIdx, 1),
2612 std::move(constructorArgs));
2613
John Stilesb23ea382020-09-16 13:41:14 -04002614 // For some of our most common use cases ('.xyz0', '.xyz1'), we will now have an identity
2615 // swizzle; in those cases we can just return the constructor without the swizzle attached.
2616 for (size_t i = 0; i < swizzleComponents.size(); ++i) {
2617 if (swizzleComponents[i] != int(i)) {
2618 // The swizzle has an effect, so apply it.
2619 return std::make_unique<Swizzle>(fContext, std::move(expr),
2620 std::move(swizzleComponents));
2621 }
2622 }
2623
2624 // The swizzle was a no-op; return the constructor expression directly.
2625 return expr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002626}
2627
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002628const Type* IRGenerator::typeForSetting(int offset, String name) const {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002629 auto found = fCapsMap.find(name);
2630 if (found == fCapsMap.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002631 fErrors.error(offset, "unknown capability flag '" + name + "'");
Ethan Nicholas3605ace2016-11-21 15:59:48 -05002632 return nullptr;
2633 }
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002634 switch (found->second.fKind) {
2635 case Program::Settings::Value::kBool_Kind: return fContext.fBool_Type.get();
2636 case Program::Settings::Value::kFloat_Kind: return fContext.fFloat_Type.get();
2637 case Program::Settings::Value::kInt_Kind: return fContext.fInt_Type.get();
2638 }
2639 SkUNREACHABLE;
2640 return nullptr;
2641}
2642
2643std::unique_ptr<Expression> IRGenerator::valueForSetting(int offset, String name) const {
2644 auto found = fCapsMap.find(name);
2645 if (found == fCapsMap.end()) {
2646 fErrors.error(offset, "unknown capability flag '" + name + "'");
2647 return nullptr;
2648 }
2649 return found->second.literal(fContext, offset);
Ethan Nicholas762466e2017-06-29 10:03:38 -04002650}
2651
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002652std::unique_ptr<Expression> IRGenerator::convertTypeField(int offset, const Type& type,
2653 StringFragment field) {
Brian Osman1313d1a2020-09-08 10:34:30 -04002654 // Find the Enum element that this type refers to (if any)
Brian Osman2b469eb2020-09-21 11:32:10 -04002655 const ProgramElement* enumElement = nullptr;
2656 for (const auto& e : *fProgramElements) {
Ethan Nicholasd83ded82020-09-29 17:05:54 -04002657 if (e->is<Enum>() && type.name() == e->as<Enum>().typeName()) {
Brian Osman2b469eb2020-09-21 11:32:10 -04002658 enumElement = e.get();
2659 break;
Brian Osman1313d1a2020-09-08 10:34:30 -04002660 }
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002661 }
Brian Osman1313d1a2020-09-08 10:34:30 -04002662
2663 if (enumElement) {
2664 // We found the Enum element. Look for 'field' as a member.
2665 std::shared_ptr<SymbolTable> old = fSymbolTable;
Ethan Nicholasd83ded82020-09-29 17:05:54 -04002666 fSymbolTable = enumElement->as<Enum>().symbols();
Brian Osman1313d1a2020-09-08 10:34:30 -04002667 std::unique_ptr<Expression> result = convertIdentifier(
2668 ASTNode(&fFile->fNodes, offset, ASTNode::Kind::kIdentifier, field));
2669 if (result) {
Ethan Nicholas78686922020-10-08 06:46:27 -04002670 const Variable& v = *result->as<VariableReference>().variable();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002671 SkASSERT(v.initialValue());
Brian Osman1313d1a2020-09-08 10:34:30 -04002672 result = std::make_unique<IntLiteral>(
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002673 offset, v.initialValue()->as<IntLiteral>().value(), &type);
Brian Osman1313d1a2020-09-08 10:34:30 -04002674 } else {
2675 fErrors.error(offset,
Ethan Nicholase2c49992020-10-05 11:49:11 -04002676 "type '" + type.name() + "' does not have a member named '" + field +
2677 "'");
Brian Osman1313d1a2020-09-08 10:34:30 -04002678 }
2679 fSymbolTable = old;
2680 return result;
2681 } else {
2682 // No Enum element? Check the intrinsics, clone it into the program, try again.
Brian Osman00a8b5b2020-10-02 09:06:04 -04002683 if (!fIsBuiltinCode && fIntrinsics) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002684 if (const ProgramElement* found = fIntrinsics->findAndInclude(type.name())) {
Brian Osman00a8b5b2020-10-02 09:06:04 -04002685 fProgramElements->push_back(found->clone());
2686 return this->convertTypeField(offset, type, field);
2687 }
Ethan Nicholasdb80f692019-11-22 14:06:12 -05002688 }
Brian Osman1313d1a2020-09-08 10:34:30 -04002689 fErrors.error(offset,
Ethan Nicholase2c49992020-10-05 11:49:11 -04002690 "type '" + type.displayName() + "' does not have a member named '" + field +
2691 "'");
Brian Osman1313d1a2020-09-08 10:34:30 -04002692 return nullptr;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002693 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002694}
2695
Ethan Nicholasfc994162019-06-06 10:04:27 -04002696std::unique_ptr<Expression> IRGenerator::convertIndexExpression(const ASTNode& index) {
2697 SkASSERT(index.fKind == ASTNode::Kind::kIndex);
2698 auto iter = index.begin();
2699 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07002700 if (!base) {
2701 return nullptr;
2702 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002703 if (iter != index.end()) {
2704 return this->convertIndex(std::move(base), *(iter++));
Ethan Nicholase6592142020-09-08 10:22:09 -04002705 } else if (base->kind() == Expression::Kind::kTypeReference) {
Ethan Nicholas5194a702020-10-12 11:12:12 -04002706 const Type& oldType = base->as<TypeReference>().value();
John Stiles3ae071e2020-08-05 15:29:29 -04002707 const Type* newType = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
Brian Osmane8c26082020-10-01 17:22:45 -04002708 oldType.name() + "[]", Type::TypeKind::kArray, oldType, Type::kUnsizedArray));
Ethan Nicholase6592142020-09-08 10:22:09 -04002709 return std::make_unique<TypeReference>(fContext, base->fOffset, newType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002710 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002711 fErrors.error(index.fOffset, "'[]' must follow a type name");
2712 return nullptr;
2713}
2714
2715std::unique_ptr<Expression> IRGenerator::convertCallExpression(const ASTNode& callNode) {
2716 SkASSERT(callNode.fKind == ASTNode::Kind::kCall);
2717 auto iter = callNode.begin();
2718 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
2719 if (!base) {
2720 return nullptr;
2721 }
John Stiles8e3b6be2020-10-13 11:14:08 -04002722 ExpressionArray arguments;
Ethan Nicholasfc994162019-06-06 10:04:27 -04002723 for (; iter != callNode.end(); ++iter) {
2724 std::unique_ptr<Expression> converted = this->convertExpression(*iter);
2725 if (!converted) {
2726 return nullptr;
2727 }
2728 arguments.push_back(std::move(converted));
2729 }
2730 return this->call(callNode.fOffset, std::move(base), std::move(arguments));
2731}
2732
2733std::unique_ptr<Expression> IRGenerator::convertFieldExpression(const ASTNode& fieldNode) {
2734 std::unique_ptr<Expression> base = this->convertExpression(*fieldNode.begin());
2735 if (!base) {
2736 return nullptr;
2737 }
2738 StringFragment field = fieldNode.getString();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002739 const Type& baseType = base->type();
2740 if (baseType == *fContext.fSkCaps_Type) {
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002741 const Type* type = this->typeForSetting(fieldNode.fOffset, field);
2742 if (!type) {
2743 return nullptr;
2744 }
2745 return std::make_unique<Setting>(fieldNode.fOffset, field, type);
Ethan Nicholasfc994162019-06-06 10:04:27 -04002746 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002747 if (base->kind() == Expression::Kind::kExternalValue) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002748 return this->convertField(std::move(base), field);
2749 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002750 switch (baseType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002751 case Type::TypeKind::kOther:
2752 case Type::TypeKind::kStruct:
Ethan Nicholasfc994162019-06-06 10:04:27 -04002753 return this->convertField(std::move(base), field);
2754 default:
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002755 return this->convertSwizzle(std::move(base), field);
Ethan Nicholasfc994162019-06-06 10:04:27 -04002756 }
2757}
2758
Brian Osman6518d772020-09-10 16:50:06 -04002759std::unique_ptr<Expression> IRGenerator::convertScopeExpression(const ASTNode& scopeNode) {
2760 std::unique_ptr<Expression> base = this->convertExpression(*scopeNode.begin());
2761 if (!base) {
2762 return nullptr;
2763 }
2764 if (!base->is<TypeReference>()) {
2765 fErrors.error(scopeNode.fOffset, "'::' must follow a type name");
2766 return nullptr;
2767 }
2768 StringFragment member = scopeNode.getString();
Ethan Nicholas5194a702020-10-12 11:12:12 -04002769 return this->convertTypeField(base->fOffset, base->as<TypeReference>().value(), member);
Brian Osman6518d772020-09-10 16:50:06 -04002770}
2771
Ethan Nicholasfc994162019-06-06 10:04:27 -04002772std::unique_ptr<Expression> IRGenerator::convertPostfixExpression(const ASTNode& expression) {
2773 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
2774 if (!base) {
2775 return nullptr;
2776 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002777 const Type& baseType = base->type();
2778 if (!baseType.isNumber()) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002779 fErrors.error(expression.fOffset,
2780 "'" + String(Compiler::OperatorName(expression.getToken().fKind)) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002781 "' cannot operate on '" + baseType.displayName() + "'");
Ethan Nicholasfc994162019-06-06 10:04:27 -04002782 return nullptr;
2783 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002784 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002785 return nullptr;
2786 }
2787 return std::make_unique<PostfixExpression>(std::move(base), expression.getToken().fKind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002788}
2789
2790void IRGenerator::checkValid(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002791 switch (expr.kind()) {
2792 case Expression::Kind::kFunctionReference:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002793 fErrors.error(expr.fOffset, "expected '(' to begin function call");
ethannicholasb3058bd2016-07-01 08:22:01 -07002794 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002795 case Expression::Kind::kTypeReference:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002796 fErrors.error(expr.fOffset, "expected '(' to begin constructor invocation");
ethannicholasb3058bd2016-07-01 08:22:01 -07002797 break;
2798 default:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002799 if (expr.type() == *fContext.fInvalid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002800 fErrors.error(expr.fOffset, "invalid expression");
ethannicholasea4567c2016-10-17 11:24:37 -07002801 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002802 }
2803}
2804
John Stilesdce4d3e2020-09-25 14:35:13 -04002805bool IRGenerator::setRefKind(Expression& expr, VariableReference::RefKind kind) {
John Stilesa976da72020-09-25 23:06:26 -04002806 VariableReference* assignableVar = nullptr;
2807 if (!Analysis::IsAssignable(expr, &assignableVar, &fErrors)) {
John Stilesdce4d3e2020-09-25 14:35:13 -04002808 return false;
2809 }
John Stilesa976da72020-09-25 23:06:26 -04002810 if (assignableVar) {
2811 assignableVar->setRefKind(kind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002812 }
Ethan Nicholascb0f4092019-04-19 11:26:50 -04002813 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07002814}
2815
Brian Osman8e2ef022020-09-30 13:26:43 -04002816void IRGenerator::cloneBuiltinVariables() {
2817 class BuiltinVariableRemapper : public ProgramWriter {
2818 public:
2819 BuiltinVariableRemapper(IRGenerator* generator) : fGenerator(generator) {}
2820
Brian Osman00a8b5b2020-10-02 09:06:04 -04002821 void cloneVariable(const String& name) {
2822 // If this is the *first* time we've seen this builtin, findAndInclude will return
2823 // the corresponding ProgramElement.
Brian Osmanafa18ee2020-10-07 17:47:45 -04002824 if (const ProgramElement* sharedDecl = fGenerator->fIntrinsics->findAndInclude(name)) {
2825 SkASSERT(sharedDecl->is<GlobalVarDeclaration>() ||
2826 sharedDecl->is<InterfaceBlock>());
Brian Osman00a8b5b2020-10-02 09:06:04 -04002827
Brian Osmanafa18ee2020-10-07 17:47:45 -04002828 // Clone the ProgramElement that declares this variable
2829 std::unique_ptr<ProgramElement> clonedDecl = sharedDecl->clone();
2830 const Variable* sharedVar = nullptr;
2831 const Expression* initialValue = nullptr;
2832
2833 if (clonedDecl->is<GlobalVarDeclaration>()) {
2834 sharedVar = clonedDecl->as<GlobalVarDeclaration>().fDecl->fVar;
2835 initialValue = clonedDecl->as<GlobalVarDeclaration>().fDecl->fValue.get();
2836 } else {
2837 SkASSERT(clonedDecl->is<InterfaceBlock>());
2838 sharedVar = clonedDecl->as<InterfaceBlock>().fVariable;
2839 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002840
2841 // Now clone the Variable, and add the clone to the Program's symbol table.
Brian Osmanc0213602020-10-06 14:43:32 -04002842 // Any initial value expression was cloned as part of the GlobalVarDeclaration,
Brian Osman00a8b5b2020-10-02 09:06:04 -04002843 // so we're pointing at a Program-owned expression.
2844 const Variable* clonedVar =
2845 fGenerator->fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Variable>(
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002846 sharedVar->fOffset, sharedVar->modifiersHandle(), sharedVar->name(),
2847 &sharedVar->type(), /*builtin=*/false, sharedVar->storage(),
Brian Osmanafa18ee2020-10-07 17:47:45 -04002848 initialValue));
Brian Osman00a8b5b2020-10-02 09:06:04 -04002849
Brian Osmanafa18ee2020-10-07 17:47:45 -04002850 // Go back and update the declaring element to point at the cloned Variable.
2851 if (clonedDecl->is<GlobalVarDeclaration>()) {
2852 clonedDecl->as<GlobalVarDeclaration>().fDecl->fVar = clonedVar;
2853 } else {
2854 clonedDecl->as<InterfaceBlock>().fVariable = clonedVar;
2855 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002856
2857 // Remember this new re-mapping...
2858 fRemap.insert({sharedVar, clonedVar});
2859
Brian Osmanafa18ee2020-10-07 17:47:45 -04002860 // Add the declaring element to this Program
2861 fNewElements.push_back(std::move(clonedDecl));
Brian Osman00a8b5b2020-10-02 09:06:04 -04002862 }
2863 }
2864
Brian Osman8e2ef022020-09-30 13:26:43 -04002865 bool visitExpression(Expression& e) override {
2866 // Look for references to builtin variables.
Ethan Nicholas78686922020-10-08 06:46:27 -04002867 if (e.is<VariableReference>() && e.as<VariableReference>().variable()->isBuiltin()) {
2868 const Variable* sharedVar = e.as<VariableReference>().variable();
Brian Osman8e2ef022020-09-30 13:26:43 -04002869
Ethan Nicholase2c49992020-10-05 11:49:11 -04002870 this->cloneVariable(sharedVar->name());
Brian Osman8e2ef022020-09-30 13:26:43 -04002871
2872 // TODO: SkASSERT(found), once all pre-includes are converted?
2873 auto found = fRemap.find(sharedVar);
2874 if (found != fRemap.end()) {
2875 e.as<VariableReference>().setVariable(found->second);
2876 }
2877 }
2878
2879 return INHERITED::visitExpression(e);
2880 }
2881
2882 IRGenerator* fGenerator;
2883 std::unordered_map<const Variable*, const Variable*> fRemap;
2884 std::vector<std::unique_ptr<ProgramElement>> fNewElements;
2885
2886 using INHERITED = ProgramWriter;
2887 using INHERITED::visitProgramElement;
2888 };
2889
Brian Osman00a8b5b2020-10-02 09:06:04 -04002890 BuiltinVariableRemapper remapper(this);
2891 for (auto& e : *fProgramElements) {
2892 remapper.visitProgramElement(*e);
Brian Osman8e2ef022020-09-30 13:26:43 -04002893 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002894
2895 // Vulkan requires certain builtin variables be present, even if they're unused. At one time,
2896 // validation errors would result if they were missing. Now, it's just (Adreno) driver bugs
2897 // that drop or corrupt draws if they're missing.
2898 switch (fKind) {
2899 case Program::kFragment_Kind:
2900 remapper.cloneVariable("sk_Clockwise");
2901 break;
2902 default:
2903 break;
2904 }
2905
2906 fProgramElements->insert(fProgramElements->begin(),
Brian Osmanafa18ee2020-10-07 17:47:45 -04002907 std::make_move_iterator(remapper.fNewElements.begin()),
2908 std::make_move_iterator(remapper.fNewElements.end()));
Brian Osman8e2ef022020-09-30 13:26:43 -04002909}
2910
Brian Osman88cda172020-10-09 12:05:16 -04002911IRGenerator::IRBundle IRGenerator::convertProgram(
2912 Program::Kind kind,
2913 const Program::Settings* settings,
2914 const ParsedModule& base,
2915 bool isBuiltinCode,
2916 const char* text,
2917 size_t length,
2918 const std::vector<std::unique_ptr<ExternalValue>>* externalValues) {
Robert Phillipsfe8da172018-01-24 14:52:02 +00002919 fKind = kind;
Brian Osman88cda172020-10-09 12:05:16 -04002920 fSettings = settings;
2921 fSymbolTable = base.fSymbols;
2922 fIntrinsics = base.fIntrinsics.get();
2923 if (fIntrinsics) {
2924 fIntrinsics->resetAlreadyIncluded();
2925 }
2926 fIsBuiltinCode = isBuiltinCode;
2927
2928 std::vector<std::unique_ptr<ProgramElement>> elements;
2929 fProgramElements = &elements;
2930
2931 fInputs.reset();
2932 fInvocations = -1;
2933 fRTAdjust = nullptr;
2934 fRTAdjustInterfaceBlock = nullptr;
2935
2936 fCapsMap.clear();
2937 if (settings->fCaps) {
2938 fill_caps(*settings->fCaps, &fCapsMap);
2939 } else {
2940 fCapsMap.insert({String("integerSupport"), Program::Settings::Value(true)});
2941 }
2942
2943 this->pushSymbolTable();
2944
2945 if (externalValues) {
2946 // Add any external values to the new symbol table, so they're only visible to this Program
2947 for (const auto& ev : *externalValues) {
2948 fSymbolTable->addWithoutOwnership(ev.get());
2949 }
2950 }
2951
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002952 Parser parser(text, length, *fSymbolTable, fErrors);
Ethan Nicholasfc994162019-06-06 10:04:27 -04002953 fFile = parser.file();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002954 if (fErrors.errorCount()) {
Brian Osman88cda172020-10-09 12:05:16 -04002955 return {};
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002956 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002957 SkASSERT(fFile);
2958 for (const auto& decl : fFile->root()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002959 switch (decl.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002960 case ASTNode::Kind::kVarDeclarations: {
Brian Osmanc0213602020-10-06 14:43:32 -04002961 std::vector<std::unique_ptr<Statement>> decls =
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002962 this->convertVarDeclarations(decl, Variable::Storage::kGlobal);
Brian Osmanc0213602020-10-06 14:43:32 -04002963 for (auto& varDecl : decls) {
2964 fProgramElements->push_back(std::make_unique<GlobalVarDeclaration>(
2965 decl.fOffset, std::move(varDecl)));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002966 }
2967 break;
2968 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002969 case ASTNode::Kind::kEnum: {
2970 this->convertEnum(decl);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002971 break;
2972 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002973 case ASTNode::Kind::kFunction: {
2974 this->convertFunction(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002975 break;
2976 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002977 case ASTNode::Kind::kModifiers: {
2978 std::unique_ptr<ModifiersDeclaration> f = this->convertModifiersDeclaration(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002979 if (f) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002980 fProgramElements->push_back(std::move(f));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002981 }
2982 break;
2983 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002984 case ASTNode::Kind::kInterfaceBlock: {
2985 std::unique_ptr<InterfaceBlock> i = this->convertInterfaceBlock(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002986 if (i) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002987 fProgramElements->push_back(std::move(i));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002988 }
2989 break;
2990 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002991 case ASTNode::Kind::kExtension: {
2992 std::unique_ptr<Extension> e = this->convertExtension(decl.fOffset,
2993 decl.getString());
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002994 if (e) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002995 fProgramElements->push_back(std::move(e));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002996 }
2997 break;
2998 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002999 case ASTNode::Kind::kSection: {
3000 std::unique_ptr<Section> s = this->convertSection(decl);
Ethan Nicholas762466e2017-06-29 10:03:38 -04003001 if (s) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003002 fProgramElements->push_back(std::move(s));
Ethan Nicholas762466e2017-06-29 10:03:38 -04003003 }
3004 break;
3005 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003006 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003007#ifdef SK_DEBUG
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003008 ABORT("unsupported declaration: %s\n", decl.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003009#endif
3010 break;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003011 }
3012 }
Brian Osmanc95d3a12020-09-09 10:56:27 -04003013
Brian Osman8e2ef022020-09-30 13:26:43 -04003014 // Any variables defined in the pre-includes need to be cloned into the Program
Brian Osman00a8b5b2020-10-02 09:06:04 -04003015 if (!fIsBuiltinCode && fIntrinsics) {
3016 this->cloneBuiltinVariables();
3017 }
Brian Osman8e2ef022020-09-30 13:26:43 -04003018
Brian Osmanc95d3a12020-09-09 10:56:27 -04003019 // Do a final pass looking for dangling FunctionReference or TypeReference expressions
3020 class FindIllegalExpressions : public ProgramVisitor {
3021 public:
3022 FindIllegalExpressions(IRGenerator* generator) : fGenerator(generator) {}
3023
3024 bool visitExpression(const Expression& e) override {
3025 fGenerator->checkValid(e);
3026 return INHERITED::visitExpression(e);
3027 }
3028
3029 IRGenerator* fGenerator;
3030 using INHERITED = ProgramVisitor;
3031 using INHERITED::visitProgramElement;
3032 };
3033 for (const auto& pe : *fProgramElements) {
3034 FindIllegalExpressions{this}.visitProgramElement(*pe);
3035 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003036
Brian Osman88cda172020-10-09 12:05:16 -04003037 IRBundle result = {std::move(elements), this->releaseModifiers(), fSymbolTable, fInputs};
3038
3039 this->popSymbolTable();
3040 fSettings = nullptr;
3041
3042 return result;
3043}
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003044
John Stilesa6841be2020-08-06 14:11:56 -04003045} // namespace SkSL