blob: 8d586487916c2c45cfa585cc04eb64a64eb42166 [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"
John Stiles569249b2020-11-03 12:18:22 -050037#include "src/sksl/ir/SkSLFunctionPrototype.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050038#include "src/sksl/ir/SkSLFunctionReference.h"
39#include "src/sksl/ir/SkSLIfStatement.h"
40#include "src/sksl/ir/SkSLIndexExpression.h"
41#include "src/sksl/ir/SkSLIntLiteral.h"
42#include "src/sksl/ir/SkSLInterfaceBlock.h"
43#include "src/sksl/ir/SkSLLayout.h"
Chris Daltonb0fd4b12019-10-29 13:41:22 -060044#include "src/sksl/ir/SkSLNop.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050045#include "src/sksl/ir/SkSLNullLiteral.h"
46#include "src/sksl/ir/SkSLPostfixExpression.h"
47#include "src/sksl/ir/SkSLPrefixExpression.h"
48#include "src/sksl/ir/SkSLReturnStatement.h"
49#include "src/sksl/ir/SkSLSetting.h"
50#include "src/sksl/ir/SkSLSwitchCase.h"
51#include "src/sksl/ir/SkSLSwitchStatement.h"
52#include "src/sksl/ir/SkSLSwizzle.h"
53#include "src/sksl/ir/SkSLTernaryExpression.h"
54#include "src/sksl/ir/SkSLUnresolvedFunction.h"
55#include "src/sksl/ir/SkSLVarDeclarations.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050056#include "src/sksl/ir/SkSLVariable.h"
57#include "src/sksl/ir/SkSLVariableReference.h"
58#include "src/sksl/ir/SkSLWhileStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070059
60namespace SkSL {
61
62class AutoSymbolTable {
63public:
Ethan Nicholas11d53972016-11-28 11:23:23 -050064 AutoSymbolTable(IRGenerator* ir)
ethannicholasb3058bd2016-07-01 08:22:01 -070065 : fIR(ir)
66 , fPrevious(fIR->fSymbolTable) {
67 fIR->pushSymbolTable();
68 }
69
70 ~AutoSymbolTable() {
71 fIR->popSymbolTable();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -040072 SkASSERT(fPrevious == fIR->fSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -070073 }
74
75 IRGenerator* fIR;
76 std::shared_ptr<SymbolTable> fPrevious;
77};
78
ethannicholas22f939e2016-10-13 13:25:34 -070079class AutoLoopLevel {
80public:
Ethan Nicholas11d53972016-11-28 11:23:23 -050081 AutoLoopLevel(IRGenerator* ir)
ethannicholas22f939e2016-10-13 13:25:34 -070082 : fIR(ir) {
83 fIR->fLoopLevel++;
84 }
85
86 ~AutoLoopLevel() {
87 fIR->fLoopLevel--;
88 }
89
90 IRGenerator* fIR;
91};
92
Ethan Nicholasaf197692017-02-27 13:26:45 -050093class AutoSwitchLevel {
94public:
95 AutoSwitchLevel(IRGenerator* ir)
96 : fIR(ir) {
97 fIR->fSwitchLevel++;
98 }
99
100 ~AutoSwitchLevel() {
101 fIR->fSwitchLevel--;
102 }
103
104 IRGenerator* fIR;
105};
106
John Stiles4c412bc2020-10-13 11:19:41 -0400107class AutoDisableInline {
108public:
109 AutoDisableInline(IRGenerator* ir, bool canInline = false)
110 : fIR(ir) {
111 fOldCanInline = ir->fCanInline;
112 fIR->fCanInline &= canInline;
113 }
114
115 ~AutoDisableInline() {
116 fIR->fCanInline = fOldCanInline;
117 }
118
119 IRGenerator* fIR;
120 bool fOldCanInline;
121};
122
123IRGenerator::IRGenerator(const Context* context, Inliner* inliner, ErrorReporter& errorReporter)
John Stiles7b463002020-08-31 17:29:21 -0400124 : fContext(*context)
John Stiles4c412bc2020-10-13 11:19:41 -0400125 , fInliner(inliner)
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400126 , fErrors(errorReporter)
John Stiles4c412bc2020-10-13 11:19:41 -0400127 , fModifiers(new ModifiersPool()) {
128 SkASSERT(fInliner);
129}
ethannicholasb3058bd2016-07-01 08:22:01 -0700130
131void IRGenerator::pushSymbolTable() {
John Stiles7c3515b2020-10-16 18:38:39 -0400132 auto childSymTable = std::make_shared<SymbolTable>(std::move(fSymbolTable), fIsBuiltinCode);
133 fSymbolTable = std::move(childSymTable);
ethannicholasb3058bd2016-07-01 08:22:01 -0700134}
135
136void IRGenerator::popSymbolTable() {
137 fSymbolTable = fSymbolTable->fParent;
138}
139
John Stiles194b9b92020-09-15 15:37:24 -0400140static void fill_caps(const SkSL::ShaderCapsClass& caps,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400141 std::unordered_map<String, Program::Settings::Value>* capsMap) {
Brian Osman88cda172020-10-09 12:05:16 -0400142#define CAP(name) capsMap->insert({String(#name), Program::Settings::Value(caps.name())})
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500143 CAP(fbFetchSupport);
Brian Salomond4013302018-04-04 13:58:33 +0000144 CAP(fbFetchNeedsCustomOutput);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500145 CAP(flatInterpolationSupport);
146 CAP(noperspectiveInterpolationSupport);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500147 CAP(externalTextureSupport);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500148 CAP(mustEnableAdvBlendEqs);
149 CAP(mustEnableSpecificAdvBlendEqs);
150 CAP(mustDeclareFragmentShaderOutput);
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400151 CAP(mustDoOpBetweenFloorAndAbs);
Brian Salomonf8c187c2019-12-19 14:41:57 -0500152 CAP(mustGuardDivisionEvenAfterExplicitZeroCheck);
153 CAP(inBlendModesFailRandomlyForAllZeroVec);
Michael Ludwig24d438b2018-09-12 15:22:50 -0400154 CAP(atan2ImplementedAsAtanYOverX);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500155 CAP(canUseAnyFunctionInShader);
Chris Dalton47c8ed32017-11-15 18:27:09 -0700156 CAP(floatIs32Bits);
Ethan Nicholas07990de2017-07-18 09:47:43 -0400157 CAP(integerSupport);
John Stiles6f3015a2020-10-08 14:55:36 -0400158 CAP(builtinFMASupport);
159 CAP(builtinDeterminantSupport);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500160#undef CAP
161}
162
Ethan Nicholasfc994162019-06-06 10:04:27 -0400163std::unique_ptr<Extension> IRGenerator::convertExtension(int offset, StringFragment name) {
Brian Osman16f376f2020-09-02 12:30:59 -0400164 if (fKind != Program::kFragment_Kind &&
165 fKind != Program::kVertex_Kind &&
166 fKind != Program::kGeometry_Kind) {
167 fErrors.error(offset, "extensions are not allowed here");
168 return nullptr;
169 }
170
John Stilesfbd050b2020-08-03 13:21:46 -0400171 return std::make_unique<Extension>(offset, name);
ethannicholasb3058bd2016-07-01 08:22:01 -0700172}
173
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400174std::unique_ptr<ModifiersPool> IRGenerator::releaseModifiers() {
175 std::unique_ptr<ModifiersPool> result = std::move(fModifiers);
176 fModifiers = std::make_unique<ModifiersPool>();
177 return result;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400178}
179
Ethan Nicholas70728ef2020-05-28 07:09:00 -0400180std::unique_ptr<Statement> IRGenerator::convertSingleStatement(const ASTNode& statement) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700181 switch (statement.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400182 case ASTNode::Kind::kBlock:
183 return this->convertBlock(statement);
184 case ASTNode::Kind::kVarDeclarations:
185 return this->convertVarDeclarationStatement(statement);
186 case ASTNode::Kind::kIf:
187 return this->convertIf(statement);
188 case ASTNode::Kind::kFor:
189 return this->convertFor(statement);
190 case ASTNode::Kind::kWhile:
191 return this->convertWhile(statement);
192 case ASTNode::Kind::kDo:
193 return this->convertDo(statement);
194 case ASTNode::Kind::kSwitch:
195 return this->convertSwitch(statement);
196 case ASTNode::Kind::kReturn:
197 return this->convertReturn(statement);
198 case ASTNode::Kind::kBreak:
199 return this->convertBreak(statement);
200 case ASTNode::Kind::kContinue:
201 return this->convertContinue(statement);
202 case ASTNode::Kind::kDiscard:
203 return this->convertDiscard(statement);
204 default:
205 // it's an expression
206 std::unique_ptr<Statement> result = this->convertExpressionStatement(statement);
Ethan Nicholase6592142020-09-08 10:22:09 -0400207 if (fRTAdjust && fKind == Program::kGeometry_Kind) {
208 SkASSERT(result->kind() == Statement::Kind::kExpression);
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400209 Expression& expr = *result->as<ExpressionStatement>().expression();
Ethan Nicholase6592142020-09-08 10:22:09 -0400210 if (expr.kind() == Expression::Kind::kFunctionCall) {
John Stiles403a3632020-08-20 12:11:48 -0400211 FunctionCall& fc = expr.as<FunctionCall>();
Ethan Nicholased84b732020-10-08 11:45:44 -0400212 if (fc.function().isBuiltin() && fc.function().name() == "EmitVertex") {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400213 StatementArray statements;
John Stilesf4bda742020-10-14 16:57:41 -0400214 statements.reserve_back(2);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000215 statements.push_back(getNormalizeSkPositionCode());
216 statements.push_back(std::move(result));
John Stilesfbd050b2020-08-03 13:21:46 -0400217 return std::make_unique<Block>(statement.fOffset, std::move(statements),
218 fSymbolTable);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000219 }
220 }
221 }
222 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700223 }
224}
225
Ethan Nicholas70728ef2020-05-28 07:09:00 -0400226std::unique_ptr<Statement> IRGenerator::convertStatement(const ASTNode& statement) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400227 StatementArray oldExtraStatements = std::move(fExtraStatements);
Ethan Nicholas70728ef2020-05-28 07:09:00 -0400228 std::unique_ptr<Statement> result = this->convertSingleStatement(statement);
229 if (!result) {
230 fExtraStatements = std::move(oldExtraStatements);
231 return nullptr;
232 }
233 if (fExtraStatements.size()) {
234 fExtraStatements.push_back(std::move(result));
John Stiles8f2a0cf2020-10-13 12:48:21 -0400235 auto block = std::make_unique<Block>(/*offset=*/-1, std::move(fExtraStatements),
236 /*symbols=*/nullptr, /*isScope=*/false);
Ethan Nicholas70728ef2020-05-28 07:09:00 -0400237 fExtraStatements = std::move(oldExtraStatements);
John Stiles8f2a0cf2020-10-13 12:48:21 -0400238 return std::move(block);
Ethan Nicholas70728ef2020-05-28 07:09:00 -0400239 }
240 fExtraStatements = std::move(oldExtraStatements);
241 return result;
242}
243
Ethan Nicholasfc994162019-06-06 10:04:27 -0400244std::unique_ptr<Block> IRGenerator::convertBlock(const ASTNode& block) {
245 SkASSERT(block.fKind == ASTNode::Kind::kBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700246 AutoSymbolTable table(this);
John Stiles8f2a0cf2020-10-13 12:48:21 -0400247 StatementArray statements;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400248 for (const auto& child : block) {
249 std::unique_ptr<Statement> statement = this->convertStatement(child);
ethannicholasb3058bd2016-07-01 08:22:01 -0700250 if (!statement) {
251 return nullptr;
252 }
253 statements.push_back(std::move(statement));
254 }
John Stilesfbd050b2020-08-03 13:21:46 -0400255 return std::make_unique<Block>(block.fOffset, std::move(statements), fSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -0700256}
257
Ethan Nicholasfc994162019-06-06 10:04:27 -0400258std::unique_ptr<Statement> IRGenerator::convertVarDeclarationStatement(const ASTNode& s) {
259 SkASSERT(s.fKind == ASTNode::Kind::kVarDeclarations);
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400260 auto decls = this->convertVarDeclarations(s, Variable::Storage::kLocal);
Brian Osmanc0213602020-10-06 14:43:32 -0400261 if (decls.empty()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700262 return nullptr;
263 }
Brian Osmanc0213602020-10-06 14:43:32 -0400264 if (decls.size() == 1) {
265 return std::move(decls.front());
266 } else {
267 return std::make_unique<Block>(s.fOffset, std::move(decls), /*symbols=*/nullptr,
268 /*isScope=*/false);
269 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700270}
271
John Stiles8f2a0cf2020-10-13 12:48:21 -0400272StatementArray IRGenerator::convertVarDeclarations(const ASTNode& decls,
273 Variable::Storage storage) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400274 SkASSERT(decls.fKind == ASTNode::Kind::kVarDeclarations);
John Stilesf621e232020-08-25 13:33:02 -0400275 auto declarationsIter = decls.begin();
276 const Modifiers& modifiers = declarationsIter++->getModifiers();
277 const ASTNode& rawType = *(declarationsIter++);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400278 const Type* baseType = this->convertType(rawType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700279 if (!baseType) {
Brian Osmanc0213602020-10-06 14:43:32 -0400280 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700281 }
Brian Osman82329002020-07-21 09:39:27 -0400282 if (baseType->nonnullable() == *fContext.fFragmentProcessor_Type &&
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400283 storage != Variable::Storage::kGlobal) {
Brian Osman82329002020-07-21 09:39:27 -0400284 fErrors.error(decls.fOffset,
285 "variables of type '" + baseType->displayName() + "' must be global");
286 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500287 if (fKind != Program::kFragmentProcessor_Kind) {
288 if ((modifiers.fFlags & Modifiers::kIn_Flag) &&
Ethan Nicholase6592142020-09-08 10:22:09 -0400289 baseType->typeKind() == Type::TypeKind::kMatrix) {
Brian Osman2fe83fe2019-12-16 13:17:59 -0500290 fErrors.error(decls.fOffset, "'in' variables may not have matrix type");
291 }
Brian Osman088913a2019-12-19 15:44:56 -0500292 if ((modifiers.fFlags & Modifiers::kIn_Flag) &&
293 (modifiers.fFlags & Modifiers::kUniform_Flag)) {
294 fErrors.error(decls.fOffset,
295 "'in uniform' variables only permitted within fragment processors");
296 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500297 if (modifiers.fLayout.fWhen.fLength) {
298 fErrors.error(decls.fOffset, "'when' is only permitted within fragment processors");
299 }
300 if (modifiers.fLayout.fFlags & Layout::kTracked_Flag) {
301 fErrors.error(decls.fOffset, "'tracked' is only permitted within fragment processors");
302 }
303 if (modifiers.fLayout.fCType != Layout::CType::kDefault) {
304 fErrors.error(decls.fOffset, "'ctype' is only permitted within fragment processors");
305 }
306 if (modifiers.fLayout.fKey) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400307 fErrors.error(decls.fOffset, "'key' is only permitted within fragment processors");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400308 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500309 }
Brian Osmana4b91692020-08-10 14:26:16 -0400310 if (fKind == Program::kPipelineStage_Kind) {
311 if ((modifiers.fFlags & Modifiers::kIn_Flag) &&
312 baseType->nonnullable() != *fContext.fFragmentProcessor_Type) {
313 fErrors.error(decls.fOffset, "'in' variables not permitted in runtime effects");
314 }
315 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500316 if (modifiers.fLayout.fKey && (modifiers.fFlags & Modifiers::kUniform_Flag)) {
317 fErrors.error(decls.fOffset, "'key' is not permitted on 'uniform' variables");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400318 }
Brian Osmanf59a9612020-04-15 14:18:13 -0400319 if (modifiers.fLayout.fMarker.fLength) {
320 if (fKind != Program::kPipelineStage_Kind) {
321 fErrors.error(decls.fOffset, "'marker' is only permitted in runtime effects");
322 }
323 if (!(modifiers.fFlags & Modifiers::kUniform_Flag)) {
324 fErrors.error(decls.fOffset, "'marker' is only permitted on 'uniform' variables");
325 }
326 if (*baseType != *fContext.fFloat4x4_Type) {
327 fErrors.error(decls.fOffset, "'marker' is only permitted on float4x4 variables");
328 }
329 }
Brian Osmanb32d66b2020-04-30 17:12:03 -0400330 if (modifiers.fLayout.fFlags & Layout::kSRGBUnpremul_Flag) {
331 if (fKind != Program::kPipelineStage_Kind) {
332 fErrors.error(decls.fOffset, "'srgb_unpremul' is only permitted in runtime effects");
333 }
334 if (!(modifiers.fFlags & Modifiers::kUniform_Flag)) {
335 fErrors.error(decls.fOffset,
336 "'srgb_unpremul' is only permitted on 'uniform' variables");
337 }
338 auto validColorXformType = [](const Type& t) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400339 return t.typeKind() == Type::TypeKind::kVector && t.componentType().isFloat() &&
Brian Osmanb32d66b2020-04-30 17:12:03 -0400340 (t.columns() == 3 || t.columns() == 4);
341 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400342 if (!validColorXformType(*baseType) && !(baseType->typeKind() == Type::TypeKind::kArray &&
Brian Osmanb32d66b2020-04-30 17:12:03 -0400343 validColorXformType(baseType->componentType()))) {
344 fErrors.error(decls.fOffset,
345 "'srgb_unpremul' is only permitted on half3, half4, float3, or float4 "
346 "variables");
347 }
348 }
Brian Osman3c358422020-03-23 10:44:12 -0400349 if (modifiers.fFlags & Modifiers::kVarying_Flag) {
350 if (fKind != Program::kPipelineStage_Kind) {
351 fErrors.error(decls.fOffset, "'varying' is only permitted in runtime effects");
352 }
353 if (!baseType->isFloat() &&
Ethan Nicholase6592142020-09-08 10:22:09 -0400354 !(baseType->typeKind() == Type::TypeKind::kVector &&
355 baseType->componentType().isFloat())) {
Brian Osman3c358422020-03-23 10:44:12 -0400356 fErrors.error(decls.fOffset, "'varying' must be float scalar or vector");
357 }
358 }
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400359 int permitted = Modifiers::kConst_Flag;
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400360 if (storage == Variable::Storage::kGlobal) {
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400361 permitted |= Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag |
362 Modifiers::kFlat_Flag | Modifiers::kVarying_Flag |
363 Modifiers::kNoPerspective_Flag | Modifiers::kPLS_Flag |
364 Modifiers::kPLSIn_Flag | Modifiers::kPLSOut_Flag |
365 Modifiers::kRestrict_Flag | Modifiers::kVolatile_Flag |
366 Modifiers::kReadOnly_Flag | Modifiers::kWriteOnly_Flag |
367 Modifiers::kCoherent_Flag | Modifiers::kBuffer_Flag;
368 }
369 this->checkModifiers(decls.fOffset, modifiers, permitted);
John Stiles8f2a0cf2020-10-13 12:48:21 -0400370
371 StatementArray varDecls;
John Stiles9cef66f2020-10-23 09:46:11 -0400372 bool firstDecl = true;
John Stilesf621e232020-08-25 13:33:02 -0400373 for (; declarationsIter != decls.end(); ++declarationsIter) {
John Stiles9cef66f2020-10-23 09:46:11 -0400374 AutoDisableInline disableInline(this, /*canInline=*/firstDecl);
375 firstDecl = false;
376
John Stilesf621e232020-08-25 13:33:02 -0400377 const ASTNode& varDecl = *declarationsIter;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400378 if (modifiers.fLayout.fLocation == 0 && modifiers.fLayout.fIndex == 0 &&
379 (modifiers.fFlags & Modifiers::kOut_Flag) && fKind == Program::kFragment_Kind &&
380 varDecl.getVarData().fName != "sk_FragColor") {
381 fErrors.error(varDecl.fOffset,
Ethan Nicholas6c942712018-03-16 09:45:11 -0400382 "out location=0, index=0 is reserved for sk_FragColor");
383 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400384 const ASTNode::VarData& varData = varDecl.getVarData();
ethannicholasd598f792016-07-25 10:08:54 -0700385 const Type* type = baseType;
John Stiles87ae34e2020-10-13 12:50:11 -0400386 ExpressionArray sizes;
John Stilesf4bda742020-10-14 16:57:41 -0400387 sizes.reserve_back(varData.fSizeCount);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400388 auto iter = varDecl.begin();
389 for (size_t i = 0; i < varData.fSizeCount; ++i, ++iter) {
390 const ASTNode& rawSize = *iter;
ethannicholas14fe8cc2016-09-07 13:37:16 -0700391 if (rawSize) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400392 auto size = this->coerce(this->convertExpression(rawSize), *fContext.fInt_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700393 if (!size) {
Brian Osmanc0213602020-10-06 14:43:32 -0400394 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700395 }
Ethan Nicholase2c49992020-10-05 11:49:11 -0400396 String name(type->name());
Ethan Nicholas50afc172017-02-16 14:49:57 -0500397 int64_t count;
John Stiles84d503b2020-11-09 11:19:02 -0500398 if (size->is<IntLiteral>()) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400399 count = size->as<IntLiteral>().value();
ethannicholasb3058bd2016-07-01 08:22:01 -0700400 if (count <= 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700401 fErrors.error(size->fOffset, "array size must be positive");
Brian Osmanc0213602020-10-06 14:43:32 -0400402 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700403 }
404 name += "[" + to_string(count) + "]";
405 } else {
Ethan Nicholas66d80062019-09-09 14:50:51 -0400406 fErrors.error(size->fOffset, "array size must be specified");
Brian Osmanc0213602020-10-06 14:43:32 -0400407 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700408 }
John Stiles3ae071e2020-08-05 15:29:29 -0400409 type = fSymbolTable->takeOwnershipOfSymbol(
Ethan Nicholase6592142020-09-08 10:22:09 -0400410 std::make_unique<Type>(name, Type::TypeKind::kArray, *type, (int)count));
ethannicholas14fe8cc2016-09-07 13:37:16 -0700411 sizes.push_back(std::move(size));
ethannicholasb3058bd2016-07-01 08:22:01 -0700412 } else {
John Stiles3ae071e2020-08-05 15:29:29 -0400413 type = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
Brian Osmane8c26082020-10-01 17:22:45 -0400414 type->name() + "[]", Type::TypeKind::kArray, *type, Type::kUnsizedArray));
ethannicholas14fe8cc2016-09-07 13:37:16 -0700415 sizes.push_back(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700416 }
417 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400418 auto var = std::make_unique<Variable>(varDecl.fOffset, fModifiers->handle(modifiers),
419 varData.fName, type, fIsBuiltinCode, storage);
Ethan Nicholase2c49992020-10-05 11:49:11 -0400420 if (var->name() == Compiler::RTADJUST_NAME) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400421 SkASSERT(!fRTAdjust);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400422 SkASSERT(var->type() == *fContext.fFloat4_Type);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000423 fRTAdjust = var.get();
424 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700425 std::unique_ptr<Expression> value;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400426 if (iter != varDecl.end()) {
427 value = this->convertExpression(*iter);
ethannicholasb3058bd2016-07-01 08:22:01 -0700428 if (!value) {
Brian Osmanc0213602020-10-06 14:43:32 -0400429 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700430 }
John Stiles84d503b2020-11-09 11:19:02 -0500431 if (modifiers.fFlags & Modifiers::kIn_Flag) {
432 fErrors.error(value->fOffset, "'in' variables cannot use initializer expressions");
433 }
ethannicholasd598f792016-07-25 10:08:54 -0700434 value = this->coerce(std::move(value), *type);
Ethan Nicholas68dd2c12018-03-01 15:05:17 -0500435 if (!value) {
Brian Osmanc0213602020-10-06 14:43:32 -0400436 return {};
Ethan Nicholas68dd2c12018-03-01 15:05:17 -0500437 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400438 var->setInitialValue(value.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700439 }
Brian Osman8dbdf232020-10-12 14:40:24 -0400440 const Symbol* symbol = (*fSymbolTable)[var->name()];
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400441 if (symbol && storage == Variable::Storage::kGlobal && var->name() == "sk_FragColor") {
John Stilesce591b72020-08-27 11:47:30 -0400442 // Already defined, ignore.
ethannicholasf789b382016-08-03 12:43:36 -0700443 } else {
John Stilesb8cc6652020-10-08 09:12:07 -0400444 varDecls.push_back(std::make_unique<VarDeclaration>(
Brian Osmanc0213602020-10-06 14:43:32 -0400445 var.get(), baseType, std::move(sizes), std::move(value)));
John Stilesb8cc6652020-10-08 09:12:07 -0400446 fSymbolTable->add(std::move(var));
ethannicholasf789b382016-08-03 12:43:36 -0700447 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700448 }
Brian Osmanc0213602020-10-06 14:43:32 -0400449 return varDecls;
ethannicholasb3058bd2016-07-01 08:22:01 -0700450}
451
Ethan Nicholasfc994162019-06-06 10:04:27 -0400452std::unique_ptr<ModifiersDeclaration> IRGenerator::convertModifiersDeclaration(const ASTNode& m) {
Brian Osman16f376f2020-09-02 12:30:59 -0400453 if (fKind != Program::kFragment_Kind &&
454 fKind != Program::kVertex_Kind &&
455 fKind != Program::kGeometry_Kind) {
456 fErrors.error(m.fOffset, "layout qualifiers are not allowed here");
457 return nullptr;
458 }
459
Ethan Nicholasfc994162019-06-06 10:04:27 -0400460 SkASSERT(m.fKind == ASTNode::Kind::kModifiers);
461 Modifiers modifiers = m.getModifiers();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400462 if (modifiers.fLayout.fInvocations != -1) {
Ethan Nicholasf06576b2019-04-03 15:45:25 -0400463 if (fKind != Program::kGeometry_Kind) {
464 fErrors.error(m.fOffset, "'invocations' is only legal in geometry shaders");
465 return nullptr;
466 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400467 fInvocations = modifiers.fLayout.fInvocations;
Brian Osmand7e76592020-11-02 12:26:22 -0500468 if (fCaps && !fCaps->gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400469 modifiers.fLayout.fInvocations = -1;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400470 if (modifiers.fLayout.description() == "") {
471 return nullptr;
472 }
473 }
474 }
Brian Osmand7e76592020-11-02 12:26:22 -0500475 if (modifiers.fLayout.fMaxVertices != -1 && fInvocations > 0 && fCaps &&
476 !fCaps->gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400477 modifiers.fLayout.fMaxVertices *= fInvocations;
478 }
Ethan Nicholas077050b2020-10-13 10:30:20 -0400479 return std::make_unique<ModifiersDeclaration>(fModifiers->handle(modifiers));
ethannicholas5961bc92016-10-12 06:39:56 -0700480}
481
John Stilesad2319f2020-09-02 15:01:47 -0400482std::unique_ptr<Statement> IRGenerator::convertIf(const ASTNode& n) {
483 SkASSERT(n.fKind == ASTNode::Kind::kIf);
484 auto iter = n.begin();
485 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
486 *fContext.fBool_Type);
487 if (!test) {
488 return nullptr;
489 }
490 std::unique_ptr<Statement> ifTrue = this->convertStatement(*(iter++));
491 if (!ifTrue) {
492 return nullptr;
493 }
John Stilesad2319f2020-09-02 15:01:47 -0400494 std::unique_ptr<Statement> ifFalse;
495 if (iter != n.end()) {
496 ifFalse = this->convertStatement(*(iter++));
497 if (!ifFalse) {
498 return nullptr;
499 }
John Stilesad2319f2020-09-02 15:01:47 -0400500 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400501 if (test->kind() == Expression::Kind::kBoolLiteral) {
John Stilesad2319f2020-09-02 15:01:47 -0400502 // static boolean value, fold down to a single branch
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400503 if (test->as<BoolLiteral>().value()) {
John Stilesad2319f2020-09-02 15:01:47 -0400504 return ifTrue;
505 } else if (ifFalse) {
506 return ifFalse;
507 } else {
508 // False & no else clause. Not an error, so don't return null!
John Stiles2ff97062020-09-02 15:02:01 -0400509 return std::make_unique<Nop>();
John Stilesad2319f2020-09-02 15:01:47 -0400510 }
511 }
John Stiles4c412bc2020-10-13 11:19:41 -0400512 auto ifStmt = std::make_unique<IfStatement>(n.fOffset, n.getBool(), std::move(test),
513 std::move(ifTrue), std::move(ifFalse));
514 fInliner->ensureScopedBlocks(ifStmt->ifTrue().get(), ifStmt.get());
515 fInliner->ensureScopedBlocks(ifStmt->ifFalse().get(), ifStmt.get());
516 return std::move(ifStmt);
John Stilesad2319f2020-09-02 15:01:47 -0400517}
518
Ethan Nicholasfc994162019-06-06 10:04:27 -0400519std::unique_ptr<Statement> IRGenerator::convertFor(const ASTNode& f) {
520 SkASSERT(f.fKind == ASTNode::Kind::kFor);
ethannicholas22f939e2016-10-13 13:25:34 -0700521 AutoLoopLevel level(this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700522 AutoSymbolTable table(this);
ethannicholas22f939e2016-10-13 13:25:34 -0700523 std::unique_ptr<Statement> initializer;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400524 auto iter = f.begin();
525 if (*iter) {
526 initializer = this->convertStatement(*iter);
ethannicholas22f939e2016-10-13 13:25:34 -0700527 if (!initializer) {
528 return nullptr;
529 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700530 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400531 ++iter;
ethannicholas22f939e2016-10-13 13:25:34 -0700532 std::unique_ptr<Expression> test;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400533 if (*iter) {
John Stiles4c412bc2020-10-13 11:19:41 -0400534 AutoDisableInline disableInline(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400535 test = this->coerce(this->convertExpression(*iter), *fContext.fBool_Type);
ethannicholas22f939e2016-10-13 13:25:34 -0700536 if (!test) {
537 return nullptr;
538 }
John Stiles4c412bc2020-10-13 11:19:41 -0400539
ethannicholasb3058bd2016-07-01 08:22:01 -0700540 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400541 ++iter;
ethannicholas22f939e2016-10-13 13:25:34 -0700542 std::unique_ptr<Expression> next;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400543 if (*iter) {
John Stiles4c412bc2020-10-13 11:19:41 -0400544 AutoDisableInline disableInline(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400545 next = this->convertExpression(*iter);
ethannicholas22f939e2016-10-13 13:25:34 -0700546 if (!next) {
547 return nullptr;
548 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700549 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400550 ++iter;
551 std::unique_ptr<Statement> statement = this->convertStatement(*iter);
ethannicholasb3058bd2016-07-01 08:22:01 -0700552 if (!statement) {
553 return nullptr;
554 }
John Stiles4c412bc2020-10-13 11:19:41 -0400555 auto forStmt = std::make_unique<ForStatement>(f.fOffset, std::move(initializer),
556 std::move(test), std::move(next),
557 std::move(statement), fSymbolTable);
558 fInliner->ensureScopedBlocks(forStmt->statement().get(), forStmt.get());
559 return std::move(forStmt);
ethannicholasb3058bd2016-07-01 08:22:01 -0700560}
561
Ethan Nicholasfc994162019-06-06 10:04:27 -0400562std::unique_ptr<Statement> IRGenerator::convertWhile(const ASTNode& w) {
563 SkASSERT(w.fKind == ASTNode::Kind::kWhile);
ethannicholas22f939e2016-10-13 13:25:34 -0700564 AutoLoopLevel level(this);
John Stiles4c412bc2020-10-13 11:19:41 -0400565 std::unique_ptr<Expression> test;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400566 auto iter = w.begin();
John Stiles4c412bc2020-10-13 11:19:41 -0400567 {
568 AutoDisableInline disableInline(this);
569 test = this->coerce(this->convertExpression(*(iter++)), *fContext.fBool_Type);
570 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700571 if (!test) {
572 return nullptr;
573 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400574 std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700575 if (!statement) {
576 return nullptr;
577 }
John Stiles4c412bc2020-10-13 11:19:41 -0400578 auto whileStmt = std::make_unique<WhileStatement>(w.fOffset, std::move(test),
579 std::move(statement));
580 fInliner->ensureScopedBlocks(whileStmt->statement().get(), whileStmt.get());
581 return std::move(whileStmt);
ethannicholasb3058bd2016-07-01 08:22:01 -0700582}
583
Ethan Nicholasfc994162019-06-06 10:04:27 -0400584std::unique_ptr<Statement> IRGenerator::convertDo(const ASTNode& d) {
585 SkASSERT(d.fKind == ASTNode::Kind::kDo);
ethannicholas22f939e2016-10-13 13:25:34 -0700586 AutoLoopLevel level(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400587 auto iter = d.begin();
588 std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
589 if (!statement) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700590 return nullptr;
591 }
John Stiles4c412bc2020-10-13 11:19:41 -0400592 std::unique_ptr<Expression> test;
593 {
594 AutoDisableInline disableInline(this);
595 test = this->coerce(this->convertExpression(*(iter++)), *fContext.fBool_Type);
596 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400597 if (!test) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700598 return nullptr;
599 }
John Stiles4c412bc2020-10-13 11:19:41 -0400600 auto doStmt = std::make_unique<DoStatement>(d.fOffset, std::move(statement), std::move(test));
601 fInliner->ensureScopedBlocks(doStmt->statement().get(), doStmt.get());
602 return std::move(doStmt);
ethannicholasb3058bd2016-07-01 08:22:01 -0700603}
604
Ethan Nicholasfc994162019-06-06 10:04:27 -0400605std::unique_ptr<Statement> IRGenerator::convertSwitch(const ASTNode& s) {
606 SkASSERT(s.fKind == ASTNode::Kind::kSwitch);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500607 AutoSwitchLevel level(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400608 auto iter = s.begin();
609 std::unique_ptr<Expression> value = this->convertExpression(*(iter++));
Ethan Nicholasaf197692017-02-27 13:26:45 -0500610 if (!value) {
611 return nullptr;
612 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400613 if (value->type() != *fContext.fUInt_Type &&
614 value->type().typeKind() != Type::TypeKind::kEnum) {
Ethan Nicholasaf197692017-02-27 13:26:45 -0500615 value = this->coerce(std::move(value), *fContext.fInt_Type);
616 if (!value) {
617 return nullptr;
618 }
619 }
620 AutoSymbolTable table(this);
621 std::unordered_set<int> caseValues;
622 std::vector<std::unique_ptr<SwitchCase>> cases;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400623 for (; iter != s.end(); ++iter) {
624 const ASTNode& c = *iter;
625 SkASSERT(c.fKind == ASTNode::Kind::kSwitchCase);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500626 std::unique_ptr<Expression> caseValue;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400627 auto childIter = c.begin();
628 if (*childIter) {
629 caseValue = this->convertExpression(*childIter);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500630 if (!caseValue) {
631 return nullptr;
632 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400633 caseValue = this->coerce(std::move(caseValue), value->type());
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500634 if (!caseValue) {
635 return nullptr;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500636 }
Brian Osman3e3db6c2020-08-14 09:42:12 -0400637 int64_t v = 0;
638 if (!this->getConstantInt(*caseValue, &v)) {
639 fErrors.error(caseValue->fOffset, "case value must be a constant integer");
Ethan Nicholasaf197692017-02-27 13:26:45 -0500640 return nullptr;
641 }
Ethan Nicholasaf197692017-02-27 13:26:45 -0500642 if (caseValues.find(v) != caseValues.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700643 fErrors.error(caseValue->fOffset, "duplicate case value");
Ethan Nicholasaf197692017-02-27 13:26:45 -0500644 }
645 caseValues.insert(v);
646 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400647 ++childIter;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400648 StatementArray statements;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400649 for (; childIter != c.end(); ++childIter) {
650 std::unique_ptr<Statement> converted = this->convertStatement(*childIter);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500651 if (!converted) {
652 return nullptr;
653 }
654 statements.push_back(std::move(converted));
655 }
John Stiles8f2a0cf2020-10-13 12:48:21 -0400656 cases.push_back(std::make_unique<SwitchCase>(c.fOffset, std::move(caseValue),
657 std::move(statements)));
Ethan Nicholasaf197692017-02-27 13:26:45 -0500658 }
John Stiles8f2a0cf2020-10-13 12:48:21 -0400659 return std::make_unique<SwitchStatement>(s.fOffset, s.getBool(), std::move(value),
660 std::move(cases), fSymbolTable);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500661}
662
Ethan Nicholasfc994162019-06-06 10:04:27 -0400663std::unique_ptr<Statement> IRGenerator::convertExpressionStatement(const ASTNode& s) {
664 std::unique_ptr<Expression> e = this->convertExpression(s);
ethannicholasb3058bd2016-07-01 08:22:01 -0700665 if (!e) {
666 return nullptr;
667 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700668 return std::unique_ptr<Statement>(new ExpressionStatement(std::move(e)));
669}
670
Ethan Nicholasfc994162019-06-06 10:04:27 -0400671std::unique_ptr<Statement> IRGenerator::convertReturn(const ASTNode& r) {
672 SkASSERT(r.fKind == ASTNode::Kind::kReturn);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400673 SkASSERT(fCurrentFunction);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000674 // early returns from a vertex main function will bypass the sk_Position normalization, so
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400675 // 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 +0000676 // normalization before each return, but it will probably never actually be necessary.
Ethan Nicholase2c49992020-10-05 11:49:11 -0400677 SkASSERT(Program::kVertex_Kind != fKind || !fRTAdjust || "main" != fCurrentFunction->name());
Ethan Nicholasfc994162019-06-06 10:04:27 -0400678 if (r.begin() != r.end()) {
679 std::unique_ptr<Expression> result = this->convertExpression(*r.begin());
ethannicholasb3058bd2016-07-01 08:22:01 -0700680 if (!result) {
681 return nullptr;
682 }
Ethan Nicholased84b732020-10-08 11:45:44 -0400683 if (fCurrentFunction->returnType() == *fContext.fVoid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700684 fErrors.error(result->fOffset, "may not return a value from a void function");
Brian Osman5eea6ae2020-09-09 16:05:18 -0400685 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -0700686 } else {
Ethan Nicholased84b732020-10-08 11:45:44 -0400687 result = this->coerce(std::move(result), fCurrentFunction->returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700688 if (!result) {
689 return nullptr;
690 }
691 }
692 return std::unique_ptr<Statement>(new ReturnStatement(std::move(result)));
693 } else {
Ethan Nicholased84b732020-10-08 11:45:44 -0400694 if (fCurrentFunction->returnType() != *fContext.fVoid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700695 fErrors.error(r.fOffset, "expected function to return '" +
Ethan Nicholased84b732020-10-08 11:45:44 -0400696 fCurrentFunction->returnType().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -0700697 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700698 return std::unique_ptr<Statement>(new ReturnStatement(r.fOffset));
ethannicholasb3058bd2016-07-01 08:22:01 -0700699 }
700}
701
Ethan Nicholasfc994162019-06-06 10:04:27 -0400702std::unique_ptr<Statement> IRGenerator::convertBreak(const ASTNode& b) {
703 SkASSERT(b.fKind == ASTNode::Kind::kBreak);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500704 if (fLoopLevel > 0 || fSwitchLevel > 0) {
John Stilesb61ee902020-09-21 12:26:59 -0400705 return std::make_unique<BreakStatement>(b.fOffset);
ethannicholas22f939e2016-10-13 13:25:34 -0700706 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700707 fErrors.error(b.fOffset, "break statement must be inside a loop or switch");
ethannicholas22f939e2016-10-13 13:25:34 -0700708 return nullptr;
709 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700710}
711
Ethan Nicholasfc994162019-06-06 10:04:27 -0400712std::unique_ptr<Statement> IRGenerator::convertContinue(const ASTNode& c) {
713 SkASSERT(c.fKind == ASTNode::Kind::kContinue);
ethannicholas22f939e2016-10-13 13:25:34 -0700714 if (fLoopLevel > 0) {
John Stilesb61ee902020-09-21 12:26:59 -0400715 return std::make_unique<ContinueStatement>(c.fOffset);
ethannicholas22f939e2016-10-13 13:25:34 -0700716 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700717 fErrors.error(c.fOffset, "continue statement must be inside a loop");
ethannicholas22f939e2016-10-13 13:25:34 -0700718 return nullptr;
719 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700720}
721
Ethan Nicholasfc994162019-06-06 10:04:27 -0400722std::unique_ptr<Statement> IRGenerator::convertDiscard(const ASTNode& d) {
723 SkASSERT(d.fKind == ASTNode::Kind::kDiscard);
John Stilesb61ee902020-09-21 12:26:59 -0400724 return std::make_unique<DiscardStatement>(d.fOffset);
ethannicholasb3058bd2016-07-01 08:22:01 -0700725}
726
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500727std::unique_ptr<Block> IRGenerator::applyInvocationIDWorkaround(std::unique_ptr<Block> main) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400728 Layout invokeLayout;
729 Modifiers invokeModifiers(invokeLayout, Modifiers::kHasSideEffects_Flag);
John Stilesb8cc6652020-10-08 09:12:07 -0400730 const FunctionDeclaration* invokeDecl =
Ethan Nicholased84b732020-10-08 11:45:44 -0400731 fSymbolTable->add(std::make_unique<FunctionDeclaration>(
732 /*offset=*/-1,
733 fModifiers->handle(invokeModifiers),
734 "_invoke",
Brian Osman5bf3e202020-10-13 10:34:18 -0400735 std::vector<const Variable*>(),
Ethan Nicholased84b732020-10-08 11:45:44 -0400736 fContext.fVoid_Type.get(),
John Stiles7c3515b2020-10-16 18:38:39 -0400737 fIsBuiltinCode));
John Stilesb9af7232020-08-20 15:57:48 -0400738 fProgramElements->push_back(std::make_unique<FunctionDefinition>(/*offset=*/-1,
John Stiles607d36b2020-10-19 15:00:01 -0400739 invokeDecl, fIsBuiltinCode,
John Stilesb9af7232020-08-20 15:57:48 -0400740 std::move(main)));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400741
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000742 std::vector<std::unique_ptr<VarDeclaration>> variables;
John Stilesb9af7232020-08-20 15:57:48 -0400743 const Variable* loopIdx = &(*fSymbolTable)["sk_InvocationID"]->as<Variable>();
John Stiles8e3b6be2020-10-13 11:14:08 -0400744 auto test = std::make_unique<BinaryExpression>(/*offset=*/-1,
745 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx),
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400746 Token::Kind::TK_LT,
John Stiles8e3b6be2020-10-13 11:14:08 -0400747 std::make_unique<IntLiteral>(fContext, /*offset=*/-1, fInvocations),
748 fContext.fBool_Type.get());
749 auto next = std::make_unique<PostfixExpression>(
750 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx,
751 VariableReference::RefKind::kReadWrite),
752 Token::Kind::TK_PLUSPLUS);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400753 ASTNode endPrimitiveID(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier, "EndPrimitive");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400754 std::unique_ptr<Expression> endPrimitive = this->convertExpression(endPrimitiveID);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400755 SkASSERT(endPrimitive);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400756
John Stiles8f2a0cf2020-10-13 12:48:21 -0400757 StatementArray loopBody;
John Stilesf4bda742020-10-14 16:57:41 -0400758 loopBody.reserve_back(2);
John Stiles8e3b6be2020-10-13 11:14:08 -0400759 loopBody.push_back(std::make_unique<ExpressionStatement>(this->call(
760 /*offset=*/-1, *invokeDecl,
761 ExpressionArray{})));
762 loopBody.push_back(std::make_unique<ExpressionStatement>(this->call(
763 /*offset=*/-1, std::move(endPrimitive),
764 ExpressionArray{})));
765 auto assignment = std::make_unique<BinaryExpression>(/*offset=*/-1,
766 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx,
767 VariableReference::RefKind::kWrite),
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400768 Token::Kind::TK_EQ,
John Stiles8e3b6be2020-10-13 11:14:08 -0400769 std::make_unique<IntLiteral>(fContext, /*offset=*/-1, /*value=*/0),
770 fContext.fInt_Type.get());
771 auto initializer = std::make_unique<ExpressionStatement>(std::move(assignment));
772 auto loop = std::make_unique<ForStatement>(/*offset=*/-1,
773 std::move(initializer),
774 std::move(test), std::move(next),
775 std::make_unique<Block>(-1, std::move(loopBody)),
776 fSymbolTable);
John Stiles8f2a0cf2020-10-13 12:48:21 -0400777 StatementArray children;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400778 children.push_back(std::move(loop));
John Stilesfbd050b2020-08-03 13:21:46 -0400779 return std::make_unique<Block>(-1, std::move(children));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400780}
781
Robert Phillipsfe8da172018-01-24 14:52:02 +0000782std::unique_ptr<Statement> IRGenerator::getNormalizeSkPositionCode() {
Brian Osman88cda172020-10-09 12:05:16 -0400783 const Variable* skPerVertex = nullptr;
784 if (const ProgramElement* perVertexDecl = fIntrinsics->find(Compiler::PERVERTEX_NAME)) {
785 SkASSERT(perVertexDecl->is<InterfaceBlock>());
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400786 skPerVertex = &perVertexDecl->as<InterfaceBlock>().variable();
Brian Osman88cda172020-10-09 12:05:16 -0400787 }
788
Ethan Nicholasb809efb2018-04-12 14:39:21 -0400789 // sk_Position = float4(sk_Position.xy * rtAdjust.xz + sk_Position.ww * rtAdjust.yw,
Robert Phillipsfe8da172018-01-24 14:52:02 +0000790 // 0,
791 // sk_Position.w);
Brian Osman88cda172020-10-09 12:05:16 -0400792 SkASSERT(skPerVertex && fRTAdjust);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000793 #define REF(var) std::unique_ptr<Expression>(\
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400794 new VariableReference(-1, var, VariableReference::RefKind::kRead))
Ethan Nicholas4fadce42020-07-30 13:29:30 -0400795 #define WREF(var) std::unique_ptr<Expression>(\
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400796 new VariableReference(-1, var, VariableReference::RefKind::kWrite))
Robert Phillipsfe8da172018-01-24 14:52:02 +0000797 #define FIELD(var, idx) std::unique_ptr<Expression>(\
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400798 new FieldAccess(REF(var), idx, FieldAccess::OwnerKind::kAnonymousInterfaceBlock))
Brian Osman88cda172020-10-09 12:05:16 -0400799 #define POS std::unique_ptr<Expression>(new FieldAccess(WREF(skPerVertex), 0, \
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400800 FieldAccess::OwnerKind::kAnonymousInterfaceBlock))
Robert Phillipsfe8da172018-01-24 14:52:02 +0000801 #define ADJUST (fRTAdjustInterfaceBlock ? \
802 FIELD(fRTAdjustInterfaceBlock, fRTAdjustFieldIndex) : \
803 REF(fRTAdjust))
John Stiles750109b2020-10-30 13:45:46 -0400804 #define SWIZZLE(expr, comp) std::unique_ptr<Expression>( \
805 new Swizzle(fContext, expr, ComponentArray(comp, SK_ARRAY_COUNT(comp))))
Ethan Nicholasb809efb2018-04-12 14:39:21 -0400806 #define OP(left, op, right) std::unique_ptr<Expression>( \
807 new BinaryExpression(-1, left, op, right, \
Ethan Nicholas30d30222020-09-11 12:27:26 -0400808 fContext.fFloat2_Type.get()))
John Stiles750109b2020-10-30 13:45:46 -0400809
810 static constexpr int8_t kXYIndices[] = {0, 1};
811 static constexpr int8_t kXZIndices[] = {0, 2};
812 static constexpr int8_t kYWIndices[] = {1, 3};
813 static constexpr int8_t kWWIndices[] = {3, 3};
814 static constexpr int8_t kWIndex[] = {3};
815
John Stiles8e3b6be2020-10-13 11:14:08 -0400816 ExpressionArray children;
John Stilesf4bda742020-10-14 16:57:41 -0400817 children.reserve_back(3);
John Stiles750109b2020-10-30 13:45:46 -0400818 children.push_back(
819 OP(OP(SWIZZLE(POS, kXYIndices), Token::Kind::TK_STAR, SWIZZLE(ADJUST, kXZIndices)),
820 Token::Kind::TK_PLUS,
821 OP(SWIZZLE(POS, kWWIndices), Token::Kind::TK_STAR, SWIZZLE(ADJUST, kYWIndices))));
John Stiles8e3b6be2020-10-13 11:14:08 -0400822 children.push_back(std::make_unique<FloatLiteral>(fContext, /*offset=*/-1, /*value=*/0.0));
John Stiles750109b2020-10-30 13:45:46 -0400823 children.push_back(SWIZZLE(POS, kWIndex));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400824 std::unique_ptr<Expression> result = OP(POS, Token::Kind::TK_EQ,
John Stiles8e3b6be2020-10-13 11:14:08 -0400825 std::make_unique<Constructor>(/*offset=*/-1,
826 fContext.fFloat4_Type.get(),
827 std::move(children)));
828 return std::make_unique<ExpressionStatement>(std::move(result));
Robert Phillipsfe8da172018-01-24 14:52:02 +0000829}
830
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400831template<typename T>
832class AutoClear {
833public:
834 AutoClear(T* container)
835 : fContainer(container) {
836 SkASSERT(container->empty());
837 }
838
839 ~AutoClear() {
840 fContainer->clear();
841 }
842
843private:
844 T* fContainer;
845};
846
John Stilesb8e010c2020-08-11 18:05:39 -0400847template <typename T> AutoClear(T* c) -> AutoClear<T>;
848
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400849void IRGenerator::checkModifiers(int offset, const Modifiers& modifiers, int permitted) {
850 int flags = modifiers.fFlags;
851 #define CHECK(flag, name) \
852 if (!flags) return; \
853 if (flags & flag) { \
854 if (!(permitted & flag)) { \
855 fErrors.error(offset, "'" name "' is not permitted here"); \
856 } \
857 flags &= ~flag; \
858 }
859 CHECK(Modifiers::kConst_Flag, "const")
860 CHECK(Modifiers::kIn_Flag, "in")
861 CHECK(Modifiers::kOut_Flag, "out")
862 CHECK(Modifiers::kUniform_Flag, "uniform")
863 CHECK(Modifiers::kFlat_Flag, "flat")
864 CHECK(Modifiers::kNoPerspective_Flag, "noperspective")
865 CHECK(Modifiers::kReadOnly_Flag, "readonly")
866 CHECK(Modifiers::kWriteOnly_Flag, "writeonly")
867 CHECK(Modifiers::kCoherent_Flag, "coherent")
868 CHECK(Modifiers::kVolatile_Flag, "volatile")
869 CHECK(Modifiers::kRestrict_Flag, "restrict")
870 CHECK(Modifiers::kBuffer_Flag, "buffer")
871 CHECK(Modifiers::kHasSideEffects_Flag, "sk_has_side_effects")
872 CHECK(Modifiers::kPLS_Flag, "__pixel_localEXT")
873 CHECK(Modifiers::kPLSIn_Flag, "__pixel_local_inEXT")
874 CHECK(Modifiers::kPLSOut_Flag, "__pixel_local_outEXT")
875 CHECK(Modifiers::kVarying_Flag, "varying")
Ethan Nicholasf3c8f5d2020-08-20 13:09:14 +0000876 CHECK(Modifiers::kInline_Flag, "inline")
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400877 SkASSERT(flags == 0);
878}
879
Ethan Nicholasfc994162019-06-06 10:04:27 -0400880void IRGenerator::convertFunction(const ASTNode& f) {
John Stilesb8e010c2020-08-11 18:05:39 -0400881 AutoClear clear(&fReferencedIntrinsics);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400882 auto iter = f.begin();
Brian Osmand8070392020-09-09 15:50:02 -0400883 const Type* returnType = this->convertType(*(iter++), /*allowVoid=*/true);
John Stilesb9af7232020-08-20 15:57:48 -0400884 if (returnType == nullptr) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400885 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700886 }
Brian Osman3000d6b2020-07-31 15:57:28 -0400887 auto type_is_allowed = [&](const Type* t) {
888#if defined(SKSL_STANDALONE)
889 return true;
890#else
891 GrSLType unusedSLType;
892 return fKind != Program::kPipelineStage_Kind ||
893 type_to_grsltype(fContext, *t, &unusedSLType);
894#endif
895 };
896 if (returnType->nonnullable() == *fContext.fFragmentProcessor_Type ||
897 !type_is_allowed(returnType)) {
Brian Osman82329002020-07-21 09:39:27 -0400898 fErrors.error(f.fOffset,
899 "functions may not return type '" + returnType->displayName() + "'");
900 return;
901 }
John Stilesb9af7232020-08-20 15:57:48 -0400902 const ASTNode::FunctionData& funcData = f.getFunctionData();
903 this->checkModifiers(f.fOffset, funcData.fModifiers, Modifiers::kHasSideEffects_Flag |
904 Modifiers::kInline_Flag);
Brian Osman5bf3e202020-10-13 10:34:18 -0400905 std::vector<const Variable*> parameters;
John Stilesb9af7232020-08-20 15:57:48 -0400906 for (size_t i = 0; i < funcData.fParameterCount; ++i) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400907 const ASTNode& param = *(iter++);
908 SkASSERT(param.fKind == ASTNode::Kind::kParameter);
909 ASTNode::ParameterData pd = param.getParameterData();
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400910 this->checkModifiers(param.fOffset, pd.fModifiers, Modifiers::kIn_Flag |
911 Modifiers::kOut_Flag);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400912 auto paramIter = param.begin();
913 const Type* type = this->convertType(*(paramIter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700914 if (!type) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400915 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700916 }
John Stiles7f7b4852020-11-10 11:25:35 -0500917 for (int j = 1; j <= (int) pd.fSizeCount; j++) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400918 int size = (param.begin() + j)->getInt();
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400919 String name = type->name() + "[" + to_string(size) + "]";
John Stiles3ae071e2020-08-05 15:29:29 -0400920 type = fSymbolTable->takeOwnershipOfSymbol(
Ethan Nicholase6592142020-09-08 10:22:09 -0400921 std::make_unique<Type>(std::move(name), Type::TypeKind::kArray, *type, size));
ethannicholasb3058bd2016-07-01 08:22:01 -0700922 }
Brian Osman3000d6b2020-07-31 15:57:28 -0400923 // Only the (builtin) declarations of 'sample' are allowed to have FP parameters
924 if ((type->nonnullable() == *fContext.fFragmentProcessor_Type && !fIsBuiltinCode) ||
925 !type_is_allowed(type)) {
926 fErrors.error(param.fOffset,
927 "parameters of type '" + type->displayName() + "' not allowed");
928 return;
929 }
Brian Osman8dbdf232020-10-12 14:40:24 -0400930
931 Modifiers m = pd.fModifiers;
932 if (funcData.fName == "main" && (fKind == Program::kPipelineStage_Kind ||
933 fKind == Program::kFragmentProcessor_Kind)) {
934 if (i == 0) {
935 // We verify that the type is correct later, for now, if there is a parameter to
936 // a .fp or runtime-effect main(), it's supposed to be the coords:
937 m.fLayout.fBuiltin = SK_MAIN_COORDS_BUILTIN;
938 }
939 }
940
Brian Osman5bf3e202020-10-13 10:34:18 -0400941 const Variable* var = fSymbolTable->takeOwnershipOfSymbol(
Brian Osman8dbdf232020-10-12 14:40:24 -0400942 std::make_unique<Variable>(param.fOffset, fModifiers->handle(m), pd.fName, type,
943 fIsBuiltinCode, Variable::Storage::kParameter));
ethannicholasd598f792016-07-25 10:08:54 -0700944 parameters.push_back(var);
ethannicholasb3058bd2016-07-01 08:22:01 -0700945 }
946
Brian Osman767f4442020-08-13 16:59:48 -0400947 auto paramIsCoords = [&](int idx) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400948 return parameters[idx]->type() == *fContext.fFloat2_Type &&
Brian Osman8dbdf232020-10-12 14:40:24 -0400949 parameters[idx]->modifiers().fFlags == 0 &&
950 parameters[idx]->modifiers().fLayout.fBuiltin == SK_MAIN_COORDS_BUILTIN;
Brian Osman767f4442020-08-13 16:59:48 -0400951 };
Brian Osman767f4442020-08-13 16:59:48 -0400952
John Stilesb9af7232020-08-20 15:57:48 -0400953 if (funcData.fName == "main") {
Ethan Nicholas0d997662019-04-08 09:46:01 -0400954 switch (fKind) {
955 case Program::kPipelineStage_Kind: {
Brian Osman33316412020-11-06 10:42:51 -0500956 // (half4|float4) main() -or- (half4|float4) main(float2)
957 if (*returnType != *fContext.fHalf4_Type && *returnType != *fContext.fFloat4_Type) {
958 fErrors.error(f.fOffset, "'main' must return: 'vec4', 'float4', or 'half4'");
959 return;
960 }
961 if (!(parameters.size() == 0 || (parameters.size() == 1 && paramIsCoords(0)))) {
962 fErrors.error(f.fOffset, "'main' parameters must be: (), (vec2), or (float2)");
Brian Osman767f4442020-08-13 16:59:48 -0400963 return;
964 }
965 break;
Brian Osman44820a92020-08-26 09:27:39 -0400966 }
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400967 case Program::kFragmentProcessor_Kind: {
Brian Osman44820a92020-08-26 09:27:39 -0400968 bool valid = (parameters.size() == 0) ||
969 (parameters.size() == 1 && paramIsCoords(0));
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400970 if (!valid) {
971 fErrors.error(f.fOffset, ".fp 'main' must be declared main() or main(float2)");
972 return;
973 }
974 break;
975 }
Ethan Nicholas746035a2019-04-23 13:31:09 -0400976 case Program::kGeneric_Kind:
Ethan Nicholas0d997662019-04-08 09:46:01 -0400977 break;
Ethan Nicholas0d997662019-04-08 09:46:01 -0400978 default:
979 if (parameters.size()) {
980 fErrors.error(f.fOffset, "shader 'main' must have zero parameters");
981 }
Ethan Nicholas00543112018-07-31 09:44:36 -0400982 }
983 }
984
ethannicholasb3058bd2016-07-01 08:22:01 -0700985 // find existing declaration
ethannicholasd598f792016-07-25 10:08:54 -0700986 const FunctionDeclaration* decl = nullptr;
John Stilesb9af7232020-08-20 15:57:48 -0400987 const Symbol* entry = (*fSymbolTable)[funcData.fName];
ethannicholasb3058bd2016-07-01 08:22:01 -0700988 if (entry) {
ethannicholasd598f792016-07-25 10:08:54 -0700989 std::vector<const FunctionDeclaration*> functions;
Ethan Nicholase6592142020-09-08 10:22:09 -0400990 switch (entry->kind()) {
991 case Symbol::Kind::kUnresolvedFunction:
Ethan Nicholasceb62142020-10-09 16:51:18 -0400992 functions = entry->as<UnresolvedFunction>().functions();
ethannicholasb3058bd2016-07-01 08:22:01 -0700993 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400994 case Symbol::Kind::kFunctionDeclaration:
John Stiles17c5b702020-08-18 10:40:03 -0400995 functions.push_back(&entry->as<FunctionDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -0700996 break;
997 default:
John Stilesb9af7232020-08-20 15:57:48 -0400998 fErrors.error(f.fOffset, "symbol '" + funcData.fName + "' was already defined");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400999 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001000 }
John Stilesb9af7232020-08-20 15:57:48 -04001001 for (const FunctionDeclaration* other : functions) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001002 SkASSERT(other->name() == funcData.fName);
Ethan Nicholased84b732020-10-08 11:45:44 -04001003 if (parameters.size() == other->parameters().size()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001004 bool match = true;
1005 for (size_t i = 0; i < parameters.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001006 if (parameters[i]->type() != other->parameters()[i]->type()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001007 match = false;
1008 break;
1009 }
1010 }
1011 if (match) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001012 if (*returnType != other->returnType()) {
1013 FunctionDeclaration newDecl(f.fOffset,
1014 fModifiers->handle(funcData.fModifiers),
1015 funcData.fName,
1016 parameters,
1017 returnType,
1018 fIsBuiltinCode);
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001019 fErrors.error(f.fOffset, "functions '" + newDecl.description() +
1020 "' and '" + other->description() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001021 "' differ only in return type");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001022 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001023 }
1024 decl = other;
1025 for (size_t i = 0; i < parameters.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001026 if (parameters[i]->modifiers() != other->parameters()[i]->modifiers()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001027 fErrors.error(f.fOffset, "modifiers on parameter " +
1028 to_string((uint64_t) i + 1) +
John Stilesb9af7232020-08-20 15:57:48 -04001029 " differ between declaration and definition");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001030 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001031 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001032 }
Ethan Nicholased84b732020-10-08 11:45:44 -04001033 if (other->definition() && !other->isBuiltin()) {
John Stilesb9af7232020-08-20 15:57:48 -04001034 fErrors.error(f.fOffset, "duplicate definition of " + other->description());
ethannicholasb3058bd2016-07-01 08:22:01 -07001035 }
1036 break;
1037 }
1038 }
1039 }
1040 }
1041 if (!decl) {
John Stilesb9af7232020-08-20 15:57:48 -04001042 // Conservatively assume all user-defined functions have side effects.
1043 Modifiers declModifiers = funcData.fModifiers;
1044 if (!fIsBuiltinCode) {
1045 declModifiers.fFlags |= Modifiers::kHasSideEffects_Flag;
1046 }
1047
1048 // Create a new declaration.
Ethan Nicholased84b732020-10-08 11:45:44 -04001049 decl = fSymbolTable->add(std::make_unique<FunctionDeclaration>(
1050 f.fOffset,
1051 fModifiers->handle(declModifiers),
1052 funcData.fName,
1053 parameters,
1054 returnType,
1055 fIsBuiltinCode));
ethannicholasb3058bd2016-07-01 08:22:01 -07001056 }
John Stiles569249b2020-11-03 12:18:22 -05001057 if (iter == f.end()) {
1058 // If there's no body, we've found a prototype.
1059 fProgramElements->push_back(std::make_unique<FunctionPrototype>(f.fOffset, decl,
1060 fIsBuiltinCode));
1061 } else {
1062 // Compile function body.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001063 SkASSERT(!fCurrentFunction);
ethannicholasd598f792016-07-25 10:08:54 -07001064 fCurrentFunction = decl;
John Stiles569249b2020-11-03 12:18:22 -05001065
ethannicholasd598f792016-07-25 10:08:54 -07001066 AutoSymbolTable table(this);
John Stiles569249b2020-11-03 12:18:22 -05001067 for (const Variable* param : decl->parameters()) {
1068 fSymbolTable->addWithoutOwnership(param);
ethannicholasb3058bd2016-07-01 08:22:01 -07001069 }
John Stilesb9af7232020-08-20 15:57:48 -04001070 bool needInvocationIDWorkaround = fInvocations != -1 && funcData.fName == "main" &&
Brian Osmand7e76592020-11-02 12:26:22 -05001071 fCaps && !fCaps->gsInvocationsSupport();
Ethan Nicholasfc994162019-06-06 10:04:27 -04001072 std::unique_ptr<Block> body = this->convertBlock(*iter);
ethannicholasd598f792016-07-25 10:08:54 -07001073 fCurrentFunction = nullptr;
1074 if (!body) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001075 return;
1076 }
1077 if (needInvocationIDWorkaround) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001078 body = this->applyInvocationIDWorkaround(std::move(body));
ethannicholasd598f792016-07-25 10:08:54 -07001079 }
John Stilesb9af7232020-08-20 15:57:48 -04001080 if (Program::kVertex_Kind == fKind && funcData.fName == "main" && fRTAdjust) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001081 body->children().push_back(this->getNormalizeSkPositionCode());
Robert Phillipsfe8da172018-01-24 14:52:02 +00001082 }
John Stiles607d36b2020-10-19 15:00:01 -04001083 auto result = std::make_unique<FunctionDefinition>(
1084 f.fOffset, decl, fIsBuiltinCode, std::move(body), std::move(fReferencedIntrinsics));
Ethan Nicholased84b732020-10-08 11:45:44 -04001085 decl->setDefinition(result.get());
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001086 result->setSource(&f);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001087 fProgramElements->push_back(std::move(result));
ethannicholasb3058bd2016-07-01 08:22:01 -07001088 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001089}
1090
Ethan Nicholasfc994162019-06-06 10:04:27 -04001091std::unique_ptr<InterfaceBlock> IRGenerator::convertInterfaceBlock(const ASTNode& intf) {
Brian Osman16f376f2020-09-02 12:30:59 -04001092 if (fKind != Program::kFragment_Kind &&
1093 fKind != Program::kVertex_Kind &&
1094 fKind != Program::kGeometry_Kind) {
1095 fErrors.error(intf.fOffset, "interface block is not allowed here");
1096 return nullptr;
1097 }
1098
Ethan Nicholasfc994162019-06-06 10:04:27 -04001099 SkASSERT(intf.fKind == ASTNode::Kind::kInterfaceBlock);
1100 ASTNode::InterfaceBlockData id = intf.getInterfaceBlockData();
ethannicholasb3058bd2016-07-01 08:22:01 -07001101 std::shared_ptr<SymbolTable> old = fSymbolTable;
John Stiles869cdef2020-10-30 14:24:24 -04001102 std::shared_ptr<SymbolTable> symbols;
ethannicholasb3058bd2016-07-01 08:22:01 -07001103 std::vector<Type::Field> fields;
Robert Phillipsfe8da172018-01-24 14:52:02 +00001104 bool foundRTAdjust = false;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001105 auto iter = intf.begin();
John Stiles869cdef2020-10-30 14:24:24 -04001106 {
1107 AutoSymbolTable table(this);
1108 symbols = fSymbolTable;
1109 bool haveRuntimeArray = false;
1110 for (size_t i = 0; i < id.fDeclarationCount; ++i) {
1111 StatementArray decls = this->convertVarDeclarations(*(iter++),
1112 Variable::Storage::kInterfaceBlock);
1113 if (decls.empty()) {
1114 return nullptr;
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001115 }
John Stiles869cdef2020-10-30 14:24:24 -04001116 for (const auto& decl : decls) {
1117 const VarDeclaration& vd = decl->as<VarDeclaration>();
1118 if (haveRuntimeArray) {
1119 fErrors.error(decl->fOffset,
1120 "only the last entry in an interface block may be a runtime-sized "
1121 "array");
1122 }
1123 if (&vd.var() == fRTAdjust) {
1124 foundRTAdjust = true;
1125 SkASSERT(vd.var().type() == *fContext.fFloat4_Type);
1126 fRTAdjustFieldIndex = fields.size();
1127 }
1128 fields.push_back(Type::Field(vd.var().modifiers(), vd.var().name(),
1129 &vd.var().type()));
1130 if (vd.value()) {
1131 fErrors.error(decl->fOffset,
1132 "initializers are not permitted on interface block fields");
1133 }
1134 if (vd.var().type().typeKind() == Type::TypeKind::kArray &&
1135 vd.var().type().columns() == Type::kUnsizedArray) {
1136 haveRuntimeArray = true;
1137 }
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001138 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001139 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001140 }
John Stiles3ae071e2020-08-05 15:29:29 -04001141 const Type* type =
1142 old->takeOwnershipOfSymbol(std::make_unique<Type>(intf.fOffset, id.fTypeName, fields));
John Stiles87ae34e2020-10-13 12:50:11 -04001143 ExpressionArray sizes;
John Stilesf4bda742020-10-14 16:57:41 -04001144 sizes.reserve_back(id.fSizeCount);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001145 for (size_t i = 0; i < id.fSizeCount; ++i) {
1146 const ASTNode& size = *(iter++);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001147 if (size) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001148 std::unique_ptr<Expression> converted = this->convertExpression(size);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001149 if (!converted) {
1150 return nullptr;
1151 }
Ethan Nicholase2c49992020-10-05 11:49:11 -04001152 String name = type->name();
Ethan Nicholas50afc172017-02-16 14:49:57 -05001153 int64_t count;
Ethan Nicholase6592142020-09-08 10:22:09 -04001154 if (converted->kind() == Expression::Kind::kIntLiteral) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001155 count = converted->as<IntLiteral>().value();
Ethan Nicholas50afc172017-02-16 14:49:57 -05001156 if (count <= 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001157 fErrors.error(converted->fOffset, "array size must be positive");
Ethan Nicholas66d80062019-09-09 14:50:51 -04001158 return nullptr;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001159 }
1160 name += "[" + to_string(count) + "]";
1161 } else {
Ethan Nicholas66d80062019-09-09 14:50:51 -04001162 fErrors.error(intf.fOffset, "array size must be specified");
1163 return nullptr;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001164 }
John Stiles3ae071e2020-08-05 15:29:29 -04001165 type = symbols->takeOwnershipOfSymbol(
Ethan Nicholase6592142020-09-08 10:22:09 -04001166 std::make_unique<Type>(name, Type::TypeKind::kArray, *type, (int)count));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001167 sizes.push_back(std::move(converted));
1168 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001169 String name = String(type->name()) + "[]";
Brian Osmane8c26082020-10-01 17:22:45 -04001170 type = symbols->takeOwnershipOfSymbol(std::make_unique<Type>(
1171 name, Type::TypeKind::kArray, *type, Type::kUnsizedArray));
1172 sizes.push_back(nullptr);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001173 }
1174 }
Brian Osman5bf3e202020-10-13 10:34:18 -04001175 const Variable* var = old->takeOwnershipOfSymbol(
John Stiles3ae071e2020-08-05 15:29:29 -04001176 std::make_unique<Variable>(intf.fOffset,
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001177 fModifiers->handle(id.fModifiers),
John Stiles3ae071e2020-08-05 15:29:29 -04001178 id.fInstanceName.fLength ? id.fInstanceName : id.fTypeName,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001179 type,
Brian Osman3887a012020-09-30 13:22:27 -04001180 fIsBuiltinCode,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001181 Variable::Storage::kGlobal));
Robert Phillipsfe8da172018-01-24 14:52:02 +00001182 if (foundRTAdjust) {
1183 fRTAdjustInterfaceBlock = var;
1184 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001185 if (id.fInstanceName.fLength) {
John Stilesb8cc6652020-10-08 09:12:07 -04001186 old->addWithoutOwnership(var);
ethannicholasb3058bd2016-07-01 08:22:01 -07001187 } else {
1188 for (size_t i = 0; i < fields.size(); i++) {
John Stilesb8cc6652020-10-08 09:12:07 -04001189 old->add(std::make_unique<Field>(intf.fOffset, var, (int)i));
ethannicholasb3058bd2016-07-01 08:22:01 -07001190 }
1191 }
John Stilesfbd050b2020-08-03 13:21:46 -04001192 return std::make_unique<InterfaceBlock>(intf.fOffset,
1193 var,
1194 id.fTypeName,
1195 id.fInstanceName,
1196 std::move(sizes),
1197 symbols);
ethannicholasb3058bd2016-07-01 08:22:01 -07001198}
1199
Brian Osman3e3db6c2020-08-14 09:42:12 -04001200bool IRGenerator::getConstantInt(const Expression& value, int64_t* out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001201 switch (value.kind()) {
1202 case Expression::Kind::kIntLiteral:
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001203 *out = value.as<IntLiteral>().value();
Brian Osman3e3db6c2020-08-14 09:42:12 -04001204 return true;
Ethan Nicholase6592142020-09-08 10:22:09 -04001205 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001206 const Variable& var = *value.as<VariableReference>().variable();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001207 return (var.modifiers().fFlags & Modifiers::kConst_Flag) &&
1208 var.initialValue() && this->getConstantInt(*var.initialValue(), out);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001209 }
1210 default:
Brian Osman3e3db6c2020-08-14 09:42:12 -04001211 return false;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001212 }
1213}
1214
Ethan Nicholasfc994162019-06-06 10:04:27 -04001215void IRGenerator::convertEnum(const ASTNode& e) {
Brian Osman16f376f2020-09-02 12:30:59 -04001216 if (fKind == Program::kPipelineStage_Kind) {
1217 fErrors.error(e.fOffset, "enum is not allowed here");
1218 return;
1219 }
1220
Ethan Nicholasfc994162019-06-06 10:04:27 -04001221 SkASSERT(e.fKind == ASTNode::Kind::kEnum);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001222 int64_t currentValue = 0;
1223 Layout layout;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001224 ASTNode enumType(e.fNodes, e.fOffset, ASTNode::Kind::kType,
1225 ASTNode::TypeData(e.getString(), false, false));
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001226 const Type* type = this->convertType(enumType);
1227 Modifiers modifiers(layout, Modifiers::kConst_Flag);
Brian Osman1313d1a2020-09-08 10:34:30 -04001228 std::shared_ptr<SymbolTable> oldTable = fSymbolTable;
John Stiles7c3515b2020-10-16 18:38:39 -04001229 fSymbolTable = std::make_shared<SymbolTable>(fSymbolTable, fIsBuiltinCode);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001230 for (auto iter = e.begin(); iter != e.end(); ++iter) {
1231 const ASTNode& child = *iter;
1232 SkASSERT(child.fKind == ASTNode::Kind::kEnumCase);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001233 std::unique_ptr<Expression> value;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001234 if (child.begin() != child.end()) {
1235 value = this->convertExpression(*child.begin());
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001236 if (!value) {
Brian Osman1313d1a2020-09-08 10:34:30 -04001237 fSymbolTable = oldTable;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001238 return;
1239 }
Brian Osman3e3db6c2020-08-14 09:42:12 -04001240 if (!this->getConstantInt(*value, &currentValue)) {
1241 fErrors.error(value->fOffset, "enum value must be a constant integer");
Brian Osman1313d1a2020-09-08 10:34:30 -04001242 fSymbolTable = oldTable;
Brian Osman3e3db6c2020-08-14 09:42:12 -04001243 return;
1244 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001245 }
1246 value = std::unique_ptr<Expression>(new IntLiteral(fContext, e.fOffset, currentValue));
1247 ++currentValue;
John Stilesb8cc6652020-10-08 09:12:07 -04001248 fSymbolTable->add(std::make_unique<Variable>(e.fOffset, fModifiers->handle(modifiers),
1249 child.getString(), type, fIsBuiltinCode,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001250 Variable::Storage::kGlobal, value.get()));
Brian Osman3e3db6c2020-08-14 09:42:12 -04001251 fSymbolTable->takeOwnershipOfIRNode(std::move(value));
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001252 }
Brian Osman1313d1a2020-09-08 10:34:30 -04001253 // Now we orphanize the Enum's symbol table, so that future lookups in it are strict
1254 fSymbolTable->fParent = nullptr;
John Stiles1c823672020-10-20 10:23:50 -04001255 fProgramElements->push_back(std::make_unique<Enum>(e.fOffset, e.getString(), fSymbolTable,
1256 /*isSharedWithCpp=*/fIsBuiltinCode,
1257 /*isBuiltin=*/fIsBuiltinCode));
Brian Osman1313d1a2020-09-08 10:34:30 -04001258 fSymbolTable = oldTable;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001259}
1260
Brian Osmand8070392020-09-09 15:50:02 -04001261const Type* IRGenerator::convertType(const ASTNode& type, bool allowVoid) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001262 ASTNode::TypeData td = type.getTypeData();
1263 const Symbol* result = (*fSymbolTable)[td.fName];
Brian Osmand8070392020-09-09 15:50:02 -04001264 if (result && result->is<Type>()) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001265 if (td.fIsNullable) {
John Stiles17c5b702020-08-18 10:40:03 -04001266 if (result->as<Type>() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001267 if (type.begin() != type.end()) {
1268 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be used in "
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001269 "an array");
1270 }
John Stiles3ae071e2020-08-05 15:29:29 -04001271 result = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
Ethan Nicholase2c49992020-10-05 11:49:11 -04001272 String(result->name()) + "?", Type::TypeKind::kNullable,
1273 result->as<Type>()));
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001274 } else {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001275 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be nullable");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001276 }
1277 }
Brian Osmand8070392020-09-09 15:50:02 -04001278 if (result->as<Type>() == *fContext.fVoid_Type) {
1279 if (!allowVoid) {
1280 fErrors.error(type.fOffset, "type '" + td.fName + "' not allowed in this context");
1281 return nullptr;
1282 }
1283 if (type.begin() != type.end()) {
1284 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be used in an array");
1285 return nullptr;
1286 }
1287 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001288 for (const auto& size : type) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001289 String name(result->name());
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001290 name += "[";
Ethan Nicholasfc994162019-06-06 10:04:27 -04001291 if (size) {
1292 name += to_string(size.getInt());
Ethan Nicholas50afc172017-02-16 14:49:57 -05001293 }
1294 name += "]";
Brian Osmane8c26082020-10-01 17:22:45 -04001295 result = fSymbolTable->takeOwnershipOfSymbol(
1296 std::make_unique<Type>(name, Type::TypeKind::kArray, result->as<Type>(),
1297 size ? size.getInt() : Type::kUnsizedArray));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001298 }
John Stiles17c5b702020-08-18 10:40:03 -04001299 return &result->as<Type>();
ethannicholasb3058bd2016-07-01 08:22:01 -07001300 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001301 fErrors.error(type.fOffset, "unknown type '" + td.fName + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001302 return nullptr;
1303}
1304
Ethan Nicholasfc994162019-06-06 10:04:27 -04001305std::unique_ptr<Expression> IRGenerator::convertExpression(const ASTNode& expr) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001306 switch (expr.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001307 case ASTNode::Kind::kBinary:
1308 return this->convertBinaryExpression(expr);
1309 case ASTNode::Kind::kBool:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001310 return std::unique_ptr<Expression>(new BoolLiteral(fContext, expr.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04001311 expr.getBool()));
1312 case ASTNode::Kind::kCall:
1313 return this->convertCallExpression(expr);
1314 case ASTNode::Kind::kField:
1315 return this->convertFieldExpression(expr);
1316 case ASTNode::Kind::kFloat:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001317 return std::unique_ptr<Expression>(new FloatLiteral(fContext, expr.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04001318 expr.getFloat()));
1319 case ASTNode::Kind::kIdentifier:
1320 return this->convertIdentifier(expr);
1321 case ASTNode::Kind::kIndex:
1322 return this->convertIndexExpression(expr);
1323 case ASTNode::Kind::kInt:
1324 return std::unique_ptr<Expression>(new IntLiteral(fContext, expr.fOffset,
1325 expr.getInt()));
1326 case ASTNode::Kind::kNull:
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001327 return std::unique_ptr<Expression>(new NullLiteral(fContext, expr.fOffset));
Ethan Nicholasfc994162019-06-06 10:04:27 -04001328 case ASTNode::Kind::kPostfix:
1329 return this->convertPostfixExpression(expr);
1330 case ASTNode::Kind::kPrefix:
1331 return this->convertPrefixExpression(expr);
Brian Osman6518d772020-09-10 16:50:06 -04001332 case ASTNode::Kind::kScope:
1333 return this->convertScopeExpression(expr);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001334 case ASTNode::Kind::kTernary:
1335 return this->convertTernaryExpression(expr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001336 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001337#ifdef SK_DEBUG
Ethan Nicholasfc994162019-06-06 10:04:27 -04001338 ABORT("unsupported expression: %s\n", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001339#endif
1340 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001341 }
1342}
1343
Ethan Nicholasfc994162019-06-06 10:04:27 -04001344std::unique_ptr<Expression> IRGenerator::convertIdentifier(const ASTNode& identifier) {
1345 SkASSERT(identifier.fKind == ASTNode::Kind::kIdentifier);
1346 const Symbol* result = (*fSymbolTable)[identifier.getString()];
ethannicholasb3058bd2016-07-01 08:22:01 -07001347 if (!result) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001348 fErrors.error(identifier.fOffset, "unknown identifier '" + identifier.getString() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001349 return nullptr;
1350 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001351 switch (result->kind()) {
1352 case Symbol::Kind::kFunctionDeclaration: {
ethannicholasd598f792016-07-25 10:08:54 -07001353 std::vector<const FunctionDeclaration*> f = {
John Stiles17c5b702020-08-18 10:40:03 -04001354 &result->as<FunctionDeclaration>()
ethannicholasb3058bd2016-07-01 08:22:01 -07001355 };
John Stilesfbd050b2020-08-03 13:21:46 -04001356 return std::make_unique<FunctionReference>(fContext, identifier.fOffset, f);
ethannicholasb3058bd2016-07-01 08:22:01 -07001357 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001358 case Symbol::Kind::kUnresolvedFunction: {
John Stiles17c5b702020-08-18 10:40:03 -04001359 const UnresolvedFunction* f = &result->as<UnresolvedFunction>();
Ethan Nicholasceb62142020-10-09 16:51:18 -04001360 return std::make_unique<FunctionReference>(fContext, identifier.fOffset,
1361 f->functions());
ethannicholasb3058bd2016-07-01 08:22:01 -07001362 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001363 case Symbol::Kind::kVariable: {
John Stiles17c5b702020-08-18 10:40:03 -04001364 const Variable* var = &result->as<Variable>();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001365 const Modifiers& modifiers = var->modifiers();
1366 switch (modifiers.fLayout.fBuiltin) {
Ethan Nicholascd700e92018-08-24 16:43:57 -04001367 case SK_WIDTH_BUILTIN:
1368 fInputs.fRTWidth = true;
1369 break;
1370 case SK_HEIGHT_BUILTIN:
Greg Daniele6ab9982018-08-22 13:56:32 +00001371 fInputs.fRTHeight = true;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001372 break;
1373#ifndef SKSL_STANDALONE
1374 case SK_FRAGCOORD_BUILTIN:
Brian Osman9f313b62019-10-02 12:03:11 -04001375 fInputs.fFlipY = true;
1376 if (fSettings->fFlipY &&
Brian Osmand7e76592020-11-02 12:26:22 -05001377 (!fCaps || !fCaps->fragCoordConventionsExtensionString())) {
Brian Osman9f313b62019-10-02 12:03:11 -04001378 fInputs.fRTHeight = true;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001379 }
Greg Daniele6ab9982018-08-22 13:56:32 +00001380#endif
Ethan Nicholascd700e92018-08-24 16:43:57 -04001381 }
Ethan Nicholas33c59ed2019-08-13 10:21:38 -04001382 if (fKind == Program::kFragmentProcessor_Kind &&
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001383 (modifiers.fFlags & Modifiers::kIn_Flag) &&
1384 !(modifiers.fFlags & Modifiers::kUniform_Flag) &&
1385 !modifiers.fLayout.fKey &&
1386 modifiers.fLayout.fBuiltin == -1 &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001387 var->type().nonnullable() != *fContext.fFragmentProcessor_Type &&
1388 var->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholas33c59ed2019-08-13 10:21:38 -04001389 bool valid = false;
1390 for (const auto& decl : fFile->root()) {
1391 if (decl.fKind == ASTNode::Kind::kSection) {
1392 ASTNode::SectionData section = decl.getSectionData();
1393 if (section.fName == "setData") {
1394 valid = true;
1395 break;
1396 }
1397 }
1398 }
1399 if (!valid) {
1400 fErrors.error(identifier.fOffset, "'in' variable must be either 'uniform' or "
1401 "'layout(key)', or there must be a custom "
1402 "@setData function");
1403 }
1404 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001405 // default to kRead_RefKind; this will be corrected later if the variable is written to
John Stilesfbd050b2020-08-03 13:21:46 -04001406 return std::make_unique<VariableReference>(identifier.fOffset,
Brian Osman79457ef2020-09-24 15:01:27 -04001407 var,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001408 VariableReference::RefKind::kRead);
ethannicholasb3058bd2016-07-01 08:22:01 -07001409 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001410 case Symbol::Kind::kField: {
John Stiles17c5b702020-08-18 10:40:03 -04001411 const Field* field = &result->as<Field>();
Brian Osman6a204db2020-10-08 09:29:02 -04001412 auto base = std::make_unique<VariableReference>(identifier.fOffset, &field->owner(),
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001413 VariableReference::RefKind::kRead);
Brian Osman6a204db2020-10-08 09:29:02 -04001414 return std::make_unique<FieldAccess>(std::move(base),
1415 field->fieldIndex(),
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001416 FieldAccess::OwnerKind::kAnonymousInterfaceBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -07001417 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001418 case Symbol::Kind::kType: {
John Stiles17c5b702020-08-18 10:40:03 -04001419 const Type* t = &result->as<Type>();
Ethan Nicholase6592142020-09-08 10:22:09 -04001420 return std::make_unique<TypeReference>(fContext, identifier.fOffset, t);
ethannicholasb3058bd2016-07-01 08:22:01 -07001421 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001422 case Symbol::Kind::kExternal: {
John Stiles17c5b702020-08-18 10:40:03 -04001423 const ExternalValue* r = &result->as<ExternalValue>();
John Stilesfbd050b2020-08-03 13:21:46 -04001424 return std::make_unique<ExternalValueReference>(identifier.fOffset, r);
Ethan Nicholas91164d12019-05-15 15:29:54 -04001425 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001426 default:
Ethan Nicholase6592142020-09-08 10:22:09 -04001427 ABORT("unsupported symbol type %d\n", (int) result->kind());
ethannicholasb3058bd2016-07-01 08:22:01 -07001428 }
Ethan Nicholasc0709392017-06-27 11:20:22 -04001429}
1430
Ethan Nicholasfc994162019-06-06 10:04:27 -04001431std::unique_ptr<Section> IRGenerator::convertSection(const ASTNode& s) {
Brian Osman16f376f2020-09-02 12:30:59 -04001432 if (fKind != Program::kFragmentProcessor_Kind) {
1433 fErrors.error(s.fOffset, "syntax error");
1434 return nullptr;
1435 }
1436
Ethan Nicholasfc994162019-06-06 10:04:27 -04001437 ASTNode::SectionData section = s.getSectionData();
John Stilesfbd050b2020-08-03 13:21:46 -04001438 return std::make_unique<Section>(s.fOffset, section.fName, section.fArgument,
1439 section.fText);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001440}
1441
Ethan Nicholas11d53972016-11-28 11:23:23 -05001442std::unique_ptr<Expression> IRGenerator::coerce(std::unique_ptr<Expression> expr,
ethannicholasd598f792016-07-25 10:08:54 -07001443 const Type& type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001444 if (!expr) {
1445 return nullptr;
1446 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001447 if (expr->type() == type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001448 return expr;
1449 }
1450 this->checkValid(*expr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001451 if (expr->type() == *fContext.fInvalid_Type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001452 return nullptr;
1453 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001454 if (!expr->coercionCost(type).isPossible(fSettings->fAllowNarrowingConversions)) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001455 fErrors.error(expr->fOffset, "expected '" + type.displayName() + "', but found '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04001456 expr->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001457 return nullptr;
1458 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001459 if (type.typeKind() == Type::TypeKind::kScalar) {
John Stiles8e3b6be2020-10-13 11:14:08 -04001460 ExpressionArray args;
ethannicholasb3058bd2016-07-01 08:22:01 -07001461 args.push_back(std::move(expr));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001462 std::unique_ptr<Expression> ctor;
1463 if (type == *fContext.fFloatLiteral_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001464 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
1465 "float"));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001466 } else if (type == *fContext.fIntLiteral_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001467 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
1468 "int"));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001469 } else {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001470 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
Ethan Nicholase2c49992020-10-05 11:49:11 -04001471 type.name()));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001472 }
1473 if (!ctor) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001474 printf("error, null identifier: %s\n", String(type.name()).c_str());
Ethan Nicholase1f55022019-02-05 17:17:40 -05001475 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001476 SkASSERT(ctor);
John Stiles8e3b6be2020-10-13 11:14:08 -04001477 return this->call(/*offset=*/-1, std::move(ctor), std::move(args));
ethannicholasb3058bd2016-07-01 08:22:01 -07001478 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001479 if (expr->kind() == Expression::Kind::kNullLiteral) {
1480 SkASSERT(type.typeKind() == Type::TypeKind::kNullable);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001481 return std::unique_ptr<Expression>(new NullLiteral(expr->fOffset, &type));
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001482 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001483 ExpressionArray args;
ethannicholas5961bc92016-10-12 06:39:56 -07001484 args.push_back(std::move(expr));
John Stiles8e3b6be2020-10-13 11:14:08 -04001485 return std::make_unique<Constructor>(/*offset=*/-1, &type, std::move(args));
ethannicholasb3058bd2016-07-01 08:22:01 -07001486}
1487
ethannicholasf789b382016-08-03 12:43:36 -07001488static bool is_matrix_multiply(const Type& left, const Type& right) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001489 if (left.typeKind() == Type::TypeKind::kMatrix) {
1490 return right.typeKind() == Type::TypeKind::kMatrix ||
1491 right.typeKind() == Type::TypeKind::kVector;
ethannicholasf789b382016-08-03 12:43:36 -07001492 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001493 return left.typeKind() == Type::TypeKind::kVector &&
1494 right.typeKind() == Type::TypeKind::kMatrix;
ethannicholasf789b382016-08-03 12:43:36 -07001495}
ethannicholasea4567c2016-10-17 11:24:37 -07001496
ethannicholasb3058bd2016-07-01 08:22:01 -07001497/**
1498 * Determines the operand and result types of a binary expression. Returns true if the expression is
1499 * legal, false otherwise. If false, the values of the out parameters are undefined.
1500 */
Ethan Nicholas11d53972016-11-28 11:23:23 -05001501static bool determine_binary_type(const Context& context,
Brian Osman0acb5b52020-09-02 13:45:47 -04001502 bool allowNarrowing,
Ethan Nicholas11d53972016-11-28 11:23:23 -05001503 Token::Kind op,
1504 const Type& left,
1505 const Type& right,
ethannicholasd598f792016-07-25 10:08:54 -07001506 const Type** outLeftType,
1507 const Type** outRightType,
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001508 const Type** outResultType) {
1509 bool isLogical = false;
Brian Osmanbf2163f2020-09-16 16:21:40 -04001510 bool isBitwise = false;
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001511 bool validMatrixOrVectorOp = false;
1512 bool isAssignment = Compiler::IsAssignment(op);
1513
ethannicholasb3058bd2016-07-01 08:22:01 -07001514 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001515 case Token::Kind::TK_EQ:
ethannicholasea4567c2016-10-17 11:24:37 -07001516 *outLeftType = &left;
1517 *outRightType = &left;
1518 *outResultType = &left;
Brian Osman0acb5b52020-09-02 13:45:47 -04001519 return right.canCoerceTo(left, allowNarrowing);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001520 case Token::Kind::TK_EQEQ: // fall through
Brian Osman0acb5b52020-09-02 13:45:47 -04001521 case Token::Kind::TK_NEQ: {
1522 CoercionCost rightToLeft = right.coercionCost(left),
1523 leftToRight = left.coercionCost(right);
1524 if (rightToLeft < leftToRight) {
1525 if (rightToLeft.isPossible(allowNarrowing)) {
1526 *outLeftType = &left;
1527 *outRightType = &left;
1528 *outResultType = context.fBool_Type.get();
1529 return true;
1530 }
1531 } else {
1532 if (leftToRight.isPossible(allowNarrowing)) {
1533 *outLeftType = &right;
1534 *outRightType = &right;
1535 *outResultType = context.fBool_Type.get();
1536 return true;
1537 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001538 }
Ethan Nicholas23463002018-03-28 15:16:15 -04001539 return false;
Brian Osman0acb5b52020-09-02 13:45:47 -04001540 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001541 case Token::Kind::TK_LT: // fall through
1542 case Token::Kind::TK_GT: // fall through
1543 case Token::Kind::TK_LTEQ: // fall through
1544 case Token::Kind::TK_GTEQ:
ethannicholasb3058bd2016-07-01 08:22:01 -07001545 isLogical = true;
1546 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001547 case Token::Kind::TK_LOGICALOR: // fall through
1548 case Token::Kind::TK_LOGICALAND: // fall through
1549 case Token::Kind::TK_LOGICALXOR: // fall through
1550 case Token::Kind::TK_LOGICALOREQ: // fall through
1551 case Token::Kind::TK_LOGICALANDEQ: // fall through
1552 case Token::Kind::TK_LOGICALXOREQ:
ethannicholasd598f792016-07-25 10:08:54 -07001553 *outLeftType = context.fBool_Type.get();
1554 *outRightType = context.fBool_Type.get();
1555 *outResultType = context.fBool_Type.get();
Brian Osman0acb5b52020-09-02 13:45:47 -04001556 return left.canCoerceTo(*context.fBool_Type, allowNarrowing) &&
1557 right.canCoerceTo(*context.fBool_Type, allowNarrowing);
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001558 case Token::Kind::TK_STAREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001559 case Token::Kind::TK_STAR:
ethannicholasf789b382016-08-03 12:43:36 -07001560 if (is_matrix_multiply(left, right)) {
1561 // determine final component type
Brian Osman3ed22a92020-09-17 15:10:25 -04001562 if (determine_binary_type(context, allowNarrowing, op,
Brian Osman0acb5b52020-09-02 13:45:47 -04001563 left.componentType(), right.componentType(),
1564 outLeftType, outRightType, outResultType)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001565 *outLeftType = &(*outResultType)->toCompound(context, left.columns(),
Brian Salomon23356442018-11-30 15:33:19 -05001566 left.rows());
Ethan Nicholas11d53972016-11-28 11:23:23 -05001567 *outRightType = &(*outResultType)->toCompound(context, right.columns(),
Brian Salomon23356442018-11-30 15:33:19 -05001568 right.rows());
ethannicholasf789b382016-08-03 12:43:36 -07001569 int leftColumns = left.columns();
1570 int leftRows = left.rows();
1571 int rightColumns;
1572 int rightRows;
Ethan Nicholase6592142020-09-08 10:22:09 -04001573 if (right.typeKind() == Type::TypeKind::kVector) {
ethannicholasf789b382016-08-03 12:43:36 -07001574 // matrix * vector treats the vector as a column vector, so we need to
1575 // transpose it
1576 rightColumns = right.rows();
1577 rightRows = right.columns();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001578 SkASSERT(rightColumns == 1);
ethannicholasf789b382016-08-03 12:43:36 -07001579 } else {
1580 rightColumns = right.columns();
1581 rightRows = right.rows();
1582 }
1583 if (rightColumns > 1) {
1584 *outResultType = &(*outResultType)->toCompound(context, rightColumns,
1585 leftRows);
1586 } else {
1587 // result was a column vector, transpose it back to a row
1588 *outResultType = &(*outResultType)->toCompound(context, leftRows,
1589 rightColumns);
1590 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001591 if (isAssignment && ((*outResultType)->columns() != leftColumns ||
1592 (*outResultType)->rows() != leftRows)) {
1593 return false;
1594 }
ethannicholasf789b382016-08-03 12:43:36 -07001595 return leftColumns == rightRows;
1596 } else {
1597 return false;
1598 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001599 }
ethannicholasea4567c2016-10-17 11:24:37 -07001600 validMatrixOrVectorOp = true;
1601 break;
Brian Osmanbf2163f2020-09-16 16:21:40 -04001602 case Token::Kind::TK_SHLEQ:
1603 case Token::Kind::TK_SHREQ:
1604 case Token::Kind::TK_BITWISEANDEQ:
1605 case Token::Kind::TK_BITWISEOREQ:
1606 case Token::Kind::TK_BITWISEXOREQ:
1607 case Token::Kind::TK_SHL:
1608 case Token::Kind::TK_SHR:
1609 case Token::Kind::TK_BITWISEAND:
1610 case Token::Kind::TK_BITWISEOR:
1611 case Token::Kind::TK_BITWISEXOR:
1612 isBitwise = true;
1613 validMatrixOrVectorOp = true;
1614 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001615 case Token::Kind::TK_PLUSEQ:
1616 case Token::Kind::TK_MINUSEQ:
1617 case Token::Kind::TK_SLASHEQ:
1618 case Token::Kind::TK_PERCENTEQ:
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001619 case Token::Kind::TK_PLUS:
1620 case Token::Kind::TK_MINUS:
1621 case Token::Kind::TK_SLASH:
1622 case Token::Kind::TK_PERCENT:
ethannicholasea4567c2016-10-17 11:24:37 -07001623 validMatrixOrVectorOp = true;
1624 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001625 case Token::Kind::TK_COMMA:
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001626 *outLeftType = &left;
1627 *outRightType = &right;
1628 *outResultType = &right;
1629 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001630 default:
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001631 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001632 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001633
1634 bool leftIsVectorOrMatrix = left.typeKind() == Type::TypeKind::kVector ||
1635 left.typeKind() == Type::TypeKind::kMatrix,
1636 rightIsVectorOrMatrix = right.typeKind() == Type::TypeKind::kVector ||
1637 right.typeKind() == Type::TypeKind::kMatrix;
1638
1639 if (leftIsVectorOrMatrix && validMatrixOrVectorOp &&
1640 right.typeKind() == Type::TypeKind::kScalar) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001641 if (determine_binary_type(context, allowNarrowing, op, left.componentType(), right,
1642 outLeftType, outRightType, outResultType)) {
ethannicholasd598f792016-07-25 10:08:54 -07001643 *outLeftType = &(*outLeftType)->toCompound(context, left.columns(), left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001644 if (!isLogical) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001645 *outResultType =
1646 &(*outResultType)->toCompound(context, left.columns(), left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001647 }
1648 return true;
1649 }
1650 return false;
1651 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001652
1653 if (!isAssignment && rightIsVectorOrMatrix && validMatrixOrVectorOp &&
1654 left.typeKind() == Type::TypeKind::kScalar) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001655 if (determine_binary_type(context, allowNarrowing, op, left, right.componentType(),
1656 outLeftType, outRightType, outResultType)) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001657 *outRightType = &(*outRightType)->toCompound(context, right.columns(), right.rows());
1658 if (!isLogical) {
1659 *outResultType =
1660 &(*outResultType)->toCompound(context, right.columns(), right.rows());
1661 }
1662 return true;
1663 }
1664 return false;
1665 }
1666
Brian Osman0acb5b52020-09-02 13:45:47 -04001667 CoercionCost rightToLeftCost = right.coercionCost(left);
1668 CoercionCost leftToRightCost = isAssignment ? CoercionCost::Impossible()
1669 : left.coercionCost(right);
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001670
1671 if ((left.typeKind() == Type::TypeKind::kScalar &&
1672 right.typeKind() == Type::TypeKind::kScalar) ||
1673 (leftIsVectorOrMatrix && validMatrixOrVectorOp)) {
Brian Osmanbf2163f2020-09-16 16:21:40 -04001674 if (isBitwise) {
1675 const Type& leftNumberType(leftIsVectorOrMatrix ? left.componentType() : left);
1676 const Type& rightNumberType(rightIsVectorOrMatrix ? right.componentType() : right);
1677 if (!leftNumberType.isInteger() || !rightNumberType.isInteger()) {
1678 return false;
1679 }
1680 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001681 if (rightToLeftCost.isPossible(allowNarrowing) && rightToLeftCost < leftToRightCost) {
1682 // Right-to-Left conversion is possible and cheaper
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001683 *outLeftType = &left;
1684 *outRightType = &left;
1685 *outResultType = &left;
Brian Osman0acb5b52020-09-02 13:45:47 -04001686 } else if (leftToRightCost.isPossible(allowNarrowing)) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001687 // Left-to-Right conversion is possible (and at least as cheap as Right-to-Left)
1688 *outLeftType = &right;
1689 *outRightType = &right;
1690 *outResultType = &right;
1691 } else {
1692 return false;
1693 }
1694 if (isLogical) {
1695 *outResultType = context.fBool_Type.get();
1696 }
1697 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001698 }
1699 return false;
1700}
1701
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001702static std::unique_ptr<Expression> short_circuit_boolean(const Context& context,
1703 const Expression& left,
1704 Token::Kind op,
1705 const Expression& right) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001706 SkASSERT(left.kind() == Expression::Kind::kBoolLiteral);
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001707 bool leftVal = left.as<BoolLiteral>().value();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001708 if (op == Token::Kind::TK_LOGICALAND) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001709 // (true && expr) -> (expr) and (false && expr) -> (false)
1710 return leftVal ? right.clone()
1711 : std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, false));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001712 } else if (op == Token::Kind::TK_LOGICALOR) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001713 // (true || expr) -> (true) and (false || expr) -> (expr)
1714 return leftVal ? std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, true))
1715 : right.clone();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001716 } else if (op == Token::Kind::TK_LOGICALXOR) {
Noah Lavine334d0ba2019-12-18 23:03:49 -05001717 // (true ^^ expr) -> !(expr) and (false ^^ expr) -> (expr)
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001718 return leftVal ? std::unique_ptr<Expression>(new PrefixExpression(
1719 Token::Kind::TK_LOGICALNOT,
1720 right.clone()))
Noah Lavine334d0ba2019-12-18 23:03:49 -05001721 : right.clone();
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001722 } else {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001723 return nullptr;
1724 }
1725}
1726
John Stilescf27b4f2020-11-06 11:37:05 -05001727template <typename T>
1728std::unique_ptr<Expression> IRGenerator::constantFoldVector(const Expression& left,
1729 Token::Kind op,
1730 const Expression& right) const {
1731 SkASSERT(left.type() == right.type());
1732 const Type& type = left.type();
1733
1734 // Handle boolean operations: == !=
1735 if (op == Token::Kind::TK_EQEQ || op == Token::Kind::TK_NEQ) {
1736 if (left.kind() == right.kind()) {
1737 bool result = left.compareConstant(fContext, right) ^ (op == Token::Kind::TK_NEQ);
1738 return std::make_unique<BoolLiteral>(fContext, left.fOffset, result);
1739 }
1740 return nullptr;
1741 }
1742
1743 // Handle floating-point arithmetic: + - * /
1744 const auto vectorComponentwiseFold = [&](auto foldFn) -> std::unique_ptr<Constructor> {
1745 ExpressionArray args;
1746 for (int i = 0; i < type.columns(); i++) {
1747 T value = foldFn(left.getVecComponent<T>(i), right.getVecComponent<T>(i));
1748 args.push_back(std::make_unique<Literal<T>>(fContext, left.fOffset, value));
1749 }
1750 return std::make_unique<Constructor>(left.fOffset, &type, std::move(args));
1751 };
1752
1753 const auto isVectorDivisionByZero = [&]() -> bool {
1754 for (int i = 0; i < type.columns(); i++) {
1755 if (right.getVecComponent<T>(i) == 0) {
1756 return true;
1757 }
1758 }
1759 return false;
1760 };
1761
1762 switch (op) {
1763 case Token::Kind::TK_PLUS: return vectorComponentwiseFold([](T a, T b) { return a + b; });
1764 case Token::Kind::TK_MINUS: return vectorComponentwiseFold([](T a, T b) { return a - b; });
1765 case Token::Kind::TK_STAR: return vectorComponentwiseFold([](T a, T b) { return a * b; });
1766 case Token::Kind::TK_SLASH: {
1767 if (isVectorDivisionByZero()) {
1768 fErrors.error(right.fOffset, "division by zero");
1769 return nullptr;
1770 }
1771 return vectorComponentwiseFold([](T a, T b) { return a / b; });
1772 }
1773 default:
1774 return nullptr;
1775 }
1776}
1777
ethannicholas08a92112016-11-09 13:26:45 -08001778std::unique_ptr<Expression> IRGenerator::constantFold(const Expression& left,
1779 Token::Kind op,
Ethan Nicholas86a43402017-01-19 13:32:00 -05001780 const Expression& right) const {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001781 // If the left side is a constant boolean literal, the right side does not need to be constant
1782 // for short circuit optimizations to allow the constant to be folded.
John Stiles95acbbc2020-11-04 16:23:26 -05001783 if (left.is<BoolLiteral>() && !right.isCompileTimeConstant()) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001784 return short_circuit_boolean(fContext, left, op, right);
John Stiles95acbbc2020-11-04 16:23:26 -05001785 } else if (right.is<BoolLiteral>() && !left.isCompileTimeConstant()) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001786 // There aren't side effects in SKSL within expressions, so (left OP right) is equivalent to
1787 // (right OP left) for short-circuit optimizations
1788 return short_circuit_boolean(fContext, right, op, left);
1789 }
1790
1791 // Other than the short-circuit cases above, constant folding requires both sides to be constant
Brian Osmanb6b95732020-06-30 11:44:27 -04001792 if (!left.isCompileTimeConstant() || !right.isCompileTimeConstant()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001793 return nullptr;
1794 }
ethannicholas08a92112016-11-09 13:26:45 -08001795 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
1796 // precision to calculate the results and hope the result makes sense. The plan is to move the
1797 // Skia caps into SkSL, so we have access to all of them including the precisions of the various
1798 // types, which will let us be more intelligent about this.
John Stiles95acbbc2020-11-04 16:23:26 -05001799 if (left.is<BoolLiteral>() && right.is<BoolLiteral>()) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001800 bool leftVal = left.as<BoolLiteral>().value();
1801 bool rightVal = right.as<BoolLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001802 bool result;
1803 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001804 case Token::Kind::TK_LOGICALAND: result = leftVal && rightVal; break;
1805 case Token::Kind::TK_LOGICALOR: result = leftVal || rightVal; break;
1806 case Token::Kind::TK_LOGICALXOR: result = leftVal ^ rightVal; break;
ethannicholas08a92112016-11-09 13:26:45 -08001807 default: return nullptr;
1808 }
John Stiles95acbbc2020-11-04 16:23:26 -05001809 return std::make_unique<BoolLiteral>(fContext, left.fOffset, result);
ethannicholas08a92112016-11-09 13:26:45 -08001810 }
John Stilesfbd050b2020-08-03 13:21:46 -04001811 #define RESULT(t, op) std::make_unique<t ## Literal>(fContext, left.fOffset, \
1812 leftVal op rightVal)
1813 #define URESULT(t, op) std::make_unique<t ## Literal>(fContext, left.fOffset, \
1814 (uint32_t) leftVal op \
1815 (uint32_t) rightVal)
John Stiles95acbbc2020-11-04 16:23:26 -05001816 if (left.is<IntLiteral>() && right.is<IntLiteral>()) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001817 int64_t leftVal = left.as<IntLiteral>().value();
1818 int64_t rightVal = right.as<IntLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001819 switch (op) {
Ethan Nicholas66869e92020-04-30 09:27:54 -04001820 case Token::Kind::TK_PLUS: return URESULT(Int, +);
1821 case Token::Kind::TK_MINUS: return URESULT(Int, -);
1822 case Token::Kind::TK_STAR: return URESULT(Int, *);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001823 case Token::Kind::TK_SLASH:
Ethan Nicholas66869e92020-04-30 09:27:54 -04001824 if (leftVal == std::numeric_limits<int64_t>::min() && rightVal == -1) {
1825 fErrors.error(right.fOffset, "arithmetic overflow");
1826 return nullptr;
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001827 }
Ethan Nicholas66869e92020-04-30 09:27:54 -04001828 if (!rightVal) {
1829 fErrors.error(right.fOffset, "division by zero");
1830 return nullptr;
1831 }
1832 return RESULT(Int, /);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001833 case Token::Kind::TK_PERCENT:
Ethan Nicholas66869e92020-04-30 09:27:54 -04001834 if (leftVal == std::numeric_limits<int64_t>::min() && rightVal == -1) {
1835 fErrors.error(right.fOffset, "arithmetic overflow");
1836 return nullptr;
Ethan Nicholas2503ab62017-01-05 10:44:25 -05001837 }
Ethan Nicholas66869e92020-04-30 09:27:54 -04001838 if (!rightVal) {
1839 fErrors.error(right.fOffset, "division by zero");
1840 return nullptr;
1841 }
1842 return RESULT(Int, %);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001843 case Token::Kind::TK_BITWISEAND: return RESULT(Int, &);
1844 case Token::Kind::TK_BITWISEOR: return RESULT(Int, |);
1845 case Token::Kind::TK_BITWISEXOR: return RESULT(Int, ^);
1846 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
1847 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
1848 case Token::Kind::TK_GT: return RESULT(Bool, >);
1849 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
1850 case Token::Kind::TK_LT: return RESULT(Bool, <);
1851 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
1852 case Token::Kind::TK_SHL:
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001853 if (rightVal >= 0 && rightVal <= 31) {
Ethan Nicholase4489002020-04-29 14:00:14 -04001854 return URESULT(Int, <<);
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001855 }
1856 fErrors.error(right.fOffset, "shift value out of range");
1857 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001858 case Token::Kind::TK_SHR:
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001859 if (rightVal >= 0 && rightVal <= 31) {
Ethan Nicholase4489002020-04-29 14:00:14 -04001860 return URESULT(Int, >>);
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001861 }
1862 fErrors.error(right.fOffset, "shift value out of range");
1863 return nullptr;
1864
1865 default:
1866 return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001867 }
1868 }
John Stiles95acbbc2020-11-04 16:23:26 -05001869 if (left.is<FloatLiteral>() && right.is<FloatLiteral>()) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001870 SKSL_FLOAT leftVal = left.as<FloatLiteral>().value();
1871 SKSL_FLOAT rightVal = right.as<FloatLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001872 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001873 case Token::Kind::TK_PLUS: return RESULT(Float, +);
1874 case Token::Kind::TK_MINUS: return RESULT(Float, -);
1875 case Token::Kind::TK_STAR: return RESULT(Float, *);
1876 case Token::Kind::TK_SLASH:
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001877 if (rightVal) {
1878 return RESULT(Float, /);
1879 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001880 fErrors.error(right.fOffset, "division by zero");
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001881 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001882 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
1883 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
1884 case Token::Kind::TK_GT: return RESULT(Bool, >);
1885 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
1886 case Token::Kind::TK_LT: return RESULT(Bool, <);
1887 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
1888 default: return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001889 }
1890 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001891 const Type& leftType = left.type();
1892 const Type& rightType = right.type();
John Stilescf27b4f2020-11-06 11:37:05 -05001893 if (leftType.typeKind() == Type::TypeKind::kVector && leftType == rightType) {
1894 if (leftType.componentType().isFloat()) {
1895 return constantFoldVector<SKSL_FLOAT>(left, op, right);
1896 } else if (leftType.componentType().isInteger()) {
1897 return constantFoldVector<SKSL_INT>(left, op, right);
Ethan Nicholascb670962017-04-20 19:31:52 -04001898 }
1899 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001900 if (leftType.typeKind() == Type::TypeKind::kMatrix &&
1901 rightType.typeKind() == Type::TypeKind::kMatrix &&
Ethan Nicholase6592142020-09-08 10:22:09 -04001902 left.kind() == right.kind()) {
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001903 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001904 case Token::Kind::TK_EQEQ:
John Stiles95acbbc2020-11-04 16:23:26 -05001905 return std::make_unique<BoolLiteral>(fContext, left.fOffset,
John Stiles8e3b6be2020-10-13 11:14:08 -04001906 left.compareConstant(fContext, right));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001907 case Token::Kind::TK_NEQ:
John Stiles95acbbc2020-11-04 16:23:26 -05001908 return std::make_unique<BoolLiteral>(fContext, left.fOffset,
John Stiles8e3b6be2020-10-13 11:14:08 -04001909 !left.compareConstant(fContext, right));
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001910 default:
1911 return nullptr;
1912 }
1913 }
ethannicholas08a92112016-11-09 13:26:45 -08001914 #undef RESULT
1915 return nullptr;
1916}
1917
Ethan Nicholasfc994162019-06-06 10:04:27 -04001918std::unique_ptr<Expression> IRGenerator::convertBinaryExpression(const ASTNode& expression) {
1919 SkASSERT(expression.fKind == ASTNode::Kind::kBinary);
1920 auto iter = expression.begin();
1921 std::unique_ptr<Expression> left = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07001922 if (!left) {
1923 return nullptr;
1924 }
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001925 Token::Kind op = expression.getToken().fKind;
John Stiles4c412bc2020-10-13 11:19:41 -04001926 std::unique_ptr<Expression> right;
1927 {
1928 // Can't inline the right side of a short-circuiting boolean, because our inlining
1929 // approach runs things out of order.
1930 AutoDisableInline disableInline(this, /*canInline=*/(op != Token::Kind::TK_LOGICALAND &&
1931 op != Token::Kind::TK_LOGICALOR));
1932 right = this->convertExpression(*(iter++));
1933 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001934 if (!right) {
1935 return nullptr;
1936 }
ethannicholasd598f792016-07-25 10:08:54 -07001937 const Type* leftType;
1938 const Type* rightType;
1939 const Type* resultType;
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001940 const Type* rawLeftType;
John Stilesd0e48402020-09-22 14:00:40 -04001941 if (left->is<IntLiteral>() && right->type().isInteger()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001942 rawLeftType = &right->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001943 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001944 rawLeftType = &left->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001945 }
1946 const Type* rawRightType;
John Stilesd0e48402020-09-22 14:00:40 -04001947 if (right->is<IntLiteral>() && left->type().isInteger()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001948 rawRightType = &left->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001949 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001950 rawRightType = &right->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001951 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001952 if (!determine_binary_type(fContext, fSettings->fAllowNarrowingConversions, op,
1953 *rawLeftType, *rawRightType, &leftType, &rightType, &resultType)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001954 fErrors.error(expression.fOffset, String("type mismatch: '") +
Ethan Nicholasfc994162019-06-06 10:04:27 -04001955 Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04001956 "' cannot operate on '" + left->type().displayName() +
1957 "', '" + right->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001958 return nullptr;
1959 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001960 if (Compiler::IsAssignment(op)) {
Ethan Nicholas4fadce42020-07-30 13:29:30 -04001961 if (!this->setRefKind(*left, op != Token::Kind::TK_EQ
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001962 ? VariableReference::RefKind::kReadWrite
1963 : VariableReference::RefKind::kWrite)) {
Ethan Nicholas4fadce42020-07-30 13:29:30 -04001964 return nullptr;
1965 }
ethannicholasea4567c2016-10-17 11:24:37 -07001966 }
1967 left = this->coerce(std::move(left), *leftType);
1968 right = this->coerce(std::move(right), *rightType);
1969 if (!left || !right) {
1970 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001971 }
John Stilesa008b0f2020-08-16 08:48:02 -04001972 std::unique_ptr<Expression> result = this->constantFold(*left, op, *right);
ethannicholas08a92112016-11-09 13:26:45 -08001973 if (!result) {
John Stilesd1c4dac2020-08-11 18:50:50 -04001974 result = std::make_unique<BinaryExpression>(expression.fOffset, std::move(left), op,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001975 std::move(right), resultType);
ethannicholas08a92112016-11-09 13:26:45 -08001976 }
1977 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07001978}
1979
Ethan Nicholasfc994162019-06-06 10:04:27 -04001980std::unique_ptr<Expression> IRGenerator::convertTernaryExpression(const ASTNode& node) {
1981 SkASSERT(node.fKind == ASTNode::Kind::kTernary);
1982 auto iter = node.begin();
1983 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
ethannicholasd598f792016-07-25 10:08:54 -07001984 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -07001985 if (!test) {
1986 return nullptr;
1987 }
John Stiles4c412bc2020-10-13 11:19:41 -04001988 std::unique_ptr<Expression> ifTrue;
1989 std::unique_ptr<Expression> ifFalse;
1990 {
1991 AutoDisableInline disableInline(this);
1992 ifTrue = this->convertExpression(*(iter++));
1993 if (!ifTrue) {
1994 return nullptr;
1995 }
1996 ifFalse = this->convertExpression(*(iter++));
1997 if (!ifFalse) {
1998 return nullptr;
1999 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002000 }
ethannicholasd598f792016-07-25 10:08:54 -07002001 const Type* trueType;
2002 const Type* falseType;
2003 const Type* resultType;
Brian Osman0acb5b52020-09-02 13:45:47 -04002004 if (!determine_binary_type(fContext, fSettings->fAllowNarrowingConversions,
2005 Token::Kind::TK_EQEQ, ifTrue->type(), ifFalse->type(),
2006 &trueType, &falseType, &resultType) ||
2007 trueType != falseType) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002008 fErrors.error(node.fOffset, "ternary operator result mismatch: '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002009 ifTrue->type().displayName() + "', '" +
2010 ifFalse->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002011 return nullptr;
2012 }
Brian Osman82329002020-07-21 09:39:27 -04002013 if (trueType->nonnullable() == *fContext.fFragmentProcessor_Type) {
2014 fErrors.error(node.fOffset,
2015 "ternary expression of type '" + trueType->displayName() + "' not allowed");
2016 return nullptr;
2017 }
ethannicholasd598f792016-07-25 10:08:54 -07002018 ifTrue = this->coerce(std::move(ifTrue), *trueType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05002019 if (!ifTrue) {
2020 return nullptr;
2021 }
ethannicholasd598f792016-07-25 10:08:54 -07002022 ifFalse = this->coerce(std::move(ifFalse), *falseType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05002023 if (!ifFalse) {
2024 return nullptr;
2025 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002026 if (test->kind() == Expression::Kind::kBoolLiteral) {
ethannicholas08a92112016-11-09 13:26:45 -08002027 // static boolean test, just return one of the branches
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002028 if (test->as<BoolLiteral>().value()) {
ethannicholas08a92112016-11-09 13:26:45 -08002029 return ifTrue;
2030 } else {
2031 return ifFalse;
2032 }
2033 }
John Stiles8fa3b4e2020-09-02 11:27:23 -04002034 return std::make_unique<TernaryExpression>(node.fOffset,
2035 std::move(test),
2036 std::move(ifTrue),
2037 std::move(ifFalse));
ethannicholasb3058bd2016-07-01 08:22:01 -07002038}
2039
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002040void IRGenerator::copyIntrinsicIfNeeded(const FunctionDeclaration& function) {
Brian Osman00a8b5b2020-10-02 09:06:04 -04002041 if (const ProgramElement* found = fIntrinsics->findAndInclude(function.description())) {
Brian Osman2b469eb2020-09-21 11:32:10 -04002042 const FunctionDefinition& original = found->as<FunctionDefinition>();
John Stiles9878d9e2020-09-22 15:40:16 -04002043
2044 // Sort the referenced intrinsics into a consistent order; otherwise our output will become
2045 // non-deterministic.
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002046 std::vector<const FunctionDeclaration*> intrinsics(original.referencedIntrinsics().begin(),
2047 original.referencedIntrinsics().end());
John Stiles9878d9e2020-09-22 15:40:16 -04002048 std::sort(intrinsics.begin(), intrinsics.end(),
2049 [](const FunctionDeclaration* a, const FunctionDeclaration* b) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002050 if (a->isBuiltin() != b->isBuiltin()) {
2051 return a->isBuiltin() < b->isBuiltin();
John Stiles9878d9e2020-09-22 15:40:16 -04002052 }
2053 if (a->fOffset != b->fOffset) {
2054 return a->fOffset < b->fOffset;
2055 }
Ethan Nicholase2c49992020-10-05 11:49:11 -04002056 if (a->name() != b->name()) {
2057 return a->name() < b->name();
John Stiles9878d9e2020-09-22 15:40:16 -04002058 }
2059 return a->description() < b->description();
2060 });
2061 for (const FunctionDeclaration* f : intrinsics) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002062 this->copyIntrinsicIfNeeded(*f);
2063 }
John Stiles607d36b2020-10-19 15:00:01 -04002064
John Stiles1c823672020-10-20 10:23:50 -04002065 fProgramElements->push_back(original.clone());
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002066 }
2067}
2068
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002069std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05002070 const FunctionDeclaration& function,
John Stiles8e3b6be2020-10-13 11:14:08 -04002071 ExpressionArray arguments) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002072 if (function.isBuiltin()) {
2073 if (function.definition()) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002074 fReferencedIntrinsics.insert(&function);
2075 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002076 if (!fIsBuiltinCode && fIntrinsics) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002077 this->copyIntrinsicIfNeeded(function);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05002078 }
2079 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002080 if (function.parameters().size() != arguments.size()) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002081 String msg = "call to '" + function.name() + "' expected " +
Ethan Nicholased84b732020-10-08 11:45:44 -04002082 to_string((uint64_t) function.parameters().size()) +
ethannicholasb3058bd2016-07-01 08:22:01 -07002083 " argument";
Ethan Nicholased84b732020-10-08 11:45:44 -04002084 if (function.parameters().size() != 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002085 msg += "s";
2086 }
ethannicholas5961bc92016-10-12 06:39:56 -07002087 msg += ", but found " + to_string((uint64_t) arguments.size());
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002088 fErrors.error(offset, msg);
ethannicholasb3058bd2016-07-01 08:22:01 -07002089 return nullptr;
2090 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002091 if (fKind == Program::kPipelineStage_Kind && !function.definition() && !function.isBuiltin()) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002092 String msg = "call to undefined function '" + function.name() + "'";
Brian Osman5f6b41e2020-03-09 11:53:24 -04002093 fErrors.error(offset, msg);
2094 return nullptr;
2095 }
John Stilesfa889112020-10-12 19:03:43 -04002096 FunctionDeclaration::ParamTypes types;
ethannicholas471e8942016-10-28 09:02:46 -07002097 const Type* returnType;
2098 if (!function.determineFinalTypes(arguments, &types, &returnType)) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002099 String msg = "no match for " + function.name() + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002100 String separator;
ethannicholas471e8942016-10-28 09:02:46 -07002101 for (size_t i = 0; i < arguments.size(); i++) {
2102 msg += separator;
2103 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -04002104 msg += arguments[i]->type().displayName();
ethannicholas471e8942016-10-28 09:02:46 -07002105 }
2106 msg += ")";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002107 fErrors.error(offset, msg);
ethannicholas471e8942016-10-28 09:02:46 -07002108 return nullptr;
2109 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002110 for (size_t i = 0; i < arguments.size(); i++) {
ethannicholas471e8942016-10-28 09:02:46 -07002111 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
ethannicholasea4567c2016-10-17 11:24:37 -07002112 if (!arguments[i]) {
2113 return nullptr;
2114 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002115 const Modifiers& paramModifiers = function.parameters()[i]->modifiers();
John Stiles978674a2020-09-23 15:24:51 -04002116 if (paramModifiers.fFlags & Modifiers::kOut_Flag) {
2117 if (!this->setRefKind(*arguments[i], paramModifiers.fFlags & Modifiers::kIn_Flag
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002118 ? VariableReference::RefKind::kReadWrite
2119 : VariableReference::RefKind::kPointer)) {
John Stiles978674a2020-09-23 15:24:51 -04002120 return nullptr;
2121 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002122 }
2123 }
John Stilesea9ab822020-08-31 09:55:04 -04002124
John Stiles4c412bc2020-10-13 11:19:41 -04002125 auto funcCall = std::make_unique<FunctionCall>(offset, returnType, &function,
2126 std::move(arguments));
2127 if (fCanInline &&
2128 fInliner->isSafeToInline(funcCall->function().definition()) &&
2129 !fInliner->isLargeFunction(funcCall->function().definition())) {
2130 Inliner::InlinedCall inlinedCall = fInliner->inlineCall(funcCall.get(), fSymbolTable.get(),
2131 fCurrentFunction);
2132 if (inlinedCall.fInlinedBody) {
2133 fExtraStatements.push_back(std::move(inlinedCall.fInlinedBody));
2134 }
2135 return std::move(inlinedCall.fReplacementExpr);
2136 }
2137
2138 return std::move(funcCall);
ethannicholasb3058bd2016-07-01 08:22:01 -07002139}
2140
2141/**
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002142 * Determines the cost of coercing the arguments of a function to the required types. Cost has no
Brian Osman0acb5b52020-09-02 13:45:47 -04002143 * particular meaning other than "lower costs are preferred". Returns CoercionCost::Impossible() if
2144 * the call is not valid.
ethannicholasb3058bd2016-07-01 08:22:01 -07002145 */
Brian Osman0acb5b52020-09-02 13:45:47 -04002146CoercionCost IRGenerator::callCost(const FunctionDeclaration& function,
John Stiles8e3b6be2020-10-13 11:14:08 -04002147 const ExpressionArray& arguments) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002148 if (function.parameters().size() != arguments.size()) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002149 return CoercionCost::Impossible();
ethannicholasb3058bd2016-07-01 08:22:01 -07002150 }
John Stilesfa889112020-10-12 19:03:43 -04002151 FunctionDeclaration::ParamTypes types;
ethannicholas471e8942016-10-28 09:02:46 -07002152 const Type* ignored;
2153 if (!function.determineFinalTypes(arguments, &types, &ignored)) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002154 return CoercionCost::Impossible();
ethannicholas471e8942016-10-28 09:02:46 -07002155 }
Brian Osman0acb5b52020-09-02 13:45:47 -04002156 CoercionCost total = CoercionCost::Free();
ethannicholasb3058bd2016-07-01 08:22:01 -07002157 for (size_t i = 0; i < arguments.size(); i++) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002158 total = total + arguments[i]->coercionCost(*types[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -07002159 }
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002160 return total;
ethannicholasb3058bd2016-07-01 08:22:01 -07002161}
2162
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002163std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05002164 std::unique_ptr<Expression> functionValue,
John Stiles8e3b6be2020-10-13 11:14:08 -04002165 ExpressionArray arguments) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002166 switch (functionValue->kind()) {
2167 case Expression::Kind::kTypeReference:
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002168 return this->convertConstructor(offset,
Ethan Nicholas5194a702020-10-12 11:12:12 -04002169 functionValue->as<TypeReference>().value(),
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002170 std::move(arguments));
Ethan Nicholase6592142020-09-08 10:22:09 -04002171 case Expression::Kind::kExternalValue: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002172 const ExternalValue& v = functionValue->as<ExternalValueReference>().value();
2173 if (!v.canCall()) {
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002174 fErrors.error(offset, "this external value is not a function");
2175 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002176 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002177 int count = v.callParameterCount();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002178 if (count != (int) arguments.size()) {
2179 fErrors.error(offset, "external function expected " + to_string(count) +
2180 " arguments, but found " + to_string((int) arguments.size()));
2181 return nullptr;
2182 }
2183 static constexpr int PARAMETER_MAX = 16;
2184 SkASSERT(count < PARAMETER_MAX);
2185 const Type* types[PARAMETER_MAX];
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002186 v.getCallParameterTypes(types);
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002187 for (int i = 0; i < count; ++i) {
2188 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
2189 if (!arguments[i]) {
2190 return nullptr;
2191 }
2192 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002193 return std::make_unique<ExternalFunctionCall>(offset, &v, std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07002194 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002195 case Expression::Kind::kFunctionReference: {
John Stilesce591b72020-08-27 11:47:30 -04002196 const FunctionReference& ref = functionValue->as<FunctionReference>();
Ethan Nicholas5194a702020-10-12 11:12:12 -04002197 const std::vector<const FunctionDeclaration*>& functions = ref.functions();
Brian Osman0acb5b52020-09-02 13:45:47 -04002198 CoercionCost bestCost = CoercionCost::Impossible();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002199 const FunctionDeclaration* best = nullptr;
Ethan Nicholas5194a702020-10-12 11:12:12 -04002200 if (functions.size() > 1) {
2201 for (const auto& f : functions) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002202 CoercionCost cost = this->callCost(*f, arguments);
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002203 if (cost < bestCost) {
2204 bestCost = cost;
2205 best = f;
2206 }
2207 }
2208 if (best) {
2209 return this->call(offset, *best, std::move(arguments));
2210 }
Ethan Nicholas5194a702020-10-12 11:12:12 -04002211 String msg = "no match for " + functions[0]->name() + "(";
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002212 String separator;
2213 for (size_t i = 0; i < arguments.size(); i++) {
2214 msg += separator;
2215 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -04002216 msg += arguments[i]->type().displayName();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002217 }
2218 msg += ")";
2219 fErrors.error(offset, msg);
2220 return nullptr;
2221 }
Ethan Nicholas5194a702020-10-12 11:12:12 -04002222 return this->call(offset, *functions[0], std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07002223 }
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002224 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002225 fErrors.error(offset, "not a function");
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002226 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002227 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002228}
2229
John Stiles8e3b6be2020-10-13 11:14:08 -04002230std::unique_ptr<Expression> IRGenerator::convertNumberConstructor(int offset,
2231 const Type& type,
2232 ExpressionArray args) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04002233 SkASSERT(type.isNumber());
Ethan Nicholas84645e32017-02-09 13:57:14 -05002234 if (args.size() != 1) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002235 fErrors.error(offset, "invalid arguments to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002236 "' constructor, (expected exactly 1 argument, but found " +
2237 to_string((uint64_t) args.size()) + ")");
ethannicholasb3058bd2016-07-01 08:22:01 -07002238 return nullptr;
2239 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002240 const Type& argType = args[0]->type();
2241 if (type == argType) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002242 return std::move(args[0]);
2243 }
John Stilesd0e48402020-09-22 14:00:40 -04002244 if (type.isFloat() && args.size() == 1 && args[0]->is<FloatLiteral>()) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002245 SKSL_FLOAT value = args[0]->as<FloatLiteral>().value();
John Stilesd0e48402020-09-22 14:00:40 -04002246 return std::make_unique<FloatLiteral>(offset, value, &type);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002247 }
John Stilesd0e48402020-09-22 14:00:40 -04002248 if (type.isFloat() && args.size() == 1 && args[0]->is<IntLiteral>()) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002249 int64_t value = args[0]->as<IntLiteral>().value();
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002250 return std::make_unique<FloatLiteral>(offset, (float)value, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002251 }
John Stilesd0e48402020-09-22 14:00:40 -04002252 if (args[0]->is<IntLiteral>() && (type == *fContext.fInt_Type ||
2253 type == *fContext.fUInt_Type)) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002254 return std::make_unique<IntLiteral>(offset, args[0]->as<IntLiteral>().value(), &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002255 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002256 if (argType == *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002257 std::unique_ptr<IntLiteral> zero(new IntLiteral(fContext, offset, 0));
2258 std::unique_ptr<IntLiteral> one(new IntLiteral(fContext, offset, 1));
John Stilesd0e48402020-09-22 14:00:40 -04002259 return std::make_unique<TernaryExpression>(offset, std::move(args[0]),
2260 this->coerce(std::move(one), type),
2261 this->coerce(std::move(zero), type));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002262 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002263 if (!argType.isNumber()) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002264 fErrors.error(offset, "invalid argument to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002265 "' constructor (expected a number or bool, but found '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002266 argType.displayName() + "')");
Ethan Nicholas84645e32017-02-09 13:57:14 -05002267 return nullptr;
2268 }
John Stilesd0e48402020-09-22 14:00:40 -04002269 return std::make_unique<Constructor>(offset, &type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002270}
2271
John Stiles36374402020-08-13 12:16:44 -04002272static int component_count(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002273 switch (type.typeKind()) {
2274 case Type::TypeKind::kVector:
Ethan Nicholas84645e32017-02-09 13:57:14 -05002275 return type.columns();
Ethan Nicholase6592142020-09-08 10:22:09 -04002276 case Type::TypeKind::kMatrix:
Ethan Nicholas84645e32017-02-09 13:57:14 -05002277 return type.columns() * type.rows();
2278 default:
2279 return 1;
2280 }
2281}
2282
John Stiles8e3b6be2020-10-13 11:14:08 -04002283std::unique_ptr<Expression> IRGenerator::convertCompoundConstructor(int offset,
2284 const Type& type,
2285 ExpressionArray args) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002286 SkASSERT(type.typeKind() == Type::TypeKind::kVector ||
2287 type.typeKind() == Type::TypeKind::kMatrix);
2288 if (type.typeKind() == Type::TypeKind::kMatrix && args.size() == 1 &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04002289 args[0]->type().typeKind() == Type::TypeKind::kMatrix) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002290 // matrix from matrix is always legal
Ethan Nicholas30d30222020-09-11 12:27:26 -04002291 return std::unique_ptr<Expression>(new Constructor(offset, &type, std::move(args)));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002292 }
2293 int actual = 0;
2294 int expected = type.rows() * type.columns();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002295 if (args.size() != 1 || expected != component_count(args[0]->type()) ||
2296 type.componentType().isNumber() != args[0]->type().componentType().isNumber()) {
ethannicholas5961bc92016-10-12 06:39:56 -07002297 for (size_t i = 0; i < args.size(); i++) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002298 const Type& argType = args[i]->type();
2299 if (argType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002300 if (type.componentType().isNumber() !=
Ethan Nicholas30d30222020-09-11 12:27:26 -04002301 argType.componentType().isNumber()) {
2302 fErrors.error(offset, "'" + argType.displayName() + "' is not a valid "
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002303 "parameter to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002304 "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002305 return nullptr;
2306 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002307 actual += argType.columns();
2308 } else if (argType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002309 actual += 1;
Ethan Nicholase6592142020-09-08 10:22:09 -04002310 if (type.typeKind() != Type::TypeKind::kScalar) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002311 args[i] = this->coerce(std::move(args[i]), type.componentType());
2312 if (!args[i]) {
2313 return nullptr;
2314 }
2315 }
2316 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002317 fErrors.error(offset, "'" + argType.displayName() + "' is not a valid "
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002318 "parameter to '" + type.displayName() + "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002319 return nullptr;
2320 }
2321 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05002322 if (actual != 1 && actual != expected) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002323 fErrors.error(offset, "invalid arguments to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002324 "' constructor (expected " + to_string(expected) +
2325 " scalars, but found " + to_string(actual) + ")");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002326 return nullptr;
2327 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002328 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002329 return std::unique_ptr<Expression>(new Constructor(offset, &type, std::move(args)));
ethannicholasb3058bd2016-07-01 08:22:01 -07002330}
2331
John Stiles8e3b6be2020-10-13 11:14:08 -04002332std::unique_ptr<Expression> IRGenerator::convertConstructor(int offset,
2333 const Type& type,
2334 ExpressionArray args) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002335 // FIXME: add support for structs
Ethan Nicholas30d30222020-09-11 12:27:26 -04002336 if (args.size() == 1 && args[0]->type() == type &&
Brian Osman82329002020-07-21 09:39:27 -04002337 type.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002338 // argument is already the right type, just return it
2339 return std::move(args[0]);
2340 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002341 Type::TypeKind kind = type.typeKind();
Ethan Nicholas84645e32017-02-09 13:57:14 -05002342 if (type.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002343 return this->convertNumberConstructor(offset, type, std::move(args));
Ethan Nicholase6592142020-09-08 10:22:09 -04002344 } else if (kind == Type::TypeKind::kArray) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002345 const Type& base = type.componentType();
2346 for (size_t i = 0; i < args.size(); i++) {
2347 args[i] = this->coerce(std::move(args[i]), base);
2348 if (!args[i]) {
2349 return nullptr;
2350 }
2351 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002352 return std::make_unique<Constructor>(offset, &type, std::move(args));
Ethan Nicholase6592142020-09-08 10:22:09 -04002353 } else if (kind == Type::TypeKind::kVector || kind == Type::TypeKind::kMatrix) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002354 return this->convertCompoundConstructor(offset, type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002355 } else {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002356 fErrors.error(offset, "cannot construct '" + type.displayName() + "'");
Ethan Nicholas84645e32017-02-09 13:57:14 -05002357 return nullptr;
2358 }
2359}
2360
Ethan Nicholasfc994162019-06-06 10:04:27 -04002361std::unique_ptr<Expression> IRGenerator::convertPrefixExpression(const ASTNode& expression) {
2362 SkASSERT(expression.fKind == ASTNode::Kind::kPrefix);
2363 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
ethannicholasb3058bd2016-07-01 08:22:01 -07002364 if (!base) {
2365 return nullptr;
2366 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002367 const Type& baseType = base->type();
Ethan Nicholasfc994162019-06-06 10:04:27 -04002368 switch (expression.getToken().fKind) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002369 case Token::Kind::TK_PLUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002370 if (!baseType.isNumber() && baseType.typeKind() != Type::TypeKind::kVector &&
2371 baseType != *fContext.fFloatLiteral_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002372 fErrors.error(expression.fOffset,
Ethan Nicholas30d30222020-09-11 12:27:26 -04002373 "'+' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002374 return nullptr;
2375 }
2376 return base;
John Stiles978674a2020-09-23 15:24:51 -04002377
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002378 case Token::Kind::TK_MINUS:
John Stiles978674a2020-09-23 15:24:51 -04002379 if (base->is<IntLiteral>()) {
2380 return std::make_unique<IntLiteral>(fContext, base->fOffset,
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002381 -base->as<IntLiteral>().value());
ethannicholasb3058bd2016-07-01 08:22:01 -07002382 }
John Stiles978674a2020-09-23 15:24:51 -04002383 if (base->is<FloatLiteral>()) {
2384 return std::make_unique<FloatLiteral>(fContext, base->fOffset,
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002385 -base->as<FloatLiteral>().value());
ethannicholasb3058bd2016-07-01 08:22:01 -07002386 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002387 if (!baseType.isNumber() && baseType.typeKind() != Type::TypeKind::kVector) {
Ethan Nicholase1f55022019-02-05 17:17:40 -05002388 fErrors.error(expression.fOffset,
Ethan Nicholas30d30222020-09-11 12:27:26 -04002389 "'-' cannot operate on '" + baseType.displayName() + "'");
Ethan Nicholase1f55022019-02-05 17:17:40 -05002390 return nullptr;
2391 }
John Stiles978674a2020-09-23 15:24:51 -04002392 return std::make_unique<PrefixExpression>(Token::Kind::TK_MINUS, std::move(base));
2393
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002394 case Token::Kind::TK_PLUSPLUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002395 if (!baseType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002396 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002397 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002398 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002399 return nullptr;
2400 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002401 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002402 return nullptr;
2403 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002404 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002405 case Token::Kind::TK_MINUSMINUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002406 if (!baseType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002407 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002408 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002409 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002410 return nullptr;
2411 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002412 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002413 return nullptr;
2414 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002415 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002416 case Token::Kind::TK_LOGICALNOT:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002417 if (baseType != *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002418 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002419 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002420 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002421 return nullptr;
2422 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002423 if (base->kind() == Expression::Kind::kBoolLiteral) {
John Stiles978674a2020-09-23 15:24:51 -04002424 return std::make_unique<BoolLiteral>(fContext, base->fOffset,
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002425 !base->as<BoolLiteral>().value());
ethannicholas08a92112016-11-09 13:26:45 -08002426 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002427 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002428 case Token::Kind::TK_BITWISENOT:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002429 if (baseType != *fContext.fInt_Type && baseType != *fContext.fUInt_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002430 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002431 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002432 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholas5961bc92016-10-12 06:39:56 -07002433 return nullptr;
2434 }
2435 break;
Ethan Nicholas11d53972016-11-28 11:23:23 -05002436 default:
ethannicholasb3058bd2016-07-01 08:22:01 -07002437 ABORT("unsupported prefix operator\n");
2438 }
John Stiles978674a2020-09-23 15:24:51 -04002439 return std::make_unique<PrefixExpression>(expression.getToken().fKind, std::move(base));
ethannicholasb3058bd2016-07-01 08:22:01 -07002440}
2441
2442std::unique_ptr<Expression> IRGenerator::convertIndex(std::unique_ptr<Expression> base,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002443 const ASTNode& index) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002444 if (base->kind() == Expression::Kind::kTypeReference) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002445 if (index.fKind == ASTNode::Kind::kInt) {
Ethan Nicholas5194a702020-10-12 11:12:12 -04002446 const Type& oldType = base->as<TypeReference>().value();
Ethan Nicholasfc994162019-06-06 10:04:27 -04002447 SKSL_INT size = index.getInt();
John Stiles3ae071e2020-08-05 15:29:29 -04002448 const Type* newType = fSymbolTable->takeOwnershipOfSymbol(
2449 std::make_unique<Type>(oldType.name() + "[" + to_string(size) + "]",
Ethan Nicholase6592142020-09-08 10:22:09 -04002450 Type::TypeKind::kArray, oldType, size));
2451 return std::make_unique<TypeReference>(fContext, base->fOffset, newType);
Ethan Nicholas50afc172017-02-16 14:49:57 -05002452
2453 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002454 fErrors.error(base->fOffset, "array size must be a constant");
Ethan Nicholas50afc172017-02-16 14:49:57 -05002455 return nullptr;
2456 }
2457 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002458 const Type& baseType = base->type();
2459 if (baseType.typeKind() != Type::TypeKind::kArray &&
2460 baseType.typeKind() != Type::TypeKind::kMatrix &&
2461 baseType.typeKind() != Type::TypeKind::kVector) {
2462 fErrors.error(base->fOffset, "expected array, but found '" + baseType.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002463 "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002464 return nullptr;
2465 }
2466 std::unique_ptr<Expression> converted = this->convertExpression(index);
2467 if (!converted) {
2468 return nullptr;
2469 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002470 if (converted->type() != *fContext.fUInt_Type) {
ethannicholas5961bc92016-10-12 06:39:56 -07002471 converted = this->coerce(std::move(converted), *fContext.fInt_Type);
2472 if (!converted) {
2473 return nullptr;
2474 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002475 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002476 return std::make_unique<IndexExpression>(fContext, std::move(base), std::move(converted));
ethannicholasb3058bd2016-07-01 08:22:01 -07002477}
2478
2479std::unique_ptr<Expression> IRGenerator::convertField(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002480 StringFragment field) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002481 if (base->kind() == Expression::Kind::kExternalValue) {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002482 const ExternalValue& ev = base->as<ExternalValueReference>().value();
Ethan Nicholas91164d12019-05-15 15:29:54 -04002483 ExternalValue* result = ev.getChild(String(field).c_str());
2484 if (!result) {
2485 fErrors.error(base->fOffset, "external value does not have a child named '" + field +
2486 "'");
2487 return nullptr;
2488 }
2489 return std::unique_ptr<Expression>(new ExternalValueReference(base->fOffset, result));
2490 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002491 const Type& baseType = base->type();
2492 auto fields = baseType.fields();
ethannicholasb3058bd2016-07-01 08:22:01 -07002493 for (size_t i = 0; i < fields.size(); i++) {
2494 if (fields[i].fName == field) {
2495 return std::unique_ptr<Expression>(new FieldAccess(std::move(base), (int) i));
2496 }
2497 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002498 fErrors.error(base->fOffset, "type '" + baseType.displayName() + "' does not have a field "
John Stiles68861e32020-09-25 16:02:07 -04002499 "named '" + field + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002500 return nullptr;
2501}
2502
Brian Osman25647672020-09-15 15:16:56 -04002503// Swizzles are complicated due to constant components. The most difficult case is a mask like
John Stiles6e49a372020-09-16 13:40:54 -04002504// '.x1w0'. A naive approach might turn that into 'float4(base.x, 1, base.w, 0)', but that evaluates
2505// 'base' twice. We instead group the swizzle mask ('xw') and constants ('1, 0') together and use a
Brian Osman25647672020-09-15 15:16:56 -04002506// 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 -04002507// 'float4(base.xw, 1, 0).xzyw'.
ethannicholasb3058bd2016-07-01 08:22:01 -07002508std::unique_ptr<Expression> IRGenerator::convertSwizzle(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002509 StringFragment fields) {
Brian Osman25647672020-09-15 15:16:56 -04002510 const int offset = base->fOffset;
Ethan Nicholas30d30222020-09-11 12:27:26 -04002511 const Type& baseType = base->type();
2512 if (baseType.typeKind() != Type::TypeKind::kVector && !baseType.isNumber()) {
Brian Osman25647672020-09-15 15:16:56 -04002513 fErrors.error(offset, "cannot swizzle value of type '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002514 return nullptr;
2515 }
Brian Osman25647672020-09-15 15:16:56 -04002516
2517 if (fields.fLength > 4) {
2518 fErrors.error(offset, "too many components in swizzle mask '" + fields + "'");
2519 return nullptr;
2520 }
2521
John Stiles750109b2020-10-30 13:45:46 -04002522 ComponentArray maskComponents;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002523 for (size_t i = 0; i < fields.fLength; i++) {
Ethan Nicholas9e1138d2016-11-21 10:39:35 -05002524 switch (fields[i]) {
Ethan Nicholasac285b12019-02-12 16:05:18 -05002525 case '0':
Ethan Nicholasac285b12019-02-12 16:05:18 -05002526 case '1':
John Stiles6e49a372020-09-16 13:40:54 -04002527 // Skip over constant fields for now.
Ethan Nicholasac285b12019-02-12 16:05:18 -05002528 break;
Ethan Nicholase455f652019-09-13 12:52:55 -04002529 case 'x':
2530 case 'r':
Ethan Nicholas11d53972016-11-28 11:23:23 -05002531 case 's':
Ethan Nicholase455f652019-09-13 12:52:55 -04002532 case 'L':
Brian Osman25647672020-09-15 15:16:56 -04002533 maskComponents.push_back(0);
ethannicholasb3058bd2016-07-01 08:22:01 -07002534 break;
Ethan Nicholase455f652019-09-13 12:52:55 -04002535 case 'y':
2536 case 'g':
ethannicholasb3058bd2016-07-01 08:22:01 -07002537 case 't':
Ethan Nicholase455f652019-09-13 12:52:55 -04002538 case 'T':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002539 if (baseType.columns() >= 2) {
Brian Osman25647672020-09-15 15:16:56 -04002540 maskComponents.push_back(1);
ethannicholasb3058bd2016-07-01 08:22:01 -07002541 break;
2542 }
John Stiles30212b72020-06-11 17:55:07 -04002543 [[fallthrough]];
Ethan Nicholase455f652019-09-13 12:52:55 -04002544 case 'z':
2545 case 'b':
Ethan Nicholas11d53972016-11-28 11:23:23 -05002546 case 'p':
Ethan Nicholase455f652019-09-13 12:52:55 -04002547 case 'R':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002548 if (baseType.columns() >= 3) {
Brian Osman25647672020-09-15 15:16:56 -04002549 maskComponents.push_back(2);
ethannicholasb3058bd2016-07-01 08:22:01 -07002550 break;
2551 }
John Stiles30212b72020-06-11 17:55:07 -04002552 [[fallthrough]];
Ethan Nicholase455f652019-09-13 12:52:55 -04002553 case 'w':
2554 case 'a':
ethannicholasb3058bd2016-07-01 08:22:01 -07002555 case 'q':
Ethan Nicholase455f652019-09-13 12:52:55 -04002556 case 'B':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002557 if (baseType.columns() >= 4) {
Brian Osman25647672020-09-15 15:16:56 -04002558 maskComponents.push_back(3);
ethannicholasb3058bd2016-07-01 08:22:01 -07002559 break;
2560 }
John Stiles30212b72020-06-11 17:55:07 -04002561 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -07002562 default:
Brian Osman25647672020-09-15 15:16:56 -04002563 fErrors.error(offset, String::printf("invalid swizzle component '%c'", fields[i]));
ethannicholasb3058bd2016-07-01 08:22:01 -07002564 return nullptr;
2565 }
2566 }
Brian Osman25647672020-09-15 15:16:56 -04002567 if (maskComponents.empty()) {
2568 fErrors.error(offset, "swizzle must refer to base expression");
ethannicholasb3058bd2016-07-01 08:22:01 -07002569 return nullptr;
2570 }
Brian Osman25647672020-09-15 15:16:56 -04002571
2572 // First, we need a vector expression that is the non-constant portion of the swizzle, packed:
2573 // scalar.xxx -> type3(scalar)
2574 // scalar.x0x0 -> type2(scalar)
2575 // vector.zyx -> vector.zyx
2576 // vector.x0y0 -> vector.xy
2577 std::unique_ptr<Expression> expr;
Ethan Nicholas30d30222020-09-11 12:27:26 -04002578 if (baseType.isNumber()) {
John Stiles8e3b6be2020-10-13 11:14:08 -04002579 ExpressionArray scalarConstructorArgs;
Brian Osman25647672020-09-15 15:16:56 -04002580 scalarConstructorArgs.push_back(std::move(base));
2581 expr = std::make_unique<Constructor>(
2582 offset, &baseType.toCompound(fContext, maskComponents.size(), 1),
2583 std::move(scalarConstructorArgs));
2584 } else {
2585 expr = std::make_unique<Swizzle>(fContext, std::move(base), maskComponents);
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002586 }
Brian Osman25647672020-09-15 15:16:56 -04002587
John Stiles6e49a372020-09-16 13:40:54 -04002588 // If we have processed the entire swizzle, we're done.
2589 if (maskComponents.size() == fields.fLength) {
Brian Osman25647672020-09-15 15:16:56 -04002590 return expr;
2591 }
2592
2593 // Now we create a constructor that has the correct number of elements for the final swizzle,
John Stiles6e49a372020-09-16 13:40:54 -04002594 // with all fields at the start. It's not finished yet; constants we need will be added below.
2595 // scalar.x0x0 -> type4(type2(x), ...)
2596 // vector.y111 -> type4(vector.y, ...)
2597 // vector.z10x -> type4(vector.zx, ...)
Brian Osman25647672020-09-15 15:16:56 -04002598 //
John Stiles6e49a372020-09-16 13:40:54 -04002599 // We could create simpler IR in some cases by reordering here, if all fields are packed
Brian Osman25647672020-09-15 15:16:56 -04002600 // contiguously. The benefits are minor, so skip the optimization to keep the algorithm simple.
John Stiles6e49a372020-09-16 13:40:54 -04002601 // The constructor will have at most three arguments: { base value, constant 0, constant 1 }
John Stiles8e3b6be2020-10-13 11:14:08 -04002602 ExpressionArray constructorArgs;
John Stilesf4bda742020-10-14 16:57:41 -04002603 constructorArgs.reserve_back(3);
Brian Osman25647672020-09-15 15:16:56 -04002604 constructorArgs.push_back(std::move(expr));
John Stiles6e49a372020-09-16 13:40:54 -04002605
2606 // Apply another swizzle to shuffle the constants into the correct place. Any constant values we
2607 // need are also tacked on to the end of the constructor.
2608 // scalar.x0x0 -> type4(type2(x), 0).xyxy
2609 // vector.y111 -> type4(vector.y, 1).xyyy
2610 // vector.z10x -> type4(vector.zx, 1, 0).xzwy
Brian Osman25647672020-09-15 15:16:56 -04002611 const Type* numberType = baseType.isNumber() ? &baseType : &baseType.componentType();
John Stiles750109b2020-10-30 13:45:46 -04002612 ComponentArray swizzleComponents;
John Stiles6e49a372020-09-16 13:40:54 -04002613 int maskFieldIdx = 0;
2614 int constantFieldIdx = maskComponents.size();
2615 int constantZeroIdx = -1, constantOneIdx = -1;
Brian Osman25647672020-09-15 15:16:56 -04002616
Brian Osman25647672020-09-15 15:16:56 -04002617 for (size_t i = 0; i < fields.fLength; i++) {
John Stiles6e49a372020-09-16 13:40:54 -04002618 switch (fields[i]) {
2619 case '0':
2620 if (constantZeroIdx == -1) {
John Stilesd0e48402020-09-22 14:00:40 -04002621 // Synthesize a 'type(0)' argument at the end of the constructor.
John Stiles8e3b6be2020-10-13 11:14:08 -04002622 auto zero = std::make_unique<Constructor>(offset, numberType,
2623 ExpressionArray{});
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002624 zero->arguments().push_back(std::make_unique<IntLiteral>(fContext, offset,
2625 /*fValue=*/0));
John Stilesd0e48402020-09-22 14:00:40 -04002626 constructorArgs.push_back(std::move(zero));
John Stiles6e49a372020-09-16 13:40:54 -04002627 constantZeroIdx = constantFieldIdx++;
2628 }
2629 swizzleComponents.push_back(constantZeroIdx);
2630 break;
2631 case '1':
2632 if (constantOneIdx == -1) {
John Stilesd0e48402020-09-22 14:00:40 -04002633 // Synthesize a 'type(1)' argument at the end of the constructor.
John Stiles8e3b6be2020-10-13 11:14:08 -04002634 auto one = std::make_unique<Constructor>(offset, numberType, ExpressionArray{});
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002635 one->arguments().push_back(std::make_unique<IntLiteral>(fContext, offset,
2636 /*fValue=*/1));
John Stilesd0e48402020-09-22 14:00:40 -04002637 constructorArgs.push_back(std::move(one));
John Stiles6e49a372020-09-16 13:40:54 -04002638 constantOneIdx = constantFieldIdx++;
2639 }
2640 swizzleComponents.push_back(constantOneIdx);
2641 break;
2642 default:
2643 // The non-constant fields are already in the expected order.
2644 swizzleComponents.push_back(maskFieldIdx++);
2645 break;
Brian Osman25647672020-09-15 15:16:56 -04002646 }
2647 }
2648
John Stiles6e49a372020-09-16 13:40:54 -04002649 expr = std::make_unique<Constructor>(offset,
2650 &numberType->toCompound(fContext, constantFieldIdx, 1),
2651 std::move(constructorArgs));
2652
John Stilesb23ea382020-09-16 13:41:14 -04002653 // For some of our most common use cases ('.xyz0', '.xyz1'), we will now have an identity
2654 // swizzle; in those cases we can just return the constructor without the swizzle attached.
2655 for (size_t i = 0; i < swizzleComponents.size(); ++i) {
2656 if (swizzleComponents[i] != int(i)) {
2657 // The swizzle has an effect, so apply it.
John Stiles750109b2020-10-30 13:45:46 -04002658 return std::make_unique<Swizzle>(fContext, std::move(expr), swizzleComponents);
John Stilesb23ea382020-09-16 13:41:14 -04002659 }
2660 }
2661
2662 // The swizzle was a no-op; return the constructor expression directly.
2663 return expr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002664}
2665
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002666const Type* IRGenerator::typeForSetting(int offset, String name) const {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002667 auto found = fCapsMap.find(name);
2668 if (found == fCapsMap.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002669 fErrors.error(offset, "unknown capability flag '" + name + "'");
Ethan Nicholas3605ace2016-11-21 15:59:48 -05002670 return nullptr;
2671 }
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002672 switch (found->second.fKind) {
2673 case Program::Settings::Value::kBool_Kind: return fContext.fBool_Type.get();
2674 case Program::Settings::Value::kFloat_Kind: return fContext.fFloat_Type.get();
2675 case Program::Settings::Value::kInt_Kind: return fContext.fInt_Type.get();
2676 }
2677 SkUNREACHABLE;
2678 return nullptr;
2679}
2680
2681std::unique_ptr<Expression> IRGenerator::valueForSetting(int offset, String name) const {
2682 auto found = fCapsMap.find(name);
2683 if (found == fCapsMap.end()) {
2684 fErrors.error(offset, "unknown capability flag '" + name + "'");
2685 return nullptr;
2686 }
2687 return found->second.literal(fContext, offset);
Ethan Nicholas762466e2017-06-29 10:03:38 -04002688}
2689
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002690std::unique_ptr<Expression> IRGenerator::convertTypeField(int offset, const Type& type,
2691 StringFragment field) {
Brian Osman1313d1a2020-09-08 10:34:30 -04002692 // Find the Enum element that this type refers to (if any)
Brian Osman2b469eb2020-09-21 11:32:10 -04002693 const ProgramElement* enumElement = nullptr;
2694 for (const auto& e : *fProgramElements) {
Ethan Nicholasd83ded82020-09-29 17:05:54 -04002695 if (e->is<Enum>() && type.name() == e->as<Enum>().typeName()) {
Brian Osman2b469eb2020-09-21 11:32:10 -04002696 enumElement = e.get();
2697 break;
Brian Osman1313d1a2020-09-08 10:34:30 -04002698 }
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002699 }
Brian Osman1313d1a2020-09-08 10:34:30 -04002700
2701 if (enumElement) {
2702 // We found the Enum element. Look for 'field' as a member.
2703 std::shared_ptr<SymbolTable> old = fSymbolTable;
Ethan Nicholasd83ded82020-09-29 17:05:54 -04002704 fSymbolTable = enumElement->as<Enum>().symbols();
Brian Osman1313d1a2020-09-08 10:34:30 -04002705 std::unique_ptr<Expression> result = convertIdentifier(
2706 ASTNode(&fFile->fNodes, offset, ASTNode::Kind::kIdentifier, field));
2707 if (result) {
Ethan Nicholas78686922020-10-08 06:46:27 -04002708 const Variable& v = *result->as<VariableReference>().variable();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002709 SkASSERT(v.initialValue());
Brian Osman1313d1a2020-09-08 10:34:30 -04002710 result = std::make_unique<IntLiteral>(
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002711 offset, v.initialValue()->as<IntLiteral>().value(), &type);
Brian Osman1313d1a2020-09-08 10:34:30 -04002712 } else {
2713 fErrors.error(offset,
Ethan Nicholase2c49992020-10-05 11:49:11 -04002714 "type '" + type.name() + "' does not have a member named '" + field +
2715 "'");
Brian Osman1313d1a2020-09-08 10:34:30 -04002716 }
2717 fSymbolTable = old;
2718 return result;
2719 } else {
2720 // No Enum element? Check the intrinsics, clone it into the program, try again.
Brian Osman00a8b5b2020-10-02 09:06:04 -04002721 if (!fIsBuiltinCode && fIntrinsics) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002722 if (const ProgramElement* found = fIntrinsics->findAndInclude(type.name())) {
Brian Osman00a8b5b2020-10-02 09:06:04 -04002723 fProgramElements->push_back(found->clone());
2724 return this->convertTypeField(offset, type, field);
2725 }
Ethan Nicholasdb80f692019-11-22 14:06:12 -05002726 }
Brian Osman1313d1a2020-09-08 10:34:30 -04002727 fErrors.error(offset,
Ethan Nicholase2c49992020-10-05 11:49:11 -04002728 "type '" + type.displayName() + "' does not have a member named '" + field +
2729 "'");
Brian Osman1313d1a2020-09-08 10:34:30 -04002730 return nullptr;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002731 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002732}
2733
Ethan Nicholasfc994162019-06-06 10:04:27 -04002734std::unique_ptr<Expression> IRGenerator::convertIndexExpression(const ASTNode& index) {
2735 SkASSERT(index.fKind == ASTNode::Kind::kIndex);
2736 auto iter = index.begin();
2737 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07002738 if (!base) {
2739 return nullptr;
2740 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002741 if (iter != index.end()) {
2742 return this->convertIndex(std::move(base), *(iter++));
Ethan Nicholase6592142020-09-08 10:22:09 -04002743 } else if (base->kind() == Expression::Kind::kTypeReference) {
Ethan Nicholas5194a702020-10-12 11:12:12 -04002744 const Type& oldType = base->as<TypeReference>().value();
John Stiles3ae071e2020-08-05 15:29:29 -04002745 const Type* newType = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
Brian Osmane8c26082020-10-01 17:22:45 -04002746 oldType.name() + "[]", Type::TypeKind::kArray, oldType, Type::kUnsizedArray));
Ethan Nicholase6592142020-09-08 10:22:09 -04002747 return std::make_unique<TypeReference>(fContext, base->fOffset, newType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002748 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002749 fErrors.error(index.fOffset, "'[]' must follow a type name");
2750 return nullptr;
2751}
2752
2753std::unique_ptr<Expression> IRGenerator::convertCallExpression(const ASTNode& callNode) {
2754 SkASSERT(callNode.fKind == ASTNode::Kind::kCall);
2755 auto iter = callNode.begin();
2756 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
2757 if (!base) {
2758 return nullptr;
2759 }
John Stiles8e3b6be2020-10-13 11:14:08 -04002760 ExpressionArray arguments;
Ethan Nicholasfc994162019-06-06 10:04:27 -04002761 for (; iter != callNode.end(); ++iter) {
2762 std::unique_ptr<Expression> converted = this->convertExpression(*iter);
2763 if (!converted) {
2764 return nullptr;
2765 }
2766 arguments.push_back(std::move(converted));
2767 }
2768 return this->call(callNode.fOffset, std::move(base), std::move(arguments));
2769}
2770
2771std::unique_ptr<Expression> IRGenerator::convertFieldExpression(const ASTNode& fieldNode) {
2772 std::unique_ptr<Expression> base = this->convertExpression(*fieldNode.begin());
2773 if (!base) {
2774 return nullptr;
2775 }
2776 StringFragment field = fieldNode.getString();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002777 const Type& baseType = base->type();
2778 if (baseType == *fContext.fSkCaps_Type) {
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002779 const Type* type = this->typeForSetting(fieldNode.fOffset, field);
2780 if (!type) {
2781 return nullptr;
2782 }
2783 return std::make_unique<Setting>(fieldNode.fOffset, field, type);
Ethan Nicholasfc994162019-06-06 10:04:27 -04002784 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002785 if (base->kind() == Expression::Kind::kExternalValue) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002786 return this->convertField(std::move(base), field);
2787 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002788 switch (baseType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002789 case Type::TypeKind::kOther:
2790 case Type::TypeKind::kStruct:
Ethan Nicholasfc994162019-06-06 10:04:27 -04002791 return this->convertField(std::move(base), field);
2792 default:
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002793 return this->convertSwizzle(std::move(base), field);
Ethan Nicholasfc994162019-06-06 10:04:27 -04002794 }
2795}
2796
Brian Osman6518d772020-09-10 16:50:06 -04002797std::unique_ptr<Expression> IRGenerator::convertScopeExpression(const ASTNode& scopeNode) {
2798 std::unique_ptr<Expression> base = this->convertExpression(*scopeNode.begin());
2799 if (!base) {
2800 return nullptr;
2801 }
2802 if (!base->is<TypeReference>()) {
2803 fErrors.error(scopeNode.fOffset, "'::' must follow a type name");
2804 return nullptr;
2805 }
2806 StringFragment member = scopeNode.getString();
Ethan Nicholas5194a702020-10-12 11:12:12 -04002807 return this->convertTypeField(base->fOffset, base->as<TypeReference>().value(), member);
Brian Osman6518d772020-09-10 16:50:06 -04002808}
2809
Ethan Nicholasfc994162019-06-06 10:04:27 -04002810std::unique_ptr<Expression> IRGenerator::convertPostfixExpression(const ASTNode& expression) {
2811 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
2812 if (!base) {
2813 return nullptr;
2814 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002815 const Type& baseType = base->type();
2816 if (!baseType.isNumber()) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002817 fErrors.error(expression.fOffset,
2818 "'" + String(Compiler::OperatorName(expression.getToken().fKind)) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002819 "' cannot operate on '" + baseType.displayName() + "'");
Ethan Nicholasfc994162019-06-06 10:04:27 -04002820 return nullptr;
2821 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002822 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002823 return nullptr;
2824 }
2825 return std::make_unique<PostfixExpression>(std::move(base), expression.getToken().fKind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002826}
2827
2828void IRGenerator::checkValid(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002829 switch (expr.kind()) {
2830 case Expression::Kind::kFunctionReference:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002831 fErrors.error(expr.fOffset, "expected '(' to begin function call");
ethannicholasb3058bd2016-07-01 08:22:01 -07002832 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002833 case Expression::Kind::kTypeReference:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002834 fErrors.error(expr.fOffset, "expected '(' to begin constructor invocation");
ethannicholasb3058bd2016-07-01 08:22:01 -07002835 break;
2836 default:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002837 if (expr.type() == *fContext.fInvalid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002838 fErrors.error(expr.fOffset, "invalid expression");
ethannicholasea4567c2016-10-17 11:24:37 -07002839 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002840 }
2841}
2842
John Stilesdce4d3e2020-09-25 14:35:13 -04002843bool IRGenerator::setRefKind(Expression& expr, VariableReference::RefKind kind) {
John Stilesa976da72020-09-25 23:06:26 -04002844 VariableReference* assignableVar = nullptr;
2845 if (!Analysis::IsAssignable(expr, &assignableVar, &fErrors)) {
John Stilesdce4d3e2020-09-25 14:35:13 -04002846 return false;
2847 }
John Stilesa976da72020-09-25 23:06:26 -04002848 if (assignableVar) {
2849 assignableVar->setRefKind(kind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002850 }
Ethan Nicholascb0f4092019-04-19 11:26:50 -04002851 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07002852}
2853
Brian Osman8e2ef022020-09-30 13:26:43 -04002854void IRGenerator::cloneBuiltinVariables() {
2855 class BuiltinVariableRemapper : public ProgramWriter {
2856 public:
2857 BuiltinVariableRemapper(IRGenerator* generator) : fGenerator(generator) {}
2858
Brian Osman00a8b5b2020-10-02 09:06:04 -04002859 void cloneVariable(const String& name) {
2860 // If this is the *first* time we've seen this builtin, findAndInclude will return
2861 // the corresponding ProgramElement.
Brian Osmanafa18ee2020-10-07 17:47:45 -04002862 if (const ProgramElement* sharedDecl = fGenerator->fIntrinsics->findAndInclude(name)) {
2863 SkASSERT(sharedDecl->is<GlobalVarDeclaration>() ||
2864 sharedDecl->is<InterfaceBlock>());
Brian Osman00a8b5b2020-10-02 09:06:04 -04002865
Brian Osmanafa18ee2020-10-07 17:47:45 -04002866 // Clone the ProgramElement that declares this variable
2867 std::unique_ptr<ProgramElement> clonedDecl = sharedDecl->clone();
2868 const Variable* sharedVar = nullptr;
2869 const Expression* initialValue = nullptr;
2870
2871 if (clonedDecl->is<GlobalVarDeclaration>()) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002872 GlobalVarDeclaration& global = clonedDecl->as<GlobalVarDeclaration>();
2873 VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2874 sharedVar = &decl.var();
2875 initialValue = decl.value().get();
Brian Osmanafa18ee2020-10-07 17:47:45 -04002876 } else {
2877 SkASSERT(clonedDecl->is<InterfaceBlock>());
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002878 sharedVar = &clonedDecl->as<InterfaceBlock>().variable();
Brian Osmanafa18ee2020-10-07 17:47:45 -04002879 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002880
2881 // Now clone the Variable, and add the clone to the Program's symbol table.
Brian Osmanc0213602020-10-06 14:43:32 -04002882 // Any initial value expression was cloned as part of the GlobalVarDeclaration,
Brian Osman00a8b5b2020-10-02 09:06:04 -04002883 // so we're pointing at a Program-owned expression.
2884 const Variable* clonedVar =
2885 fGenerator->fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Variable>(
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002886 sharedVar->fOffset, sharedVar->modifiersHandle(), sharedVar->name(),
2887 &sharedVar->type(), /*builtin=*/false, sharedVar->storage(),
Brian Osmanafa18ee2020-10-07 17:47:45 -04002888 initialValue));
Brian Osman00a8b5b2020-10-02 09:06:04 -04002889
Brian Osmanafa18ee2020-10-07 17:47:45 -04002890 // Go back and update the declaring element to point at the cloned Variable.
2891 if (clonedDecl->is<GlobalVarDeclaration>()) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002892 GlobalVarDeclaration& global = clonedDecl->as<GlobalVarDeclaration>();
2893 global.declaration()->as<VarDeclaration>().setVar(clonedVar);
Brian Osmanafa18ee2020-10-07 17:47:45 -04002894 } else {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002895 clonedDecl->as<InterfaceBlock>().setVariable(clonedVar);
Brian Osmanafa18ee2020-10-07 17:47:45 -04002896 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002897
2898 // Remember this new re-mapping...
2899 fRemap.insert({sharedVar, clonedVar});
2900
Brian Osmanafa18ee2020-10-07 17:47:45 -04002901 // Add the declaring element to this Program
2902 fNewElements.push_back(std::move(clonedDecl));
Brian Osman00a8b5b2020-10-02 09:06:04 -04002903 }
2904 }
2905
Brian Osman8e2ef022020-09-30 13:26:43 -04002906 bool visitExpression(Expression& e) override {
2907 // Look for references to builtin variables.
Ethan Nicholas78686922020-10-08 06:46:27 -04002908 if (e.is<VariableReference>() && e.as<VariableReference>().variable()->isBuiltin()) {
2909 const Variable* sharedVar = e.as<VariableReference>().variable();
Brian Osman8e2ef022020-09-30 13:26:43 -04002910
Ethan Nicholase2c49992020-10-05 11:49:11 -04002911 this->cloneVariable(sharedVar->name());
Brian Osman8e2ef022020-09-30 13:26:43 -04002912
2913 // TODO: SkASSERT(found), once all pre-includes are converted?
2914 auto found = fRemap.find(sharedVar);
2915 if (found != fRemap.end()) {
2916 e.as<VariableReference>().setVariable(found->second);
2917 }
2918 }
2919
2920 return INHERITED::visitExpression(e);
2921 }
2922
2923 IRGenerator* fGenerator;
2924 std::unordered_map<const Variable*, const Variable*> fRemap;
2925 std::vector<std::unique_ptr<ProgramElement>> fNewElements;
2926
2927 using INHERITED = ProgramWriter;
2928 using INHERITED::visitProgramElement;
2929 };
2930
Brian Osman00a8b5b2020-10-02 09:06:04 -04002931 BuiltinVariableRemapper remapper(this);
2932 for (auto& e : *fProgramElements) {
2933 remapper.visitProgramElement(*e);
Brian Osman8e2ef022020-09-30 13:26:43 -04002934 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002935
2936 // Vulkan requires certain builtin variables be present, even if they're unused. At one time,
2937 // validation errors would result if they were missing. Now, it's just (Adreno) driver bugs
2938 // that drop or corrupt draws if they're missing.
2939 switch (fKind) {
2940 case Program::kFragment_Kind:
2941 remapper.cloneVariable("sk_Clockwise");
2942 break;
2943 default:
2944 break;
2945 }
2946
2947 fProgramElements->insert(fProgramElements->begin(),
Brian Osmanafa18ee2020-10-07 17:47:45 -04002948 std::make_move_iterator(remapper.fNewElements.begin()),
2949 std::make_move_iterator(remapper.fNewElements.end()));
Brian Osman8e2ef022020-09-30 13:26:43 -04002950}
2951
Brian Osman88cda172020-10-09 12:05:16 -04002952IRGenerator::IRBundle IRGenerator::convertProgram(
2953 Program::Kind kind,
2954 const Program::Settings* settings,
Brian Osmand7e76592020-11-02 12:26:22 -05002955 const ShaderCapsClass* caps,
Brian Osman88cda172020-10-09 12:05:16 -04002956 const ParsedModule& base,
2957 bool isBuiltinCode,
2958 const char* text,
2959 size_t length,
2960 const std::vector<std::unique_ptr<ExternalValue>>* externalValues) {
Robert Phillipsfe8da172018-01-24 14:52:02 +00002961 fKind = kind;
Brian Osman88cda172020-10-09 12:05:16 -04002962 fSettings = settings;
Brian Osmand7e76592020-11-02 12:26:22 -05002963 fCaps = caps;
Brian Osman88cda172020-10-09 12:05:16 -04002964 fSymbolTable = base.fSymbols;
2965 fIntrinsics = base.fIntrinsics.get();
2966 if (fIntrinsics) {
2967 fIntrinsics->resetAlreadyIncluded();
2968 }
2969 fIsBuiltinCode = isBuiltinCode;
2970
2971 std::vector<std::unique_ptr<ProgramElement>> elements;
2972 fProgramElements = &elements;
2973
2974 fInputs.reset();
2975 fInvocations = -1;
2976 fRTAdjust = nullptr;
2977 fRTAdjustInterfaceBlock = nullptr;
2978
2979 fCapsMap.clear();
Brian Osmand7e76592020-11-02 12:26:22 -05002980 if (fCaps) {
2981 fill_caps(*fCaps, &fCapsMap);
Brian Osman88cda172020-10-09 12:05:16 -04002982 } else {
2983 fCapsMap.insert({String("integerSupport"), Program::Settings::Value(true)});
2984 }
2985
John Stilese51b6a32020-10-21 15:02:37 -04002986 AutoSymbolTable table(this);
Brian Osman88cda172020-10-09 12:05:16 -04002987
Brian Osman68c1d402020-10-12 16:36:38 -04002988 if (kind == Program::kGeometry_Kind && !fIsBuiltinCode) {
2989 // Declare sk_InvocationID programmatically. With invocations support, it's an 'in' builtin.
2990 // If we're applying the workaround, then it's a plain global.
Brian Osmand7e76592020-11-02 12:26:22 -05002991 bool workaround = fCaps && !fCaps->gsInvocationsSupport();
Brian Osman68c1d402020-10-12 16:36:38 -04002992 Modifiers m;
2993 if (!workaround) {
2994 m.fFlags = Modifiers::kIn_Flag;
2995 m.fLayout.fBuiltin = SK_INVOCATIONID_BUILTIN;
2996 }
2997 auto var = std::make_unique<Variable>(-1, fModifiers->handle(m), "sk_InvocationID",
2998 fContext.fInt_Type.get(), false,
2999 Variable::Storage::kGlobal);
John Stiles87ae34e2020-10-13 12:50:11 -04003000 auto decl = std::make_unique<VarDeclaration>(var.get(), fContext.fInt_Type.get(),
3001 /*sizes=*/ExpressionArray{},
3002 /*value=*/nullptr);
Brian Osman68c1d402020-10-12 16:36:38 -04003003 fSymbolTable->add(std::move(var));
3004 fProgramElements->push_back(
3005 std::make_unique<GlobalVarDeclaration>(/*offset=*/-1, std::move(decl)));
3006 }
3007
Brian Osman88cda172020-10-09 12:05:16 -04003008 if (externalValues) {
3009 // Add any external values to the new symbol table, so they're only visible to this Program
3010 for (const auto& ev : *externalValues) {
3011 fSymbolTable->addWithoutOwnership(ev.get());
3012 }
3013 }
3014
Ethan Nicholasc18bb512020-07-28 14:46:53 -04003015 Parser parser(text, length, *fSymbolTable, fErrors);
Ethan Nicholasba9a04f2020-11-06 09:28:04 -05003016 fFile = parser.compilationUnit();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003017 if (fErrors.errorCount()) {
Brian Osman88cda172020-10-09 12:05:16 -04003018 return {};
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003019 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003020 SkASSERT(fFile);
3021 for (const auto& decl : fFile->root()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003022 switch (decl.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04003023 case ASTNode::Kind::kVarDeclarations: {
John Stiles8f2a0cf2020-10-13 12:48:21 -04003024 StatementArray decls = this->convertVarDeclarations(decl,
3025 Variable::Storage::kGlobal);
Brian Osmanc0213602020-10-06 14:43:32 -04003026 for (auto& varDecl : decls) {
3027 fProgramElements->push_back(std::make_unique<GlobalVarDeclaration>(
3028 decl.fOffset, std::move(varDecl)));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003029 }
3030 break;
3031 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003032 case ASTNode::Kind::kEnum: {
3033 this->convertEnum(decl);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003034 break;
3035 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003036 case ASTNode::Kind::kFunction: {
3037 this->convertFunction(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003038 break;
3039 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003040 case ASTNode::Kind::kModifiers: {
3041 std::unique_ptr<ModifiersDeclaration> f = this->convertModifiersDeclaration(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003042 if (f) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003043 fProgramElements->push_back(std::move(f));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003044 }
3045 break;
3046 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003047 case ASTNode::Kind::kInterfaceBlock: {
3048 std::unique_ptr<InterfaceBlock> i = this->convertInterfaceBlock(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003049 if (i) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003050 fProgramElements->push_back(std::move(i));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003051 }
3052 break;
3053 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003054 case ASTNode::Kind::kExtension: {
3055 std::unique_ptr<Extension> e = this->convertExtension(decl.fOffset,
3056 decl.getString());
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003057 if (e) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003058 fProgramElements->push_back(std::move(e));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003059 }
3060 break;
3061 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003062 case ASTNode::Kind::kSection: {
3063 std::unique_ptr<Section> s = this->convertSection(decl);
Ethan Nicholas762466e2017-06-29 10:03:38 -04003064 if (s) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003065 fProgramElements->push_back(std::move(s));
Ethan Nicholas762466e2017-06-29 10:03:38 -04003066 }
3067 break;
3068 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003069 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003070#ifdef SK_DEBUG
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003071 ABORT("unsupported declaration: %s\n", decl.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003072#endif
3073 break;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003074 }
3075 }
Brian Osmanc95d3a12020-09-09 10:56:27 -04003076
Brian Osman8e2ef022020-09-30 13:26:43 -04003077 // Any variables defined in the pre-includes need to be cloned into the Program
Brian Osman00a8b5b2020-10-02 09:06:04 -04003078 if (!fIsBuiltinCode && fIntrinsics) {
3079 this->cloneBuiltinVariables();
3080 }
Brian Osman8e2ef022020-09-30 13:26:43 -04003081
Brian Osmanc95d3a12020-09-09 10:56:27 -04003082 // Do a final pass looking for dangling FunctionReference or TypeReference expressions
3083 class FindIllegalExpressions : public ProgramVisitor {
3084 public:
3085 FindIllegalExpressions(IRGenerator* generator) : fGenerator(generator) {}
3086
3087 bool visitExpression(const Expression& e) override {
3088 fGenerator->checkValid(e);
3089 return INHERITED::visitExpression(e);
3090 }
3091
3092 IRGenerator* fGenerator;
3093 using INHERITED = ProgramVisitor;
3094 using INHERITED::visitProgramElement;
3095 };
3096 for (const auto& pe : *fProgramElements) {
3097 FindIllegalExpressions{this}.visitProgramElement(*pe);
3098 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003099
Brian Osman88cda172020-10-09 12:05:16 -04003100 fSettings = nullptr;
3101
John Stilese51b6a32020-10-21 15:02:37 -04003102 return IRBundle{std::move(elements), this->releaseModifiers(), fSymbolTable, fInputs};
Brian Osman88cda172020-10-09 12:05:16 -04003103}
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003104
John Stilesa6841be2020-08-06 14:11:56 -04003105} // namespace SkSL