blob: dfe553d2ecfac614e1bd2039ee51c6e1667a2b19 [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 }
John Stiles586df952020-11-12 18:27:13 -0500418 auto var = std::make_unique<Variable>(varDecl.fOffset, fModifiers->addToPool(modifiers),
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400419 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 }
John Stiles586df952020-11-12 18:27:13 -0500479 return std::make_unique<ModifiersDeclaration>(fModifiers->addToPool(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 Stiles586df952020-11-12 18:27:13 -0500730 const FunctionDeclaration* invokeDecl = fSymbolTable->add(std::make_unique<FunctionDeclaration>(
731 /*offset=*/-1,
732 fModifiers->addToPool(invokeModifiers),
733 "_invoke",
734 std::vector<const Variable*>(),
735 fContext.fVoid_Type.get(),
736 fIsBuiltinCode));
John Stilesb9af7232020-08-20 15:57:48 -0400737 fProgramElements->push_back(std::make_unique<FunctionDefinition>(/*offset=*/-1,
John Stiles607d36b2020-10-19 15:00:01 -0400738 invokeDecl, fIsBuiltinCode,
John Stilesb9af7232020-08-20 15:57:48 -0400739 std::move(main)));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400740
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000741 std::vector<std::unique_ptr<VarDeclaration>> variables;
John Stilesb9af7232020-08-20 15:57:48 -0400742 const Variable* loopIdx = &(*fSymbolTable)["sk_InvocationID"]->as<Variable>();
John Stiles8e3b6be2020-10-13 11:14:08 -0400743 auto test = std::make_unique<BinaryExpression>(/*offset=*/-1,
744 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx),
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400745 Token::Kind::TK_LT,
John Stiles8e3b6be2020-10-13 11:14:08 -0400746 std::make_unique<IntLiteral>(fContext, /*offset=*/-1, fInvocations),
747 fContext.fBool_Type.get());
748 auto next = std::make_unique<PostfixExpression>(
749 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx,
750 VariableReference::RefKind::kReadWrite),
751 Token::Kind::TK_PLUSPLUS);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400752 ASTNode endPrimitiveID(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier, "EndPrimitive");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400753 std::unique_ptr<Expression> endPrimitive = this->convertExpression(endPrimitiveID);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400754 SkASSERT(endPrimitive);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400755
John Stiles8f2a0cf2020-10-13 12:48:21 -0400756 StatementArray loopBody;
John Stilesf4bda742020-10-14 16:57:41 -0400757 loopBody.reserve_back(2);
John Stiles8e3b6be2020-10-13 11:14:08 -0400758 loopBody.push_back(std::make_unique<ExpressionStatement>(this->call(
759 /*offset=*/-1, *invokeDecl,
760 ExpressionArray{})));
761 loopBody.push_back(std::make_unique<ExpressionStatement>(this->call(
762 /*offset=*/-1, std::move(endPrimitive),
763 ExpressionArray{})));
764 auto assignment = std::make_unique<BinaryExpression>(/*offset=*/-1,
765 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx,
766 VariableReference::RefKind::kWrite),
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400767 Token::Kind::TK_EQ,
John Stiles8e3b6be2020-10-13 11:14:08 -0400768 std::make_unique<IntLiteral>(fContext, /*offset=*/-1, /*value=*/0),
769 fContext.fInt_Type.get());
770 auto initializer = std::make_unique<ExpressionStatement>(std::move(assignment));
771 auto loop = std::make_unique<ForStatement>(/*offset=*/-1,
772 std::move(initializer),
773 std::move(test), std::move(next),
774 std::make_unique<Block>(-1, std::move(loopBody)),
775 fSymbolTable);
John Stiles8f2a0cf2020-10-13 12:48:21 -0400776 StatementArray children;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400777 children.push_back(std::move(loop));
John Stilesfbd050b2020-08-03 13:21:46 -0400778 return std::make_unique<Block>(-1, std::move(children));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400779}
780
Robert Phillipsfe8da172018-01-24 14:52:02 +0000781std::unique_ptr<Statement> IRGenerator::getNormalizeSkPositionCode() {
Brian Osman88cda172020-10-09 12:05:16 -0400782 const Variable* skPerVertex = nullptr;
783 if (const ProgramElement* perVertexDecl = fIntrinsics->find(Compiler::PERVERTEX_NAME)) {
784 SkASSERT(perVertexDecl->is<InterfaceBlock>());
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400785 skPerVertex = &perVertexDecl->as<InterfaceBlock>().variable();
Brian Osman88cda172020-10-09 12:05:16 -0400786 }
787
Ethan Nicholasb809efb2018-04-12 14:39:21 -0400788 // sk_Position = float4(sk_Position.xy * rtAdjust.xz + sk_Position.ww * rtAdjust.yw,
Robert Phillipsfe8da172018-01-24 14:52:02 +0000789 // 0,
790 // sk_Position.w);
Brian Osman88cda172020-10-09 12:05:16 -0400791 SkASSERT(skPerVertex && fRTAdjust);
John Stiles5acf6a82020-11-10 22:38:01 -0500792 auto Ref = [](const Variable* var) -> std::unique_ptr<Expression> {
793 return std::make_unique<VariableReference>(-1, var, VariableReference::RefKind::kRead);
794 };
795 auto WRef = [](const Variable* var) -> std::unique_ptr<Expression> {
796 return std::make_unique<VariableReference>(-1, var, VariableReference::RefKind::kWrite);
797 };
798 auto Field = [&](const Variable* var, int idx) -> std::unique_ptr<Expression> {
799 return std::make_unique<FieldAccess>(Ref(var), idx,
800 FieldAccess::OwnerKind::kAnonymousInterfaceBlock);
801 };
802 auto Pos = [&]() -> std::unique_ptr<Expression> {
803 return std::make_unique<FieldAccess>(WRef(skPerVertex), 0,
804 FieldAccess::OwnerKind::kAnonymousInterfaceBlock);
805 };
806 auto Adjust = [&]() -> std::unique_ptr<Expression> {
807 return fRTAdjustInterfaceBlock ? Field(fRTAdjustInterfaceBlock, fRTAdjustFieldIndex)
808 : Ref(fRTAdjust);
809 };
810 auto Swizzle = [&](std::unique_ptr<Expression> expr,
811 const ComponentArray& comp) -> std::unique_ptr<Expression> {
812 return std::make_unique<SkSL::Swizzle>(fContext, std::move(expr), comp);
813 };
814 auto Op = [&](std::unique_ptr<Expression> left, Token::Kind op,
815 std::unique_ptr<Expression> right) -> std::unique_ptr<Expression> {
816 return std::make_unique<BinaryExpression>(-1, std::move(left), op, std::move(right),
817 fContext.fFloat2_Type.get());
818 };
John Stiles750109b2020-10-30 13:45:46 -0400819
John Stiles5acf6a82020-11-10 22:38:01 -0500820 static const ComponentArray kXYIndices{0, 1};
821 static const ComponentArray kXZIndices{0, 2};
822 static const ComponentArray kYWIndices{1, 3};
823 static const ComponentArray kWWIndices{3, 3};
824 static const ComponentArray kWIndex{3};
John Stiles750109b2020-10-30 13:45:46 -0400825
John Stiles8e3b6be2020-10-13 11:14:08 -0400826 ExpressionArray children;
John Stilesf4bda742020-10-14 16:57:41 -0400827 children.reserve_back(3);
John Stiles5acf6a82020-11-10 22:38:01 -0500828 children.push_back(Op(
829 Op(Swizzle(Pos(), kXYIndices), Token::Kind::TK_STAR, Swizzle(Adjust(), kXZIndices)),
830 Token::Kind::TK_PLUS,
831 Op(Swizzle(Pos(), kWWIndices), Token::Kind::TK_STAR, Swizzle(Adjust(), kYWIndices))));
John Stiles8e3b6be2020-10-13 11:14:08 -0400832 children.push_back(std::make_unique<FloatLiteral>(fContext, /*offset=*/-1, /*value=*/0.0));
John Stiles5acf6a82020-11-10 22:38:01 -0500833 children.push_back(Swizzle(Pos(), kWIndex));
834 std::unique_ptr<Expression> result = Op(Pos(), Token::Kind::TK_EQ,
John Stiles8e3b6be2020-10-13 11:14:08 -0400835 std::make_unique<Constructor>(/*offset=*/-1,
836 fContext.fFloat4_Type.get(),
837 std::move(children)));
838 return std::make_unique<ExpressionStatement>(std::move(result));
Robert Phillipsfe8da172018-01-24 14:52:02 +0000839}
840
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400841template<typename T>
842class AutoClear {
843public:
844 AutoClear(T* container)
845 : fContainer(container) {
846 SkASSERT(container->empty());
847 }
848
849 ~AutoClear() {
850 fContainer->clear();
851 }
852
853private:
854 T* fContainer;
855};
856
John Stilesb8e010c2020-08-11 18:05:39 -0400857template <typename T> AutoClear(T* c) -> AutoClear<T>;
858
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400859void IRGenerator::checkModifiers(int offset, const Modifiers& modifiers, int permitted) {
860 int flags = modifiers.fFlags;
861 #define CHECK(flag, name) \
862 if (!flags) return; \
863 if (flags & flag) { \
864 if (!(permitted & flag)) { \
865 fErrors.error(offset, "'" name "' is not permitted here"); \
866 } \
867 flags &= ~flag; \
868 }
869 CHECK(Modifiers::kConst_Flag, "const")
870 CHECK(Modifiers::kIn_Flag, "in")
871 CHECK(Modifiers::kOut_Flag, "out")
872 CHECK(Modifiers::kUniform_Flag, "uniform")
873 CHECK(Modifiers::kFlat_Flag, "flat")
874 CHECK(Modifiers::kNoPerspective_Flag, "noperspective")
875 CHECK(Modifiers::kReadOnly_Flag, "readonly")
876 CHECK(Modifiers::kWriteOnly_Flag, "writeonly")
877 CHECK(Modifiers::kCoherent_Flag, "coherent")
878 CHECK(Modifiers::kVolatile_Flag, "volatile")
879 CHECK(Modifiers::kRestrict_Flag, "restrict")
880 CHECK(Modifiers::kBuffer_Flag, "buffer")
881 CHECK(Modifiers::kHasSideEffects_Flag, "sk_has_side_effects")
882 CHECK(Modifiers::kPLS_Flag, "__pixel_localEXT")
883 CHECK(Modifiers::kPLSIn_Flag, "__pixel_local_inEXT")
884 CHECK(Modifiers::kPLSOut_Flag, "__pixel_local_outEXT")
885 CHECK(Modifiers::kVarying_Flag, "varying")
Ethan Nicholasf3c8f5d2020-08-20 13:09:14 +0000886 CHECK(Modifiers::kInline_Flag, "inline")
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400887 SkASSERT(flags == 0);
888}
889
Ethan Nicholasfc994162019-06-06 10:04:27 -0400890void IRGenerator::convertFunction(const ASTNode& f) {
John Stilesb8e010c2020-08-11 18:05:39 -0400891 AutoClear clear(&fReferencedIntrinsics);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400892 auto iter = f.begin();
Brian Osmand8070392020-09-09 15:50:02 -0400893 const Type* returnType = this->convertType(*(iter++), /*allowVoid=*/true);
John Stilesb9af7232020-08-20 15:57:48 -0400894 if (returnType == nullptr) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400895 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700896 }
Brian Osman3000d6b2020-07-31 15:57:28 -0400897 auto type_is_allowed = [&](const Type* t) {
898#if defined(SKSL_STANDALONE)
899 return true;
900#else
901 GrSLType unusedSLType;
902 return fKind != Program::kPipelineStage_Kind ||
903 type_to_grsltype(fContext, *t, &unusedSLType);
904#endif
905 };
906 if (returnType->nonnullable() == *fContext.fFragmentProcessor_Type ||
907 !type_is_allowed(returnType)) {
Brian Osman82329002020-07-21 09:39:27 -0400908 fErrors.error(f.fOffset,
909 "functions may not return type '" + returnType->displayName() + "'");
910 return;
911 }
John Stilesb9af7232020-08-20 15:57:48 -0400912 const ASTNode::FunctionData& funcData = f.getFunctionData();
913 this->checkModifiers(f.fOffset, funcData.fModifiers, Modifiers::kHasSideEffects_Flag |
914 Modifiers::kInline_Flag);
Brian Osman5bf3e202020-10-13 10:34:18 -0400915 std::vector<const Variable*> parameters;
John Stilesb9af7232020-08-20 15:57:48 -0400916 for (size_t i = 0; i < funcData.fParameterCount; ++i) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400917 const ASTNode& param = *(iter++);
918 SkASSERT(param.fKind == ASTNode::Kind::kParameter);
919 ASTNode::ParameterData pd = param.getParameterData();
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400920 this->checkModifiers(param.fOffset, pd.fModifiers, Modifiers::kIn_Flag |
921 Modifiers::kOut_Flag);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400922 auto paramIter = param.begin();
923 const Type* type = this->convertType(*(paramIter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700924 if (!type) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400925 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700926 }
John Stiles7f7b4852020-11-10 11:25:35 -0500927 for (int j = 1; j <= (int) pd.fSizeCount; j++) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400928 int size = (param.begin() + j)->getInt();
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400929 String name = type->name() + "[" + to_string(size) + "]";
John Stiles3ae071e2020-08-05 15:29:29 -0400930 type = fSymbolTable->takeOwnershipOfSymbol(
Ethan Nicholase6592142020-09-08 10:22:09 -0400931 std::make_unique<Type>(std::move(name), Type::TypeKind::kArray, *type, size));
ethannicholasb3058bd2016-07-01 08:22:01 -0700932 }
Brian Osman3000d6b2020-07-31 15:57:28 -0400933 // Only the (builtin) declarations of 'sample' are allowed to have FP parameters
934 if ((type->nonnullable() == *fContext.fFragmentProcessor_Type && !fIsBuiltinCode) ||
935 !type_is_allowed(type)) {
936 fErrors.error(param.fOffset,
937 "parameters of type '" + type->displayName() + "' not allowed");
938 return;
939 }
Brian Osman8dbdf232020-10-12 14:40:24 -0400940
941 Modifiers m = pd.fModifiers;
942 if (funcData.fName == "main" && (fKind == Program::kPipelineStage_Kind ||
943 fKind == Program::kFragmentProcessor_Kind)) {
944 if (i == 0) {
945 // We verify that the type is correct later, for now, if there is a parameter to
946 // a .fp or runtime-effect main(), it's supposed to be the coords:
947 m.fLayout.fBuiltin = SK_MAIN_COORDS_BUILTIN;
948 }
949 }
950
Brian Osman5bf3e202020-10-13 10:34:18 -0400951 const Variable* var = fSymbolTable->takeOwnershipOfSymbol(
John Stiles586df952020-11-12 18:27:13 -0500952 std::make_unique<Variable>(param.fOffset, fModifiers->addToPool(m), pd.fName, type,
Brian Osman8dbdf232020-10-12 14:40:24 -0400953 fIsBuiltinCode, Variable::Storage::kParameter));
ethannicholasd598f792016-07-25 10:08:54 -0700954 parameters.push_back(var);
ethannicholasb3058bd2016-07-01 08:22:01 -0700955 }
956
Brian Osman767f4442020-08-13 16:59:48 -0400957 auto paramIsCoords = [&](int idx) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400958 return parameters[idx]->type() == *fContext.fFloat2_Type &&
Brian Osman8dbdf232020-10-12 14:40:24 -0400959 parameters[idx]->modifiers().fFlags == 0 &&
960 parameters[idx]->modifiers().fLayout.fBuiltin == SK_MAIN_COORDS_BUILTIN;
Brian Osman767f4442020-08-13 16:59:48 -0400961 };
Brian Osman767f4442020-08-13 16:59:48 -0400962
John Stilesb9af7232020-08-20 15:57:48 -0400963 if (funcData.fName == "main") {
Ethan Nicholas0d997662019-04-08 09:46:01 -0400964 switch (fKind) {
965 case Program::kPipelineStage_Kind: {
Brian Osman33316412020-11-06 10:42:51 -0500966 // (half4|float4) main() -or- (half4|float4) main(float2)
967 if (*returnType != *fContext.fHalf4_Type && *returnType != *fContext.fFloat4_Type) {
968 fErrors.error(f.fOffset, "'main' must return: 'vec4', 'float4', or 'half4'");
969 return;
970 }
971 if (!(parameters.size() == 0 || (parameters.size() == 1 && paramIsCoords(0)))) {
972 fErrors.error(f.fOffset, "'main' parameters must be: (), (vec2), or (float2)");
Brian Osman767f4442020-08-13 16:59:48 -0400973 return;
974 }
975 break;
Brian Osman44820a92020-08-26 09:27:39 -0400976 }
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400977 case Program::kFragmentProcessor_Kind: {
Brian Osman44820a92020-08-26 09:27:39 -0400978 bool valid = (parameters.size() == 0) ||
979 (parameters.size() == 1 && paramIsCoords(0));
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400980 if (!valid) {
981 fErrors.error(f.fOffset, ".fp 'main' must be declared main() or main(float2)");
982 return;
983 }
984 break;
985 }
Ethan Nicholas746035a2019-04-23 13:31:09 -0400986 case Program::kGeneric_Kind:
Ethan Nicholas0d997662019-04-08 09:46:01 -0400987 break;
Ethan Nicholas0d997662019-04-08 09:46:01 -0400988 default:
989 if (parameters.size()) {
990 fErrors.error(f.fOffset, "shader 'main' must have zero parameters");
991 }
Ethan Nicholas00543112018-07-31 09:44:36 -0400992 }
993 }
994
ethannicholasb3058bd2016-07-01 08:22:01 -0700995 // find existing declaration
ethannicholasd598f792016-07-25 10:08:54 -0700996 const FunctionDeclaration* decl = nullptr;
John Stilesb9af7232020-08-20 15:57:48 -0400997 const Symbol* entry = (*fSymbolTable)[funcData.fName];
ethannicholasb3058bd2016-07-01 08:22:01 -0700998 if (entry) {
ethannicholasd598f792016-07-25 10:08:54 -0700999 std::vector<const FunctionDeclaration*> functions;
Ethan Nicholase6592142020-09-08 10:22:09 -04001000 switch (entry->kind()) {
1001 case Symbol::Kind::kUnresolvedFunction:
Ethan Nicholasceb62142020-10-09 16:51:18 -04001002 functions = entry->as<UnresolvedFunction>().functions();
ethannicholasb3058bd2016-07-01 08:22:01 -07001003 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001004 case Symbol::Kind::kFunctionDeclaration:
John Stiles17c5b702020-08-18 10:40:03 -04001005 functions.push_back(&entry->as<FunctionDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -07001006 break;
1007 default:
John Stilesb9af7232020-08-20 15:57:48 -04001008 fErrors.error(f.fOffset, "symbol '" + funcData.fName + "' was already defined");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001009 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001010 }
John Stilesb9af7232020-08-20 15:57:48 -04001011 for (const FunctionDeclaration* other : functions) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001012 SkASSERT(other->name() == funcData.fName);
Ethan Nicholased84b732020-10-08 11:45:44 -04001013 if (parameters.size() == other->parameters().size()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001014 bool match = true;
1015 for (size_t i = 0; i < parameters.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001016 if (parameters[i]->type() != other->parameters()[i]->type()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001017 match = false;
1018 break;
1019 }
1020 }
1021 if (match) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001022 if (*returnType != other->returnType()) {
1023 FunctionDeclaration newDecl(f.fOffset,
John Stiles586df952020-11-12 18:27:13 -05001024 fModifiers->addToPool(funcData.fModifiers),
Ethan Nicholased84b732020-10-08 11:45:44 -04001025 funcData.fName,
1026 parameters,
1027 returnType,
1028 fIsBuiltinCode);
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001029 fErrors.error(f.fOffset, "functions '" + newDecl.description() +
1030 "' and '" + other->description() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001031 "' differ only in return type");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001032 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001033 }
1034 decl = other;
1035 for (size_t i = 0; i < parameters.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001036 if (parameters[i]->modifiers() != other->parameters()[i]->modifiers()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001037 fErrors.error(f.fOffset, "modifiers on parameter " +
1038 to_string((uint64_t) i + 1) +
John Stilesb9af7232020-08-20 15:57:48 -04001039 " differ between declaration and definition");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001040 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001041 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001042 }
Ethan Nicholased84b732020-10-08 11:45:44 -04001043 if (other->definition() && !other->isBuiltin()) {
John Stilesb9af7232020-08-20 15:57:48 -04001044 fErrors.error(f.fOffset, "duplicate definition of " + other->description());
ethannicholasb3058bd2016-07-01 08:22:01 -07001045 }
1046 break;
1047 }
1048 }
1049 }
1050 }
1051 if (!decl) {
John Stilesb9af7232020-08-20 15:57:48 -04001052 // Conservatively assume all user-defined functions have side effects.
1053 Modifiers declModifiers = funcData.fModifiers;
1054 if (!fIsBuiltinCode) {
1055 declModifiers.fFlags |= Modifiers::kHasSideEffects_Flag;
1056 }
1057
1058 // Create a new declaration.
John Stiles586df952020-11-12 18:27:13 -05001059 decl = fSymbolTable->add(
1060 std::make_unique<FunctionDeclaration>(f.fOffset,
1061 fModifiers->addToPool(declModifiers),
1062 funcData.fName,
1063 parameters,
1064 returnType,
1065 fIsBuiltinCode));
ethannicholasb3058bd2016-07-01 08:22:01 -07001066 }
John Stiles569249b2020-11-03 12:18:22 -05001067 if (iter == f.end()) {
1068 // If there's no body, we've found a prototype.
1069 fProgramElements->push_back(std::make_unique<FunctionPrototype>(f.fOffset, decl,
1070 fIsBuiltinCode));
1071 } else {
1072 // Compile function body.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001073 SkASSERT(!fCurrentFunction);
ethannicholasd598f792016-07-25 10:08:54 -07001074 fCurrentFunction = decl;
John Stiles569249b2020-11-03 12:18:22 -05001075
ethannicholasd598f792016-07-25 10:08:54 -07001076 AutoSymbolTable table(this);
John Stiles569249b2020-11-03 12:18:22 -05001077 for (const Variable* param : decl->parameters()) {
1078 fSymbolTable->addWithoutOwnership(param);
ethannicholasb3058bd2016-07-01 08:22:01 -07001079 }
John Stilesb9af7232020-08-20 15:57:48 -04001080 bool needInvocationIDWorkaround = fInvocations != -1 && funcData.fName == "main" &&
Brian Osmand7e76592020-11-02 12:26:22 -05001081 fCaps && !fCaps->gsInvocationsSupport();
Ethan Nicholasfc994162019-06-06 10:04:27 -04001082 std::unique_ptr<Block> body = this->convertBlock(*iter);
ethannicholasd598f792016-07-25 10:08:54 -07001083 fCurrentFunction = nullptr;
1084 if (!body) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001085 return;
1086 }
1087 if (needInvocationIDWorkaround) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001088 body = this->applyInvocationIDWorkaround(std::move(body));
ethannicholasd598f792016-07-25 10:08:54 -07001089 }
John Stilesb9af7232020-08-20 15:57:48 -04001090 if (Program::kVertex_Kind == fKind && funcData.fName == "main" && fRTAdjust) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001091 body->children().push_back(this->getNormalizeSkPositionCode());
Robert Phillipsfe8da172018-01-24 14:52:02 +00001092 }
John Stiles607d36b2020-10-19 15:00:01 -04001093 auto result = std::make_unique<FunctionDefinition>(
1094 f.fOffset, decl, fIsBuiltinCode, std::move(body), std::move(fReferencedIntrinsics));
Ethan Nicholased84b732020-10-08 11:45:44 -04001095 decl->setDefinition(result.get());
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001096 result->setSource(&f);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001097 fProgramElements->push_back(std::move(result));
ethannicholasb3058bd2016-07-01 08:22:01 -07001098 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001099}
1100
Ethan Nicholasfc994162019-06-06 10:04:27 -04001101std::unique_ptr<InterfaceBlock> IRGenerator::convertInterfaceBlock(const ASTNode& intf) {
Brian Osman16f376f2020-09-02 12:30:59 -04001102 if (fKind != Program::kFragment_Kind &&
1103 fKind != Program::kVertex_Kind &&
1104 fKind != Program::kGeometry_Kind) {
1105 fErrors.error(intf.fOffset, "interface block is not allowed here");
1106 return nullptr;
1107 }
1108
Ethan Nicholasfc994162019-06-06 10:04:27 -04001109 SkASSERT(intf.fKind == ASTNode::Kind::kInterfaceBlock);
1110 ASTNode::InterfaceBlockData id = intf.getInterfaceBlockData();
ethannicholasb3058bd2016-07-01 08:22:01 -07001111 std::shared_ptr<SymbolTable> old = fSymbolTable;
John Stiles869cdef2020-10-30 14:24:24 -04001112 std::shared_ptr<SymbolTable> symbols;
ethannicholasb3058bd2016-07-01 08:22:01 -07001113 std::vector<Type::Field> fields;
Robert Phillipsfe8da172018-01-24 14:52:02 +00001114 bool foundRTAdjust = false;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001115 auto iter = intf.begin();
John Stiles869cdef2020-10-30 14:24:24 -04001116 {
1117 AutoSymbolTable table(this);
1118 symbols = fSymbolTable;
1119 bool haveRuntimeArray = false;
1120 for (size_t i = 0; i < id.fDeclarationCount; ++i) {
1121 StatementArray decls = this->convertVarDeclarations(*(iter++),
1122 Variable::Storage::kInterfaceBlock);
1123 if (decls.empty()) {
1124 return nullptr;
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001125 }
John Stiles869cdef2020-10-30 14:24:24 -04001126 for (const auto& decl : decls) {
1127 const VarDeclaration& vd = decl->as<VarDeclaration>();
1128 if (haveRuntimeArray) {
1129 fErrors.error(decl->fOffset,
1130 "only the last entry in an interface block may be a runtime-sized "
1131 "array");
1132 }
1133 if (&vd.var() == fRTAdjust) {
1134 foundRTAdjust = true;
1135 SkASSERT(vd.var().type() == *fContext.fFloat4_Type);
1136 fRTAdjustFieldIndex = fields.size();
1137 }
1138 fields.push_back(Type::Field(vd.var().modifiers(), vd.var().name(),
1139 &vd.var().type()));
1140 if (vd.value()) {
1141 fErrors.error(decl->fOffset,
1142 "initializers are not permitted on interface block fields");
1143 }
1144 if (vd.var().type().typeKind() == Type::TypeKind::kArray &&
1145 vd.var().type().columns() == Type::kUnsizedArray) {
1146 haveRuntimeArray = true;
1147 }
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001148 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001149 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001150 }
John Stiles3ae071e2020-08-05 15:29:29 -04001151 const Type* type =
1152 old->takeOwnershipOfSymbol(std::make_unique<Type>(intf.fOffset, id.fTypeName, fields));
John Stiles87ae34e2020-10-13 12:50:11 -04001153 ExpressionArray sizes;
John Stilesf4bda742020-10-14 16:57:41 -04001154 sizes.reserve_back(id.fSizeCount);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001155 for (size_t i = 0; i < id.fSizeCount; ++i) {
1156 const ASTNode& size = *(iter++);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001157 if (size) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001158 std::unique_ptr<Expression> converted = this->convertExpression(size);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001159 if (!converted) {
1160 return nullptr;
1161 }
Ethan Nicholase2c49992020-10-05 11:49:11 -04001162 String name = type->name();
Ethan Nicholas50afc172017-02-16 14:49:57 -05001163 int64_t count;
Ethan Nicholase6592142020-09-08 10:22:09 -04001164 if (converted->kind() == Expression::Kind::kIntLiteral) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001165 count = converted->as<IntLiteral>().value();
Ethan Nicholas50afc172017-02-16 14:49:57 -05001166 if (count <= 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001167 fErrors.error(converted->fOffset, "array size must be positive");
Ethan Nicholas66d80062019-09-09 14:50:51 -04001168 return nullptr;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001169 }
1170 name += "[" + to_string(count) + "]";
1171 } else {
Ethan Nicholas66d80062019-09-09 14:50:51 -04001172 fErrors.error(intf.fOffset, "array size must be specified");
1173 return nullptr;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001174 }
John Stiles3ae071e2020-08-05 15:29:29 -04001175 type = symbols->takeOwnershipOfSymbol(
Ethan Nicholase6592142020-09-08 10:22:09 -04001176 std::make_unique<Type>(name, Type::TypeKind::kArray, *type, (int)count));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001177 sizes.push_back(std::move(converted));
1178 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001179 String name = String(type->name()) + "[]";
Brian Osmane8c26082020-10-01 17:22:45 -04001180 type = symbols->takeOwnershipOfSymbol(std::make_unique<Type>(
1181 name, Type::TypeKind::kArray, *type, Type::kUnsizedArray));
1182 sizes.push_back(nullptr);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001183 }
1184 }
Brian Osman5bf3e202020-10-13 10:34:18 -04001185 const Variable* var = old->takeOwnershipOfSymbol(
John Stiles3ae071e2020-08-05 15:29:29 -04001186 std::make_unique<Variable>(intf.fOffset,
John Stiles586df952020-11-12 18:27:13 -05001187 fModifiers->addToPool(id.fModifiers),
John Stiles3ae071e2020-08-05 15:29:29 -04001188 id.fInstanceName.fLength ? id.fInstanceName : id.fTypeName,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001189 type,
Brian Osman3887a012020-09-30 13:22:27 -04001190 fIsBuiltinCode,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001191 Variable::Storage::kGlobal));
Robert Phillipsfe8da172018-01-24 14:52:02 +00001192 if (foundRTAdjust) {
1193 fRTAdjustInterfaceBlock = var;
1194 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001195 if (id.fInstanceName.fLength) {
John Stilesb8cc6652020-10-08 09:12:07 -04001196 old->addWithoutOwnership(var);
ethannicholasb3058bd2016-07-01 08:22:01 -07001197 } else {
1198 for (size_t i = 0; i < fields.size(); i++) {
John Stilesb8cc6652020-10-08 09:12:07 -04001199 old->add(std::make_unique<Field>(intf.fOffset, var, (int)i));
ethannicholasb3058bd2016-07-01 08:22:01 -07001200 }
1201 }
John Stilesfbd050b2020-08-03 13:21:46 -04001202 return std::make_unique<InterfaceBlock>(intf.fOffset,
1203 var,
1204 id.fTypeName,
1205 id.fInstanceName,
1206 std::move(sizes),
1207 symbols);
ethannicholasb3058bd2016-07-01 08:22:01 -07001208}
1209
Brian Osman3e3db6c2020-08-14 09:42:12 -04001210bool IRGenerator::getConstantInt(const Expression& value, int64_t* out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001211 switch (value.kind()) {
1212 case Expression::Kind::kIntLiteral:
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001213 *out = value.as<IntLiteral>().value();
Brian Osman3e3db6c2020-08-14 09:42:12 -04001214 return true;
Ethan Nicholase6592142020-09-08 10:22:09 -04001215 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001216 const Variable& var = *value.as<VariableReference>().variable();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001217 return (var.modifiers().fFlags & Modifiers::kConst_Flag) &&
1218 var.initialValue() && this->getConstantInt(*var.initialValue(), out);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001219 }
1220 default:
Brian Osman3e3db6c2020-08-14 09:42:12 -04001221 return false;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001222 }
1223}
1224
Ethan Nicholasfc994162019-06-06 10:04:27 -04001225void IRGenerator::convertEnum(const ASTNode& e) {
Brian Osman16f376f2020-09-02 12:30:59 -04001226 if (fKind == Program::kPipelineStage_Kind) {
1227 fErrors.error(e.fOffset, "enum is not allowed here");
1228 return;
1229 }
1230
Ethan Nicholasfc994162019-06-06 10:04:27 -04001231 SkASSERT(e.fKind == ASTNode::Kind::kEnum);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001232 int64_t currentValue = 0;
1233 Layout layout;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001234 ASTNode enumType(e.fNodes, e.fOffset, ASTNode::Kind::kType,
1235 ASTNode::TypeData(e.getString(), false, false));
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001236 const Type* type = this->convertType(enumType);
1237 Modifiers modifiers(layout, Modifiers::kConst_Flag);
Brian Osman1313d1a2020-09-08 10:34:30 -04001238 std::shared_ptr<SymbolTable> oldTable = fSymbolTable;
John Stiles7c3515b2020-10-16 18:38:39 -04001239 fSymbolTable = std::make_shared<SymbolTable>(fSymbolTable, fIsBuiltinCode);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001240 for (auto iter = e.begin(); iter != e.end(); ++iter) {
1241 const ASTNode& child = *iter;
1242 SkASSERT(child.fKind == ASTNode::Kind::kEnumCase);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001243 std::unique_ptr<Expression> value;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001244 if (child.begin() != child.end()) {
1245 value = this->convertExpression(*child.begin());
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001246 if (!value) {
Brian Osman1313d1a2020-09-08 10:34:30 -04001247 fSymbolTable = oldTable;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001248 return;
1249 }
Brian Osman3e3db6c2020-08-14 09:42:12 -04001250 if (!this->getConstantInt(*value, &currentValue)) {
1251 fErrors.error(value->fOffset, "enum value must be a constant integer");
Brian Osman1313d1a2020-09-08 10:34:30 -04001252 fSymbolTable = oldTable;
Brian Osman3e3db6c2020-08-14 09:42:12 -04001253 return;
1254 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001255 }
1256 value = std::unique_ptr<Expression>(new IntLiteral(fContext, e.fOffset, currentValue));
1257 ++currentValue;
John Stiles586df952020-11-12 18:27:13 -05001258 fSymbolTable->add(std::make_unique<Variable>(e.fOffset, fModifiers->addToPool(modifiers),
John Stilesb8cc6652020-10-08 09:12:07 -04001259 child.getString(), type, fIsBuiltinCode,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001260 Variable::Storage::kGlobal, value.get()));
Brian Osman3e3db6c2020-08-14 09:42:12 -04001261 fSymbolTable->takeOwnershipOfIRNode(std::move(value));
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001262 }
Brian Osman1313d1a2020-09-08 10:34:30 -04001263 // Now we orphanize the Enum's symbol table, so that future lookups in it are strict
1264 fSymbolTable->fParent = nullptr;
John Stiles1c823672020-10-20 10:23:50 -04001265 fProgramElements->push_back(std::make_unique<Enum>(e.fOffset, e.getString(), fSymbolTable,
1266 /*isSharedWithCpp=*/fIsBuiltinCode,
1267 /*isBuiltin=*/fIsBuiltinCode));
Brian Osman1313d1a2020-09-08 10:34:30 -04001268 fSymbolTable = oldTable;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001269}
1270
Brian Osmand8070392020-09-09 15:50:02 -04001271const Type* IRGenerator::convertType(const ASTNode& type, bool allowVoid) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001272 ASTNode::TypeData td = type.getTypeData();
1273 const Symbol* result = (*fSymbolTable)[td.fName];
Brian Osmand8070392020-09-09 15:50:02 -04001274 if (result && result->is<Type>()) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001275 if (td.fIsNullable) {
John Stiles17c5b702020-08-18 10:40:03 -04001276 if (result->as<Type>() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001277 if (type.begin() != type.end()) {
1278 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be used in "
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001279 "an array");
1280 }
John Stiles3ae071e2020-08-05 15:29:29 -04001281 result = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
Ethan Nicholase2c49992020-10-05 11:49:11 -04001282 String(result->name()) + "?", Type::TypeKind::kNullable,
1283 result->as<Type>()));
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001284 } else {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001285 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be nullable");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001286 }
1287 }
Brian Osmand8070392020-09-09 15:50:02 -04001288 if (result->as<Type>() == *fContext.fVoid_Type) {
1289 if (!allowVoid) {
1290 fErrors.error(type.fOffset, "type '" + td.fName + "' not allowed in this context");
1291 return nullptr;
1292 }
1293 if (type.begin() != type.end()) {
1294 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be used in an array");
1295 return nullptr;
1296 }
1297 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001298 for (const auto& size : type) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001299 String name(result->name());
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001300 name += "[";
Ethan Nicholasfc994162019-06-06 10:04:27 -04001301 if (size) {
1302 name += to_string(size.getInt());
Ethan Nicholas50afc172017-02-16 14:49:57 -05001303 }
1304 name += "]";
Brian Osmane8c26082020-10-01 17:22:45 -04001305 result = fSymbolTable->takeOwnershipOfSymbol(
1306 std::make_unique<Type>(name, Type::TypeKind::kArray, result->as<Type>(),
1307 size ? size.getInt() : Type::kUnsizedArray));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001308 }
John Stiles17c5b702020-08-18 10:40:03 -04001309 return &result->as<Type>();
ethannicholasb3058bd2016-07-01 08:22:01 -07001310 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001311 fErrors.error(type.fOffset, "unknown type '" + td.fName + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001312 return nullptr;
1313}
1314
Ethan Nicholasfc994162019-06-06 10:04:27 -04001315std::unique_ptr<Expression> IRGenerator::convertExpression(const ASTNode& expr) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001316 switch (expr.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001317 case ASTNode::Kind::kBinary:
1318 return this->convertBinaryExpression(expr);
1319 case ASTNode::Kind::kBool:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001320 return std::unique_ptr<Expression>(new BoolLiteral(fContext, expr.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04001321 expr.getBool()));
1322 case ASTNode::Kind::kCall:
1323 return this->convertCallExpression(expr);
1324 case ASTNode::Kind::kField:
1325 return this->convertFieldExpression(expr);
1326 case ASTNode::Kind::kFloat:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001327 return std::unique_ptr<Expression>(new FloatLiteral(fContext, expr.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04001328 expr.getFloat()));
1329 case ASTNode::Kind::kIdentifier:
1330 return this->convertIdentifier(expr);
1331 case ASTNode::Kind::kIndex:
1332 return this->convertIndexExpression(expr);
1333 case ASTNode::Kind::kInt:
1334 return std::unique_ptr<Expression>(new IntLiteral(fContext, expr.fOffset,
1335 expr.getInt()));
1336 case ASTNode::Kind::kNull:
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001337 return std::unique_ptr<Expression>(new NullLiteral(fContext, expr.fOffset));
Ethan Nicholasfc994162019-06-06 10:04:27 -04001338 case ASTNode::Kind::kPostfix:
1339 return this->convertPostfixExpression(expr);
1340 case ASTNode::Kind::kPrefix:
1341 return this->convertPrefixExpression(expr);
Brian Osman6518d772020-09-10 16:50:06 -04001342 case ASTNode::Kind::kScope:
1343 return this->convertScopeExpression(expr);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001344 case ASTNode::Kind::kTernary:
1345 return this->convertTernaryExpression(expr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001346 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001347#ifdef SK_DEBUG
Ethan Nicholasfc994162019-06-06 10:04:27 -04001348 ABORT("unsupported expression: %s\n", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001349#endif
1350 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001351 }
1352}
1353
Ethan Nicholasfc994162019-06-06 10:04:27 -04001354std::unique_ptr<Expression> IRGenerator::convertIdentifier(const ASTNode& identifier) {
1355 SkASSERT(identifier.fKind == ASTNode::Kind::kIdentifier);
1356 const Symbol* result = (*fSymbolTable)[identifier.getString()];
ethannicholasb3058bd2016-07-01 08:22:01 -07001357 if (!result) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001358 fErrors.error(identifier.fOffset, "unknown identifier '" + identifier.getString() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001359 return nullptr;
1360 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001361 switch (result->kind()) {
1362 case Symbol::Kind::kFunctionDeclaration: {
ethannicholasd598f792016-07-25 10:08:54 -07001363 std::vector<const FunctionDeclaration*> f = {
John Stiles17c5b702020-08-18 10:40:03 -04001364 &result->as<FunctionDeclaration>()
ethannicholasb3058bd2016-07-01 08:22:01 -07001365 };
John Stilesfbd050b2020-08-03 13:21:46 -04001366 return std::make_unique<FunctionReference>(fContext, identifier.fOffset, f);
ethannicholasb3058bd2016-07-01 08:22:01 -07001367 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001368 case Symbol::Kind::kUnresolvedFunction: {
John Stiles17c5b702020-08-18 10:40:03 -04001369 const UnresolvedFunction* f = &result->as<UnresolvedFunction>();
Ethan Nicholasceb62142020-10-09 16:51:18 -04001370 return std::make_unique<FunctionReference>(fContext, identifier.fOffset,
1371 f->functions());
ethannicholasb3058bd2016-07-01 08:22:01 -07001372 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001373 case Symbol::Kind::kVariable: {
John Stiles17c5b702020-08-18 10:40:03 -04001374 const Variable* var = &result->as<Variable>();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001375 const Modifiers& modifiers = var->modifiers();
1376 switch (modifiers.fLayout.fBuiltin) {
Ethan Nicholascd700e92018-08-24 16:43:57 -04001377 case SK_WIDTH_BUILTIN:
1378 fInputs.fRTWidth = true;
1379 break;
1380 case SK_HEIGHT_BUILTIN:
Greg Daniele6ab9982018-08-22 13:56:32 +00001381 fInputs.fRTHeight = true;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001382 break;
1383#ifndef SKSL_STANDALONE
1384 case SK_FRAGCOORD_BUILTIN:
Brian Osman9f313b62019-10-02 12:03:11 -04001385 fInputs.fFlipY = true;
1386 if (fSettings->fFlipY &&
Brian Osmand7e76592020-11-02 12:26:22 -05001387 (!fCaps || !fCaps->fragCoordConventionsExtensionString())) {
Brian Osman9f313b62019-10-02 12:03:11 -04001388 fInputs.fRTHeight = true;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001389 }
Greg Daniele6ab9982018-08-22 13:56:32 +00001390#endif
Ethan Nicholascd700e92018-08-24 16:43:57 -04001391 }
Ethan Nicholas33c59ed2019-08-13 10:21:38 -04001392 if (fKind == Program::kFragmentProcessor_Kind &&
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001393 (modifiers.fFlags & Modifiers::kIn_Flag) &&
1394 !(modifiers.fFlags & Modifiers::kUniform_Flag) &&
1395 !modifiers.fLayout.fKey &&
1396 modifiers.fLayout.fBuiltin == -1 &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001397 var->type().nonnullable() != *fContext.fFragmentProcessor_Type &&
1398 var->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholas33c59ed2019-08-13 10:21:38 -04001399 bool valid = false;
1400 for (const auto& decl : fFile->root()) {
1401 if (decl.fKind == ASTNode::Kind::kSection) {
1402 ASTNode::SectionData section = decl.getSectionData();
1403 if (section.fName == "setData") {
1404 valid = true;
1405 break;
1406 }
1407 }
1408 }
1409 if (!valid) {
1410 fErrors.error(identifier.fOffset, "'in' variable must be either 'uniform' or "
1411 "'layout(key)', or there must be a custom "
1412 "@setData function");
1413 }
1414 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001415 // default to kRead_RefKind; this will be corrected later if the variable is written to
John Stilesfbd050b2020-08-03 13:21:46 -04001416 return std::make_unique<VariableReference>(identifier.fOffset,
Brian Osman79457ef2020-09-24 15:01:27 -04001417 var,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001418 VariableReference::RefKind::kRead);
ethannicholasb3058bd2016-07-01 08:22:01 -07001419 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001420 case Symbol::Kind::kField: {
John Stiles17c5b702020-08-18 10:40:03 -04001421 const Field* field = &result->as<Field>();
Brian Osman6a204db2020-10-08 09:29:02 -04001422 auto base = std::make_unique<VariableReference>(identifier.fOffset, &field->owner(),
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001423 VariableReference::RefKind::kRead);
Brian Osman6a204db2020-10-08 09:29:02 -04001424 return std::make_unique<FieldAccess>(std::move(base),
1425 field->fieldIndex(),
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001426 FieldAccess::OwnerKind::kAnonymousInterfaceBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -07001427 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001428 case Symbol::Kind::kType: {
John Stiles17c5b702020-08-18 10:40:03 -04001429 const Type* t = &result->as<Type>();
Ethan Nicholase6592142020-09-08 10:22:09 -04001430 return std::make_unique<TypeReference>(fContext, identifier.fOffset, t);
ethannicholasb3058bd2016-07-01 08:22:01 -07001431 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001432 case Symbol::Kind::kExternal: {
John Stiles17c5b702020-08-18 10:40:03 -04001433 const ExternalValue* r = &result->as<ExternalValue>();
John Stilesfbd050b2020-08-03 13:21:46 -04001434 return std::make_unique<ExternalValueReference>(identifier.fOffset, r);
Ethan Nicholas91164d12019-05-15 15:29:54 -04001435 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001436 default:
Ethan Nicholase6592142020-09-08 10:22:09 -04001437 ABORT("unsupported symbol type %d\n", (int) result->kind());
ethannicholasb3058bd2016-07-01 08:22:01 -07001438 }
Ethan Nicholasc0709392017-06-27 11:20:22 -04001439}
1440
Ethan Nicholasfc994162019-06-06 10:04:27 -04001441std::unique_ptr<Section> IRGenerator::convertSection(const ASTNode& s) {
Brian Osman16f376f2020-09-02 12:30:59 -04001442 if (fKind != Program::kFragmentProcessor_Kind) {
1443 fErrors.error(s.fOffset, "syntax error");
1444 return nullptr;
1445 }
1446
Ethan Nicholasfc994162019-06-06 10:04:27 -04001447 ASTNode::SectionData section = s.getSectionData();
John Stilesfbd050b2020-08-03 13:21:46 -04001448 return std::make_unique<Section>(s.fOffset, section.fName, section.fArgument,
1449 section.fText);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001450}
1451
Ethan Nicholas11d53972016-11-28 11:23:23 -05001452std::unique_ptr<Expression> IRGenerator::coerce(std::unique_ptr<Expression> expr,
ethannicholasd598f792016-07-25 10:08:54 -07001453 const Type& type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001454 if (!expr) {
1455 return nullptr;
1456 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001457 if (expr->type() == type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001458 return expr;
1459 }
1460 this->checkValid(*expr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001461 if (expr->type() == *fContext.fInvalid_Type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001462 return nullptr;
1463 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001464 if (!expr->coercionCost(type).isPossible(fSettings->fAllowNarrowingConversions)) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001465 fErrors.error(expr->fOffset, "expected '" + type.displayName() + "', but found '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04001466 expr->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001467 return nullptr;
1468 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001469 if (type.typeKind() == Type::TypeKind::kScalar) {
John Stiles8e3b6be2020-10-13 11:14:08 -04001470 ExpressionArray args;
ethannicholasb3058bd2016-07-01 08:22:01 -07001471 args.push_back(std::move(expr));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001472 std::unique_ptr<Expression> ctor;
1473 if (type == *fContext.fFloatLiteral_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001474 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
1475 "float"));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001476 } else if (type == *fContext.fIntLiteral_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001477 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
1478 "int"));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001479 } else {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001480 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
Ethan Nicholase2c49992020-10-05 11:49:11 -04001481 type.name()));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001482 }
1483 if (!ctor) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001484 printf("error, null identifier: %s\n", String(type.name()).c_str());
Ethan Nicholase1f55022019-02-05 17:17:40 -05001485 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001486 SkASSERT(ctor);
John Stiles8e3b6be2020-10-13 11:14:08 -04001487 return this->call(/*offset=*/-1, std::move(ctor), std::move(args));
ethannicholasb3058bd2016-07-01 08:22:01 -07001488 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001489 if (expr->kind() == Expression::Kind::kNullLiteral) {
1490 SkASSERT(type.typeKind() == Type::TypeKind::kNullable);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001491 return std::unique_ptr<Expression>(new NullLiteral(expr->fOffset, &type));
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001492 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001493 ExpressionArray args;
ethannicholas5961bc92016-10-12 06:39:56 -07001494 args.push_back(std::move(expr));
John Stiles8e3b6be2020-10-13 11:14:08 -04001495 return std::make_unique<Constructor>(/*offset=*/-1, &type, std::move(args));
ethannicholasb3058bd2016-07-01 08:22:01 -07001496}
1497
ethannicholasf789b382016-08-03 12:43:36 -07001498static bool is_matrix_multiply(const Type& left, const Type& right) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001499 if (left.typeKind() == Type::TypeKind::kMatrix) {
1500 return right.typeKind() == Type::TypeKind::kMatrix ||
1501 right.typeKind() == Type::TypeKind::kVector;
ethannicholasf789b382016-08-03 12:43:36 -07001502 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001503 return left.typeKind() == Type::TypeKind::kVector &&
1504 right.typeKind() == Type::TypeKind::kMatrix;
ethannicholasf789b382016-08-03 12:43:36 -07001505}
ethannicholasea4567c2016-10-17 11:24:37 -07001506
ethannicholasb3058bd2016-07-01 08:22:01 -07001507/**
1508 * Determines the operand and result types of a binary expression. Returns true if the expression is
1509 * legal, false otherwise. If false, the values of the out parameters are undefined.
1510 */
Ethan Nicholas11d53972016-11-28 11:23:23 -05001511static bool determine_binary_type(const Context& context,
Brian Osman0acb5b52020-09-02 13:45:47 -04001512 bool allowNarrowing,
Ethan Nicholas11d53972016-11-28 11:23:23 -05001513 Token::Kind op,
1514 const Type& left,
1515 const Type& right,
ethannicholasd598f792016-07-25 10:08:54 -07001516 const Type** outLeftType,
1517 const Type** outRightType,
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001518 const Type** outResultType) {
1519 bool isLogical = false;
Brian Osmanbf2163f2020-09-16 16:21:40 -04001520 bool isBitwise = false;
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001521 bool validMatrixOrVectorOp = false;
1522 bool isAssignment = Compiler::IsAssignment(op);
1523
ethannicholasb3058bd2016-07-01 08:22:01 -07001524 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001525 case Token::Kind::TK_EQ:
ethannicholasea4567c2016-10-17 11:24:37 -07001526 *outLeftType = &left;
1527 *outRightType = &left;
1528 *outResultType = &left;
Brian Osman0acb5b52020-09-02 13:45:47 -04001529 return right.canCoerceTo(left, allowNarrowing);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001530 case Token::Kind::TK_EQEQ: // fall through
Brian Osman0acb5b52020-09-02 13:45:47 -04001531 case Token::Kind::TK_NEQ: {
1532 CoercionCost rightToLeft = right.coercionCost(left),
1533 leftToRight = left.coercionCost(right);
1534 if (rightToLeft < leftToRight) {
1535 if (rightToLeft.isPossible(allowNarrowing)) {
1536 *outLeftType = &left;
1537 *outRightType = &left;
1538 *outResultType = context.fBool_Type.get();
1539 return true;
1540 }
1541 } else {
1542 if (leftToRight.isPossible(allowNarrowing)) {
1543 *outLeftType = &right;
1544 *outRightType = &right;
1545 *outResultType = context.fBool_Type.get();
1546 return true;
1547 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001548 }
Ethan Nicholas23463002018-03-28 15:16:15 -04001549 return false;
Brian Osman0acb5b52020-09-02 13:45:47 -04001550 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001551 case Token::Kind::TK_LT: // fall through
1552 case Token::Kind::TK_GT: // fall through
1553 case Token::Kind::TK_LTEQ: // fall through
1554 case Token::Kind::TK_GTEQ:
ethannicholasb3058bd2016-07-01 08:22:01 -07001555 isLogical = true;
1556 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001557 case Token::Kind::TK_LOGICALOR: // fall through
1558 case Token::Kind::TK_LOGICALAND: // fall through
1559 case Token::Kind::TK_LOGICALXOR: // fall through
1560 case Token::Kind::TK_LOGICALOREQ: // fall through
1561 case Token::Kind::TK_LOGICALANDEQ: // fall through
1562 case Token::Kind::TK_LOGICALXOREQ:
ethannicholasd598f792016-07-25 10:08:54 -07001563 *outLeftType = context.fBool_Type.get();
1564 *outRightType = context.fBool_Type.get();
1565 *outResultType = context.fBool_Type.get();
Brian Osman0acb5b52020-09-02 13:45:47 -04001566 return left.canCoerceTo(*context.fBool_Type, allowNarrowing) &&
1567 right.canCoerceTo(*context.fBool_Type, allowNarrowing);
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001568 case Token::Kind::TK_STAREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001569 case Token::Kind::TK_STAR:
ethannicholasf789b382016-08-03 12:43:36 -07001570 if (is_matrix_multiply(left, right)) {
1571 // determine final component type
Brian Osman3ed22a92020-09-17 15:10:25 -04001572 if (determine_binary_type(context, allowNarrowing, op,
Brian Osman0acb5b52020-09-02 13:45:47 -04001573 left.componentType(), right.componentType(),
1574 outLeftType, outRightType, outResultType)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001575 *outLeftType = &(*outResultType)->toCompound(context, left.columns(),
Brian Salomon23356442018-11-30 15:33:19 -05001576 left.rows());
Ethan Nicholas11d53972016-11-28 11:23:23 -05001577 *outRightType = &(*outResultType)->toCompound(context, right.columns(),
Brian Salomon23356442018-11-30 15:33:19 -05001578 right.rows());
ethannicholasf789b382016-08-03 12:43:36 -07001579 int leftColumns = left.columns();
1580 int leftRows = left.rows();
1581 int rightColumns;
1582 int rightRows;
Ethan Nicholase6592142020-09-08 10:22:09 -04001583 if (right.typeKind() == Type::TypeKind::kVector) {
ethannicholasf789b382016-08-03 12:43:36 -07001584 // matrix * vector treats the vector as a column vector, so we need to
1585 // transpose it
1586 rightColumns = right.rows();
1587 rightRows = right.columns();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001588 SkASSERT(rightColumns == 1);
ethannicholasf789b382016-08-03 12:43:36 -07001589 } else {
1590 rightColumns = right.columns();
1591 rightRows = right.rows();
1592 }
1593 if (rightColumns > 1) {
1594 *outResultType = &(*outResultType)->toCompound(context, rightColumns,
1595 leftRows);
1596 } else {
1597 // result was a column vector, transpose it back to a row
1598 *outResultType = &(*outResultType)->toCompound(context, leftRows,
1599 rightColumns);
1600 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001601 if (isAssignment && ((*outResultType)->columns() != leftColumns ||
1602 (*outResultType)->rows() != leftRows)) {
1603 return false;
1604 }
ethannicholasf789b382016-08-03 12:43:36 -07001605 return leftColumns == rightRows;
1606 } else {
1607 return false;
1608 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001609 }
ethannicholasea4567c2016-10-17 11:24:37 -07001610 validMatrixOrVectorOp = true;
1611 break;
Brian Osmanbf2163f2020-09-16 16:21:40 -04001612 case Token::Kind::TK_SHLEQ:
1613 case Token::Kind::TK_SHREQ:
1614 case Token::Kind::TK_BITWISEANDEQ:
1615 case Token::Kind::TK_BITWISEOREQ:
1616 case Token::Kind::TK_BITWISEXOREQ:
1617 case Token::Kind::TK_SHL:
1618 case Token::Kind::TK_SHR:
1619 case Token::Kind::TK_BITWISEAND:
1620 case Token::Kind::TK_BITWISEOR:
1621 case Token::Kind::TK_BITWISEXOR:
1622 isBitwise = true;
1623 validMatrixOrVectorOp = true;
1624 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001625 case Token::Kind::TK_PLUSEQ:
1626 case Token::Kind::TK_MINUSEQ:
1627 case Token::Kind::TK_SLASHEQ:
1628 case Token::Kind::TK_PERCENTEQ:
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001629 case Token::Kind::TK_PLUS:
1630 case Token::Kind::TK_MINUS:
1631 case Token::Kind::TK_SLASH:
1632 case Token::Kind::TK_PERCENT:
ethannicholasea4567c2016-10-17 11:24:37 -07001633 validMatrixOrVectorOp = true;
1634 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001635 case Token::Kind::TK_COMMA:
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001636 *outLeftType = &left;
1637 *outRightType = &right;
1638 *outResultType = &right;
1639 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001640 default:
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001641 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001642 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001643
1644 bool leftIsVectorOrMatrix = left.typeKind() == Type::TypeKind::kVector ||
1645 left.typeKind() == Type::TypeKind::kMatrix,
1646 rightIsVectorOrMatrix = right.typeKind() == Type::TypeKind::kVector ||
1647 right.typeKind() == Type::TypeKind::kMatrix;
1648
1649 if (leftIsVectorOrMatrix && validMatrixOrVectorOp &&
1650 right.typeKind() == Type::TypeKind::kScalar) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001651 if (determine_binary_type(context, allowNarrowing, op, left.componentType(), right,
1652 outLeftType, outRightType, outResultType)) {
ethannicholasd598f792016-07-25 10:08:54 -07001653 *outLeftType = &(*outLeftType)->toCompound(context, left.columns(), left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001654 if (!isLogical) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001655 *outResultType =
1656 &(*outResultType)->toCompound(context, left.columns(), left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001657 }
1658 return true;
1659 }
1660 return false;
1661 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001662
1663 if (!isAssignment && rightIsVectorOrMatrix && validMatrixOrVectorOp &&
1664 left.typeKind() == Type::TypeKind::kScalar) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001665 if (determine_binary_type(context, allowNarrowing, op, left, right.componentType(),
1666 outLeftType, outRightType, outResultType)) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001667 *outRightType = &(*outRightType)->toCompound(context, right.columns(), right.rows());
1668 if (!isLogical) {
1669 *outResultType =
1670 &(*outResultType)->toCompound(context, right.columns(), right.rows());
1671 }
1672 return true;
1673 }
1674 return false;
1675 }
1676
Brian Osman0acb5b52020-09-02 13:45:47 -04001677 CoercionCost rightToLeftCost = right.coercionCost(left);
1678 CoercionCost leftToRightCost = isAssignment ? CoercionCost::Impossible()
1679 : left.coercionCost(right);
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001680
1681 if ((left.typeKind() == Type::TypeKind::kScalar &&
1682 right.typeKind() == Type::TypeKind::kScalar) ||
1683 (leftIsVectorOrMatrix && validMatrixOrVectorOp)) {
Brian Osmanbf2163f2020-09-16 16:21:40 -04001684 if (isBitwise) {
1685 const Type& leftNumberType(leftIsVectorOrMatrix ? left.componentType() : left);
1686 const Type& rightNumberType(rightIsVectorOrMatrix ? right.componentType() : right);
1687 if (!leftNumberType.isInteger() || !rightNumberType.isInteger()) {
1688 return false;
1689 }
1690 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001691 if (rightToLeftCost.isPossible(allowNarrowing) && rightToLeftCost < leftToRightCost) {
1692 // Right-to-Left conversion is possible and cheaper
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001693 *outLeftType = &left;
1694 *outRightType = &left;
1695 *outResultType = &left;
Brian Osman0acb5b52020-09-02 13:45:47 -04001696 } else if (leftToRightCost.isPossible(allowNarrowing)) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001697 // Left-to-Right conversion is possible (and at least as cheap as Right-to-Left)
1698 *outLeftType = &right;
1699 *outRightType = &right;
1700 *outResultType = &right;
1701 } else {
1702 return false;
1703 }
1704 if (isLogical) {
1705 *outResultType = context.fBool_Type.get();
1706 }
1707 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001708 }
1709 return false;
1710}
1711
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001712static std::unique_ptr<Expression> short_circuit_boolean(const Context& context,
1713 const Expression& left,
1714 Token::Kind op,
1715 const Expression& right) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001716 SkASSERT(left.kind() == Expression::Kind::kBoolLiteral);
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001717 bool leftVal = left.as<BoolLiteral>().value();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001718 if (op == Token::Kind::TK_LOGICALAND) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001719 // (true && expr) -> (expr) and (false && expr) -> (false)
1720 return leftVal ? right.clone()
1721 : std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, false));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001722 } else if (op == Token::Kind::TK_LOGICALOR) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001723 // (true || expr) -> (true) and (false || expr) -> (expr)
1724 return leftVal ? std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, true))
1725 : right.clone();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001726 } else if (op == Token::Kind::TK_LOGICALXOR) {
Noah Lavine334d0ba2019-12-18 23:03:49 -05001727 // (true ^^ expr) -> !(expr) and (false ^^ expr) -> (expr)
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001728 return leftVal ? std::unique_ptr<Expression>(new PrefixExpression(
1729 Token::Kind::TK_LOGICALNOT,
1730 right.clone()))
Noah Lavine334d0ba2019-12-18 23:03:49 -05001731 : right.clone();
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001732 } else {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001733 return nullptr;
1734 }
1735}
1736
John Stilescf27b4f2020-11-06 11:37:05 -05001737template <typename T>
1738std::unique_ptr<Expression> IRGenerator::constantFoldVector(const Expression& left,
1739 Token::Kind op,
1740 const Expression& right) const {
1741 SkASSERT(left.type() == right.type());
1742 const Type& type = left.type();
1743
1744 // Handle boolean operations: == !=
1745 if (op == Token::Kind::TK_EQEQ || op == Token::Kind::TK_NEQ) {
1746 if (left.kind() == right.kind()) {
1747 bool result = left.compareConstant(fContext, right) ^ (op == Token::Kind::TK_NEQ);
1748 return std::make_unique<BoolLiteral>(fContext, left.fOffset, result);
1749 }
1750 return nullptr;
1751 }
1752
1753 // Handle floating-point arithmetic: + - * /
1754 const auto vectorComponentwiseFold = [&](auto foldFn) -> std::unique_ptr<Constructor> {
1755 ExpressionArray args;
1756 for (int i = 0; i < type.columns(); i++) {
1757 T value = foldFn(left.getVecComponent<T>(i), right.getVecComponent<T>(i));
1758 args.push_back(std::make_unique<Literal<T>>(fContext, left.fOffset, value));
1759 }
1760 return std::make_unique<Constructor>(left.fOffset, &type, std::move(args));
1761 };
1762
1763 const auto isVectorDivisionByZero = [&]() -> bool {
1764 for (int i = 0; i < type.columns(); i++) {
1765 if (right.getVecComponent<T>(i) == 0) {
1766 return true;
1767 }
1768 }
1769 return false;
1770 };
1771
1772 switch (op) {
1773 case Token::Kind::TK_PLUS: return vectorComponentwiseFold([](T a, T b) { return a + b; });
1774 case Token::Kind::TK_MINUS: return vectorComponentwiseFold([](T a, T b) { return a - b; });
1775 case Token::Kind::TK_STAR: return vectorComponentwiseFold([](T a, T b) { return a * b; });
1776 case Token::Kind::TK_SLASH: {
1777 if (isVectorDivisionByZero()) {
1778 fErrors.error(right.fOffset, "division by zero");
1779 return nullptr;
1780 }
1781 return vectorComponentwiseFold([](T a, T b) { return a / b; });
1782 }
1783 default:
1784 return nullptr;
1785 }
1786}
1787
ethannicholas08a92112016-11-09 13:26:45 -08001788std::unique_ptr<Expression> IRGenerator::constantFold(const Expression& left,
1789 Token::Kind op,
Ethan Nicholas86a43402017-01-19 13:32:00 -05001790 const Expression& right) const {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001791 // If the left side is a constant boolean literal, the right side does not need to be constant
1792 // for short circuit optimizations to allow the constant to be folded.
John Stiles95acbbc2020-11-04 16:23:26 -05001793 if (left.is<BoolLiteral>() && !right.isCompileTimeConstant()) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001794 return short_circuit_boolean(fContext, left, op, right);
John Stiles95acbbc2020-11-04 16:23:26 -05001795 } else if (right.is<BoolLiteral>() && !left.isCompileTimeConstant()) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001796 // There aren't side effects in SKSL within expressions, so (left OP right) is equivalent to
1797 // (right OP left) for short-circuit optimizations
1798 return short_circuit_boolean(fContext, right, op, left);
1799 }
1800
1801 // Other than the short-circuit cases above, constant folding requires both sides to be constant
Brian Osmanb6b95732020-06-30 11:44:27 -04001802 if (!left.isCompileTimeConstant() || !right.isCompileTimeConstant()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001803 return nullptr;
1804 }
ethannicholas08a92112016-11-09 13:26:45 -08001805 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
1806 // precision to calculate the results and hope the result makes sense. The plan is to move the
1807 // Skia caps into SkSL, so we have access to all of them including the precisions of the various
1808 // types, which will let us be more intelligent about this.
John Stiles95acbbc2020-11-04 16:23:26 -05001809 if (left.is<BoolLiteral>() && right.is<BoolLiteral>()) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001810 bool leftVal = left.as<BoolLiteral>().value();
1811 bool rightVal = right.as<BoolLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001812 bool result;
1813 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001814 case Token::Kind::TK_LOGICALAND: result = leftVal && rightVal; break;
1815 case Token::Kind::TK_LOGICALOR: result = leftVal || rightVal; break;
1816 case Token::Kind::TK_LOGICALXOR: result = leftVal ^ rightVal; break;
ethannicholas08a92112016-11-09 13:26:45 -08001817 default: return nullptr;
1818 }
John Stiles95acbbc2020-11-04 16:23:26 -05001819 return std::make_unique<BoolLiteral>(fContext, left.fOffset, result);
ethannicholas08a92112016-11-09 13:26:45 -08001820 }
John Stilesfbd050b2020-08-03 13:21:46 -04001821 #define RESULT(t, op) std::make_unique<t ## Literal>(fContext, left.fOffset, \
1822 leftVal op rightVal)
1823 #define URESULT(t, op) std::make_unique<t ## Literal>(fContext, left.fOffset, \
1824 (uint32_t) leftVal op \
1825 (uint32_t) rightVal)
John Stiles95acbbc2020-11-04 16:23:26 -05001826 if (left.is<IntLiteral>() && right.is<IntLiteral>()) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001827 int64_t leftVal = left.as<IntLiteral>().value();
1828 int64_t rightVal = right.as<IntLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001829 switch (op) {
Ethan Nicholas66869e92020-04-30 09:27:54 -04001830 case Token::Kind::TK_PLUS: return URESULT(Int, +);
1831 case Token::Kind::TK_MINUS: return URESULT(Int, -);
1832 case Token::Kind::TK_STAR: return URESULT(Int, *);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001833 case Token::Kind::TK_SLASH:
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 Nicholas9a5610e2017-01-03 15:16:29 -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_PERCENT:
Ethan Nicholas66869e92020-04-30 09:27:54 -04001844 if (leftVal == std::numeric_limits<int64_t>::min() && rightVal == -1) {
1845 fErrors.error(right.fOffset, "arithmetic overflow");
1846 return nullptr;
Ethan Nicholas2503ab62017-01-05 10:44:25 -05001847 }
Ethan Nicholas66869e92020-04-30 09:27:54 -04001848 if (!rightVal) {
1849 fErrors.error(right.fOffset, "division by zero");
1850 return nullptr;
1851 }
1852 return RESULT(Int, %);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001853 case Token::Kind::TK_BITWISEAND: return RESULT(Int, &);
1854 case Token::Kind::TK_BITWISEOR: return RESULT(Int, |);
1855 case Token::Kind::TK_BITWISEXOR: return RESULT(Int, ^);
1856 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
1857 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
1858 case Token::Kind::TK_GT: return RESULT(Bool, >);
1859 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
1860 case Token::Kind::TK_LT: return RESULT(Bool, <);
1861 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
1862 case Token::Kind::TK_SHL:
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001863 if (rightVal >= 0 && rightVal <= 31) {
Ethan Nicholase4489002020-04-29 14:00:14 -04001864 return URESULT(Int, <<);
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001865 }
1866 fErrors.error(right.fOffset, "shift value out of range");
1867 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001868 case Token::Kind::TK_SHR:
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001869 if (rightVal >= 0 && rightVal <= 31) {
Ethan Nicholase4489002020-04-29 14:00:14 -04001870 return URESULT(Int, >>);
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001871 }
1872 fErrors.error(right.fOffset, "shift value out of range");
1873 return nullptr;
1874
1875 default:
1876 return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001877 }
1878 }
John Stiles95acbbc2020-11-04 16:23:26 -05001879 if (left.is<FloatLiteral>() && right.is<FloatLiteral>()) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001880 SKSL_FLOAT leftVal = left.as<FloatLiteral>().value();
1881 SKSL_FLOAT rightVal = right.as<FloatLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001882 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001883 case Token::Kind::TK_PLUS: return RESULT(Float, +);
1884 case Token::Kind::TK_MINUS: return RESULT(Float, -);
1885 case Token::Kind::TK_STAR: return RESULT(Float, *);
1886 case Token::Kind::TK_SLASH:
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001887 if (rightVal) {
1888 return RESULT(Float, /);
1889 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001890 fErrors.error(right.fOffset, "division by zero");
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001891 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001892 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
1893 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
1894 case Token::Kind::TK_GT: return RESULT(Bool, >);
1895 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
1896 case Token::Kind::TK_LT: return RESULT(Bool, <);
1897 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
1898 default: return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001899 }
1900 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001901 const Type& leftType = left.type();
1902 const Type& rightType = right.type();
John Stilescf27b4f2020-11-06 11:37:05 -05001903 if (leftType.typeKind() == Type::TypeKind::kVector && leftType == rightType) {
1904 if (leftType.componentType().isFloat()) {
1905 return constantFoldVector<SKSL_FLOAT>(left, op, right);
1906 } else if (leftType.componentType().isInteger()) {
1907 return constantFoldVector<SKSL_INT>(left, op, right);
Ethan Nicholascb670962017-04-20 19:31:52 -04001908 }
1909 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001910 if (leftType.typeKind() == Type::TypeKind::kMatrix &&
1911 rightType.typeKind() == Type::TypeKind::kMatrix &&
Ethan Nicholase6592142020-09-08 10:22:09 -04001912 left.kind() == right.kind()) {
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001913 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001914 case Token::Kind::TK_EQEQ:
John Stiles95acbbc2020-11-04 16:23:26 -05001915 return std::make_unique<BoolLiteral>(fContext, left.fOffset,
John Stiles8e3b6be2020-10-13 11:14:08 -04001916 left.compareConstant(fContext, right));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001917 case Token::Kind::TK_NEQ:
John Stiles95acbbc2020-11-04 16:23:26 -05001918 return std::make_unique<BoolLiteral>(fContext, left.fOffset,
John Stiles8e3b6be2020-10-13 11:14:08 -04001919 !left.compareConstant(fContext, right));
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001920 default:
1921 return nullptr;
1922 }
1923 }
ethannicholas08a92112016-11-09 13:26:45 -08001924 #undef RESULT
1925 return nullptr;
1926}
1927
Ethan Nicholasfc994162019-06-06 10:04:27 -04001928std::unique_ptr<Expression> IRGenerator::convertBinaryExpression(const ASTNode& expression) {
1929 SkASSERT(expression.fKind == ASTNode::Kind::kBinary);
1930 auto iter = expression.begin();
1931 std::unique_ptr<Expression> left = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07001932 if (!left) {
1933 return nullptr;
1934 }
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001935 Token::Kind op = expression.getToken().fKind;
John Stiles4c412bc2020-10-13 11:19:41 -04001936 std::unique_ptr<Expression> right;
1937 {
1938 // Can't inline the right side of a short-circuiting boolean, because our inlining
1939 // approach runs things out of order.
1940 AutoDisableInline disableInline(this, /*canInline=*/(op != Token::Kind::TK_LOGICALAND &&
1941 op != Token::Kind::TK_LOGICALOR));
1942 right = this->convertExpression(*(iter++));
1943 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001944 if (!right) {
1945 return nullptr;
1946 }
ethannicholasd598f792016-07-25 10:08:54 -07001947 const Type* leftType;
1948 const Type* rightType;
1949 const Type* resultType;
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001950 const Type* rawLeftType;
John Stilesd0e48402020-09-22 14:00:40 -04001951 if (left->is<IntLiteral>() && right->type().isInteger()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001952 rawLeftType = &right->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001953 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001954 rawLeftType = &left->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001955 }
1956 const Type* rawRightType;
John Stilesd0e48402020-09-22 14:00:40 -04001957 if (right->is<IntLiteral>() && left->type().isInteger()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001958 rawRightType = &left->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001959 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001960 rawRightType = &right->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001961 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001962 if (!determine_binary_type(fContext, fSettings->fAllowNarrowingConversions, op,
1963 *rawLeftType, *rawRightType, &leftType, &rightType, &resultType)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001964 fErrors.error(expression.fOffset, String("type mismatch: '") +
Ethan Nicholasfc994162019-06-06 10:04:27 -04001965 Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04001966 "' cannot operate on '" + left->type().displayName() +
1967 "', '" + right->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001968 return nullptr;
1969 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001970 if (Compiler::IsAssignment(op)) {
Ethan Nicholas4fadce42020-07-30 13:29:30 -04001971 if (!this->setRefKind(*left, op != Token::Kind::TK_EQ
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001972 ? VariableReference::RefKind::kReadWrite
1973 : VariableReference::RefKind::kWrite)) {
Ethan Nicholas4fadce42020-07-30 13:29:30 -04001974 return nullptr;
1975 }
ethannicholasea4567c2016-10-17 11:24:37 -07001976 }
1977 left = this->coerce(std::move(left), *leftType);
1978 right = this->coerce(std::move(right), *rightType);
1979 if (!left || !right) {
1980 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001981 }
John Stilesa008b0f2020-08-16 08:48:02 -04001982 std::unique_ptr<Expression> result = this->constantFold(*left, op, *right);
ethannicholas08a92112016-11-09 13:26:45 -08001983 if (!result) {
John Stilesd1c4dac2020-08-11 18:50:50 -04001984 result = std::make_unique<BinaryExpression>(expression.fOffset, std::move(left), op,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001985 std::move(right), resultType);
ethannicholas08a92112016-11-09 13:26:45 -08001986 }
1987 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07001988}
1989
Ethan Nicholasfc994162019-06-06 10:04:27 -04001990std::unique_ptr<Expression> IRGenerator::convertTernaryExpression(const ASTNode& node) {
1991 SkASSERT(node.fKind == ASTNode::Kind::kTernary);
1992 auto iter = node.begin();
1993 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
ethannicholasd598f792016-07-25 10:08:54 -07001994 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -07001995 if (!test) {
1996 return nullptr;
1997 }
John Stiles4c412bc2020-10-13 11:19:41 -04001998 std::unique_ptr<Expression> ifTrue;
1999 std::unique_ptr<Expression> ifFalse;
2000 {
2001 AutoDisableInline disableInline(this);
2002 ifTrue = this->convertExpression(*(iter++));
2003 if (!ifTrue) {
2004 return nullptr;
2005 }
2006 ifFalse = this->convertExpression(*(iter++));
2007 if (!ifFalse) {
2008 return nullptr;
2009 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002010 }
ethannicholasd598f792016-07-25 10:08:54 -07002011 const Type* trueType;
2012 const Type* falseType;
2013 const Type* resultType;
Brian Osman0acb5b52020-09-02 13:45:47 -04002014 if (!determine_binary_type(fContext, fSettings->fAllowNarrowingConversions,
2015 Token::Kind::TK_EQEQ, ifTrue->type(), ifFalse->type(),
2016 &trueType, &falseType, &resultType) ||
2017 trueType != falseType) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002018 fErrors.error(node.fOffset, "ternary operator result mismatch: '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002019 ifTrue->type().displayName() + "', '" +
2020 ifFalse->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002021 return nullptr;
2022 }
Brian Osman82329002020-07-21 09:39:27 -04002023 if (trueType->nonnullable() == *fContext.fFragmentProcessor_Type) {
2024 fErrors.error(node.fOffset,
2025 "ternary expression of type '" + trueType->displayName() + "' not allowed");
2026 return nullptr;
2027 }
ethannicholasd598f792016-07-25 10:08:54 -07002028 ifTrue = this->coerce(std::move(ifTrue), *trueType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05002029 if (!ifTrue) {
2030 return nullptr;
2031 }
ethannicholasd598f792016-07-25 10:08:54 -07002032 ifFalse = this->coerce(std::move(ifFalse), *falseType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05002033 if (!ifFalse) {
2034 return nullptr;
2035 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002036 if (test->kind() == Expression::Kind::kBoolLiteral) {
ethannicholas08a92112016-11-09 13:26:45 -08002037 // static boolean test, just return one of the branches
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002038 if (test->as<BoolLiteral>().value()) {
ethannicholas08a92112016-11-09 13:26:45 -08002039 return ifTrue;
2040 } else {
2041 return ifFalse;
2042 }
2043 }
John Stiles8fa3b4e2020-09-02 11:27:23 -04002044 return std::make_unique<TernaryExpression>(node.fOffset,
2045 std::move(test),
2046 std::move(ifTrue),
2047 std::move(ifFalse));
ethannicholasb3058bd2016-07-01 08:22:01 -07002048}
2049
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002050void IRGenerator::copyIntrinsicIfNeeded(const FunctionDeclaration& function) {
Brian Osman00a8b5b2020-10-02 09:06:04 -04002051 if (const ProgramElement* found = fIntrinsics->findAndInclude(function.description())) {
Brian Osman2b469eb2020-09-21 11:32:10 -04002052 const FunctionDefinition& original = found->as<FunctionDefinition>();
John Stiles9878d9e2020-09-22 15:40:16 -04002053
2054 // Sort the referenced intrinsics into a consistent order; otherwise our output will become
2055 // non-deterministic.
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002056 std::vector<const FunctionDeclaration*> intrinsics(original.referencedIntrinsics().begin(),
2057 original.referencedIntrinsics().end());
John Stiles9878d9e2020-09-22 15:40:16 -04002058 std::sort(intrinsics.begin(), intrinsics.end(),
2059 [](const FunctionDeclaration* a, const FunctionDeclaration* b) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002060 if (a->isBuiltin() != b->isBuiltin()) {
2061 return a->isBuiltin() < b->isBuiltin();
John Stiles9878d9e2020-09-22 15:40:16 -04002062 }
2063 if (a->fOffset != b->fOffset) {
2064 return a->fOffset < b->fOffset;
2065 }
Ethan Nicholase2c49992020-10-05 11:49:11 -04002066 if (a->name() != b->name()) {
2067 return a->name() < b->name();
John Stiles9878d9e2020-09-22 15:40:16 -04002068 }
2069 return a->description() < b->description();
2070 });
2071 for (const FunctionDeclaration* f : intrinsics) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002072 this->copyIntrinsicIfNeeded(*f);
2073 }
John Stiles607d36b2020-10-19 15:00:01 -04002074
John Stiles1c823672020-10-20 10:23:50 -04002075 fProgramElements->push_back(original.clone());
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002076 }
2077}
2078
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002079std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05002080 const FunctionDeclaration& function,
John Stiles8e3b6be2020-10-13 11:14:08 -04002081 ExpressionArray arguments) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002082 if (function.isBuiltin()) {
2083 if (function.definition()) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002084 fReferencedIntrinsics.insert(&function);
2085 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002086 if (!fIsBuiltinCode && fIntrinsics) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002087 this->copyIntrinsicIfNeeded(function);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05002088 }
2089 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002090 if (function.parameters().size() != arguments.size()) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002091 String msg = "call to '" + function.name() + "' expected " +
Ethan Nicholased84b732020-10-08 11:45:44 -04002092 to_string((uint64_t) function.parameters().size()) +
ethannicholasb3058bd2016-07-01 08:22:01 -07002093 " argument";
Ethan Nicholased84b732020-10-08 11:45:44 -04002094 if (function.parameters().size() != 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002095 msg += "s";
2096 }
ethannicholas5961bc92016-10-12 06:39:56 -07002097 msg += ", but found " + to_string((uint64_t) arguments.size());
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002098 fErrors.error(offset, msg);
ethannicholasb3058bd2016-07-01 08:22:01 -07002099 return nullptr;
2100 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002101 if (fKind == Program::kPipelineStage_Kind && !function.definition() && !function.isBuiltin()) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002102 String msg = "call to undefined function '" + function.name() + "'";
Brian Osman5f6b41e2020-03-09 11:53:24 -04002103 fErrors.error(offset, msg);
2104 return nullptr;
2105 }
John Stilesfa889112020-10-12 19:03:43 -04002106 FunctionDeclaration::ParamTypes types;
ethannicholas471e8942016-10-28 09:02:46 -07002107 const Type* returnType;
2108 if (!function.determineFinalTypes(arguments, &types, &returnType)) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002109 String msg = "no match for " + function.name() + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002110 String separator;
ethannicholas471e8942016-10-28 09:02:46 -07002111 for (size_t i = 0; i < arguments.size(); i++) {
2112 msg += separator;
2113 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -04002114 msg += arguments[i]->type().displayName();
ethannicholas471e8942016-10-28 09:02:46 -07002115 }
2116 msg += ")";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002117 fErrors.error(offset, msg);
ethannicholas471e8942016-10-28 09:02:46 -07002118 return nullptr;
2119 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002120 for (size_t i = 0; i < arguments.size(); i++) {
ethannicholas471e8942016-10-28 09:02:46 -07002121 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
ethannicholasea4567c2016-10-17 11:24:37 -07002122 if (!arguments[i]) {
2123 return nullptr;
2124 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002125 const Modifiers& paramModifiers = function.parameters()[i]->modifiers();
John Stiles978674a2020-09-23 15:24:51 -04002126 if (paramModifiers.fFlags & Modifiers::kOut_Flag) {
2127 if (!this->setRefKind(*arguments[i], paramModifiers.fFlags & Modifiers::kIn_Flag
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002128 ? VariableReference::RefKind::kReadWrite
2129 : VariableReference::RefKind::kPointer)) {
John Stiles978674a2020-09-23 15:24:51 -04002130 return nullptr;
2131 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002132 }
2133 }
John Stilesea9ab822020-08-31 09:55:04 -04002134
John Stiles4c412bc2020-10-13 11:19:41 -04002135 auto funcCall = std::make_unique<FunctionCall>(offset, returnType, &function,
2136 std::move(arguments));
2137 if (fCanInline &&
2138 fInliner->isSafeToInline(funcCall->function().definition()) &&
2139 !fInliner->isLargeFunction(funcCall->function().definition())) {
2140 Inliner::InlinedCall inlinedCall = fInliner->inlineCall(funcCall.get(), fSymbolTable.get(),
2141 fCurrentFunction);
2142 if (inlinedCall.fInlinedBody) {
2143 fExtraStatements.push_back(std::move(inlinedCall.fInlinedBody));
2144 }
2145 return std::move(inlinedCall.fReplacementExpr);
2146 }
2147
2148 return std::move(funcCall);
ethannicholasb3058bd2016-07-01 08:22:01 -07002149}
2150
2151/**
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002152 * Determines the cost of coercing the arguments of a function to the required types. Cost has no
Brian Osman0acb5b52020-09-02 13:45:47 -04002153 * particular meaning other than "lower costs are preferred". Returns CoercionCost::Impossible() if
2154 * the call is not valid.
ethannicholasb3058bd2016-07-01 08:22:01 -07002155 */
Brian Osman0acb5b52020-09-02 13:45:47 -04002156CoercionCost IRGenerator::callCost(const FunctionDeclaration& function,
John Stiles8e3b6be2020-10-13 11:14:08 -04002157 const ExpressionArray& arguments) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002158 if (function.parameters().size() != arguments.size()) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002159 return CoercionCost::Impossible();
ethannicholasb3058bd2016-07-01 08:22:01 -07002160 }
John Stilesfa889112020-10-12 19:03:43 -04002161 FunctionDeclaration::ParamTypes types;
ethannicholas471e8942016-10-28 09:02:46 -07002162 const Type* ignored;
2163 if (!function.determineFinalTypes(arguments, &types, &ignored)) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002164 return CoercionCost::Impossible();
ethannicholas471e8942016-10-28 09:02:46 -07002165 }
Brian Osman0acb5b52020-09-02 13:45:47 -04002166 CoercionCost total = CoercionCost::Free();
ethannicholasb3058bd2016-07-01 08:22:01 -07002167 for (size_t i = 0; i < arguments.size(); i++) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002168 total = total + arguments[i]->coercionCost(*types[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -07002169 }
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002170 return total;
ethannicholasb3058bd2016-07-01 08:22:01 -07002171}
2172
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002173std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05002174 std::unique_ptr<Expression> functionValue,
John Stiles8e3b6be2020-10-13 11:14:08 -04002175 ExpressionArray arguments) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002176 switch (functionValue->kind()) {
2177 case Expression::Kind::kTypeReference:
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002178 return this->convertConstructor(offset,
Ethan Nicholas5194a702020-10-12 11:12:12 -04002179 functionValue->as<TypeReference>().value(),
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002180 std::move(arguments));
Ethan Nicholase6592142020-09-08 10:22:09 -04002181 case Expression::Kind::kExternalValue: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002182 const ExternalValue& v = functionValue->as<ExternalValueReference>().value();
2183 if (!v.canCall()) {
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002184 fErrors.error(offset, "this external value is not a function");
2185 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002186 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002187 int count = v.callParameterCount();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002188 if (count != (int) arguments.size()) {
2189 fErrors.error(offset, "external function expected " + to_string(count) +
2190 " arguments, but found " + to_string((int) arguments.size()));
2191 return nullptr;
2192 }
2193 static constexpr int PARAMETER_MAX = 16;
2194 SkASSERT(count < PARAMETER_MAX);
2195 const Type* types[PARAMETER_MAX];
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002196 v.getCallParameterTypes(types);
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002197 for (int i = 0; i < count; ++i) {
2198 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
2199 if (!arguments[i]) {
2200 return nullptr;
2201 }
2202 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002203 return std::make_unique<ExternalFunctionCall>(offset, &v, std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07002204 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002205 case Expression::Kind::kFunctionReference: {
John Stilesce591b72020-08-27 11:47:30 -04002206 const FunctionReference& ref = functionValue->as<FunctionReference>();
Ethan Nicholas5194a702020-10-12 11:12:12 -04002207 const std::vector<const FunctionDeclaration*>& functions = ref.functions();
Brian Osman0acb5b52020-09-02 13:45:47 -04002208 CoercionCost bestCost = CoercionCost::Impossible();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002209 const FunctionDeclaration* best = nullptr;
Ethan Nicholas5194a702020-10-12 11:12:12 -04002210 if (functions.size() > 1) {
2211 for (const auto& f : functions) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002212 CoercionCost cost = this->callCost(*f, arguments);
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002213 if (cost < bestCost) {
2214 bestCost = cost;
2215 best = f;
2216 }
2217 }
2218 if (best) {
2219 return this->call(offset, *best, std::move(arguments));
2220 }
Ethan Nicholas5194a702020-10-12 11:12:12 -04002221 String msg = "no match for " + functions[0]->name() + "(";
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002222 String separator;
2223 for (size_t i = 0; i < arguments.size(); i++) {
2224 msg += separator;
2225 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -04002226 msg += arguments[i]->type().displayName();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002227 }
2228 msg += ")";
2229 fErrors.error(offset, msg);
2230 return nullptr;
2231 }
Ethan Nicholas5194a702020-10-12 11:12:12 -04002232 return this->call(offset, *functions[0], std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07002233 }
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002234 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002235 fErrors.error(offset, "not a function");
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002236 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002237 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002238}
2239
John Stiles8e3b6be2020-10-13 11:14:08 -04002240std::unique_ptr<Expression> IRGenerator::convertNumberConstructor(int offset,
2241 const Type& type,
2242 ExpressionArray args) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04002243 SkASSERT(type.isNumber());
Ethan Nicholas84645e32017-02-09 13:57:14 -05002244 if (args.size() != 1) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002245 fErrors.error(offset, "invalid arguments to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002246 "' constructor, (expected exactly 1 argument, but found " +
2247 to_string((uint64_t) args.size()) + ")");
ethannicholasb3058bd2016-07-01 08:22:01 -07002248 return nullptr;
2249 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002250 const Type& argType = args[0]->type();
2251 if (type == argType) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002252 return std::move(args[0]);
2253 }
John Stilesd0e48402020-09-22 14:00:40 -04002254 if (type.isFloat() && args.size() == 1 && args[0]->is<FloatLiteral>()) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002255 SKSL_FLOAT value = args[0]->as<FloatLiteral>().value();
John Stilesd0e48402020-09-22 14:00:40 -04002256 return std::make_unique<FloatLiteral>(offset, value, &type);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002257 }
John Stilesd0e48402020-09-22 14:00:40 -04002258 if (type.isFloat() && args.size() == 1 && args[0]->is<IntLiteral>()) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002259 int64_t value = args[0]->as<IntLiteral>().value();
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002260 return std::make_unique<FloatLiteral>(offset, (float)value, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002261 }
John Stilesd0e48402020-09-22 14:00:40 -04002262 if (args[0]->is<IntLiteral>() && (type == *fContext.fInt_Type ||
2263 type == *fContext.fUInt_Type)) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002264 return std::make_unique<IntLiteral>(offset, args[0]->as<IntLiteral>().value(), &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002265 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002266 if (argType == *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002267 std::unique_ptr<IntLiteral> zero(new IntLiteral(fContext, offset, 0));
2268 std::unique_ptr<IntLiteral> one(new IntLiteral(fContext, offset, 1));
John Stilesd0e48402020-09-22 14:00:40 -04002269 return std::make_unique<TernaryExpression>(offset, std::move(args[0]),
2270 this->coerce(std::move(one), type),
2271 this->coerce(std::move(zero), type));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002272 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002273 if (!argType.isNumber()) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002274 fErrors.error(offset, "invalid argument to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002275 "' constructor (expected a number or bool, but found '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002276 argType.displayName() + "')");
Ethan Nicholas84645e32017-02-09 13:57:14 -05002277 return nullptr;
2278 }
John Stilesd0e48402020-09-22 14:00:40 -04002279 return std::make_unique<Constructor>(offset, &type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002280}
2281
John Stiles36374402020-08-13 12:16:44 -04002282static int component_count(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002283 switch (type.typeKind()) {
2284 case Type::TypeKind::kVector:
Ethan Nicholas84645e32017-02-09 13:57:14 -05002285 return type.columns();
Ethan Nicholase6592142020-09-08 10:22:09 -04002286 case Type::TypeKind::kMatrix:
Ethan Nicholas84645e32017-02-09 13:57:14 -05002287 return type.columns() * type.rows();
2288 default:
2289 return 1;
2290 }
2291}
2292
John Stiles8e3b6be2020-10-13 11:14:08 -04002293std::unique_ptr<Expression> IRGenerator::convertCompoundConstructor(int offset,
2294 const Type& type,
2295 ExpressionArray args) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002296 SkASSERT(type.typeKind() == Type::TypeKind::kVector ||
2297 type.typeKind() == Type::TypeKind::kMatrix);
2298 if (type.typeKind() == Type::TypeKind::kMatrix && args.size() == 1 &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04002299 args[0]->type().typeKind() == Type::TypeKind::kMatrix) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002300 // matrix from matrix is always legal
Ethan Nicholas30d30222020-09-11 12:27:26 -04002301 return std::unique_ptr<Expression>(new Constructor(offset, &type, std::move(args)));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002302 }
2303 int actual = 0;
2304 int expected = type.rows() * type.columns();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002305 if (args.size() != 1 || expected != component_count(args[0]->type()) ||
2306 type.componentType().isNumber() != args[0]->type().componentType().isNumber()) {
ethannicholas5961bc92016-10-12 06:39:56 -07002307 for (size_t i = 0; i < args.size(); i++) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002308 const Type& argType = args[i]->type();
2309 if (argType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002310 if (type.componentType().isNumber() !=
Ethan Nicholas30d30222020-09-11 12:27:26 -04002311 argType.componentType().isNumber()) {
2312 fErrors.error(offset, "'" + argType.displayName() + "' is not a valid "
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002313 "parameter to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002314 "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002315 return nullptr;
2316 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002317 actual += argType.columns();
2318 } else if (argType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002319 actual += 1;
Ethan Nicholase6592142020-09-08 10:22:09 -04002320 if (type.typeKind() != Type::TypeKind::kScalar) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002321 args[i] = this->coerce(std::move(args[i]), type.componentType());
2322 if (!args[i]) {
2323 return nullptr;
2324 }
2325 }
2326 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002327 fErrors.error(offset, "'" + argType.displayName() + "' is not a valid "
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002328 "parameter to '" + type.displayName() + "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002329 return nullptr;
2330 }
2331 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05002332 if (actual != 1 && actual != expected) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002333 fErrors.error(offset, "invalid arguments to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002334 "' constructor (expected " + to_string(expected) +
2335 " scalars, but found " + to_string(actual) + ")");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002336 return nullptr;
2337 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002338 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002339 return std::unique_ptr<Expression>(new Constructor(offset, &type, std::move(args)));
ethannicholasb3058bd2016-07-01 08:22:01 -07002340}
2341
John Stiles8e3b6be2020-10-13 11:14:08 -04002342std::unique_ptr<Expression> IRGenerator::convertConstructor(int offset,
2343 const Type& type,
2344 ExpressionArray args) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002345 // FIXME: add support for structs
Ethan Nicholas30d30222020-09-11 12:27:26 -04002346 if (args.size() == 1 && args[0]->type() == type &&
Brian Osman82329002020-07-21 09:39:27 -04002347 type.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002348 // argument is already the right type, just return it
2349 return std::move(args[0]);
2350 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002351 Type::TypeKind kind = type.typeKind();
Ethan Nicholas84645e32017-02-09 13:57:14 -05002352 if (type.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002353 return this->convertNumberConstructor(offset, type, std::move(args));
Ethan Nicholase6592142020-09-08 10:22:09 -04002354 } else if (kind == Type::TypeKind::kArray) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002355 const Type& base = type.componentType();
2356 for (size_t i = 0; i < args.size(); i++) {
2357 args[i] = this->coerce(std::move(args[i]), base);
2358 if (!args[i]) {
2359 return nullptr;
2360 }
2361 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002362 return std::make_unique<Constructor>(offset, &type, std::move(args));
Ethan Nicholase6592142020-09-08 10:22:09 -04002363 } else if (kind == Type::TypeKind::kVector || kind == Type::TypeKind::kMatrix) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002364 return this->convertCompoundConstructor(offset, type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002365 } else {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002366 fErrors.error(offset, "cannot construct '" + type.displayName() + "'");
Ethan Nicholas84645e32017-02-09 13:57:14 -05002367 return nullptr;
2368 }
2369}
2370
Ethan Nicholasfc994162019-06-06 10:04:27 -04002371std::unique_ptr<Expression> IRGenerator::convertPrefixExpression(const ASTNode& expression) {
2372 SkASSERT(expression.fKind == ASTNode::Kind::kPrefix);
2373 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
ethannicholasb3058bd2016-07-01 08:22:01 -07002374 if (!base) {
2375 return nullptr;
2376 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002377 const Type& baseType = base->type();
Ethan Nicholasfc994162019-06-06 10:04:27 -04002378 switch (expression.getToken().fKind) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002379 case Token::Kind::TK_PLUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002380 if (!baseType.isNumber() && baseType.typeKind() != Type::TypeKind::kVector &&
2381 baseType != *fContext.fFloatLiteral_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002382 fErrors.error(expression.fOffset,
Ethan Nicholas30d30222020-09-11 12:27:26 -04002383 "'+' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002384 return nullptr;
2385 }
2386 return base;
John Stiles978674a2020-09-23 15:24:51 -04002387
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002388 case Token::Kind::TK_MINUS:
John Stiles978674a2020-09-23 15:24:51 -04002389 if (base->is<IntLiteral>()) {
2390 return std::make_unique<IntLiteral>(fContext, base->fOffset,
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002391 -base->as<IntLiteral>().value());
ethannicholasb3058bd2016-07-01 08:22:01 -07002392 }
John Stiles978674a2020-09-23 15:24:51 -04002393 if (base->is<FloatLiteral>()) {
2394 return std::make_unique<FloatLiteral>(fContext, base->fOffset,
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002395 -base->as<FloatLiteral>().value());
ethannicholasb3058bd2016-07-01 08:22:01 -07002396 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002397 if (!baseType.isNumber() && baseType.typeKind() != Type::TypeKind::kVector) {
Ethan Nicholase1f55022019-02-05 17:17:40 -05002398 fErrors.error(expression.fOffset,
Ethan Nicholas30d30222020-09-11 12:27:26 -04002399 "'-' cannot operate on '" + baseType.displayName() + "'");
Ethan Nicholase1f55022019-02-05 17:17:40 -05002400 return nullptr;
2401 }
John Stiles978674a2020-09-23 15:24:51 -04002402 return std::make_unique<PrefixExpression>(Token::Kind::TK_MINUS, std::move(base));
2403
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002404 case Token::Kind::TK_PLUSPLUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002405 if (!baseType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002406 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002407 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002408 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002409 return nullptr;
2410 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002411 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002412 return nullptr;
2413 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002414 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002415 case Token::Kind::TK_MINUSMINUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002416 if (!baseType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002417 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002418 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002419 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002420 return nullptr;
2421 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002422 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002423 return nullptr;
2424 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002425 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002426 case Token::Kind::TK_LOGICALNOT:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002427 if (baseType != *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002428 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002429 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002430 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002431 return nullptr;
2432 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002433 if (base->kind() == Expression::Kind::kBoolLiteral) {
John Stiles978674a2020-09-23 15:24:51 -04002434 return std::make_unique<BoolLiteral>(fContext, base->fOffset,
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002435 !base->as<BoolLiteral>().value());
ethannicholas08a92112016-11-09 13:26:45 -08002436 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002437 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002438 case Token::Kind::TK_BITWISENOT:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002439 if (baseType != *fContext.fInt_Type && baseType != *fContext.fUInt_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002440 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002441 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002442 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholas5961bc92016-10-12 06:39:56 -07002443 return nullptr;
2444 }
2445 break;
Ethan Nicholas11d53972016-11-28 11:23:23 -05002446 default:
ethannicholasb3058bd2016-07-01 08:22:01 -07002447 ABORT("unsupported prefix operator\n");
2448 }
John Stiles978674a2020-09-23 15:24:51 -04002449 return std::make_unique<PrefixExpression>(expression.getToken().fKind, std::move(base));
ethannicholasb3058bd2016-07-01 08:22:01 -07002450}
2451
2452std::unique_ptr<Expression> IRGenerator::convertIndex(std::unique_ptr<Expression> base,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002453 const ASTNode& index) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002454 if (base->kind() == Expression::Kind::kTypeReference) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002455 if (index.fKind == ASTNode::Kind::kInt) {
Ethan Nicholas5194a702020-10-12 11:12:12 -04002456 const Type& oldType = base->as<TypeReference>().value();
Ethan Nicholasfc994162019-06-06 10:04:27 -04002457 SKSL_INT size = index.getInt();
John Stiles3ae071e2020-08-05 15:29:29 -04002458 const Type* newType = fSymbolTable->takeOwnershipOfSymbol(
2459 std::make_unique<Type>(oldType.name() + "[" + to_string(size) + "]",
Ethan Nicholase6592142020-09-08 10:22:09 -04002460 Type::TypeKind::kArray, oldType, size));
2461 return std::make_unique<TypeReference>(fContext, base->fOffset, newType);
Ethan Nicholas50afc172017-02-16 14:49:57 -05002462
2463 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002464 fErrors.error(base->fOffset, "array size must be a constant");
Ethan Nicholas50afc172017-02-16 14:49:57 -05002465 return nullptr;
2466 }
2467 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002468 const Type& baseType = base->type();
2469 if (baseType.typeKind() != Type::TypeKind::kArray &&
2470 baseType.typeKind() != Type::TypeKind::kMatrix &&
2471 baseType.typeKind() != Type::TypeKind::kVector) {
2472 fErrors.error(base->fOffset, "expected array, but found '" + baseType.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002473 "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002474 return nullptr;
2475 }
2476 std::unique_ptr<Expression> converted = this->convertExpression(index);
2477 if (!converted) {
2478 return nullptr;
2479 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002480 if (converted->type() != *fContext.fUInt_Type) {
ethannicholas5961bc92016-10-12 06:39:56 -07002481 converted = this->coerce(std::move(converted), *fContext.fInt_Type);
2482 if (!converted) {
2483 return nullptr;
2484 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002485 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002486 return std::make_unique<IndexExpression>(fContext, std::move(base), std::move(converted));
ethannicholasb3058bd2016-07-01 08:22:01 -07002487}
2488
2489std::unique_ptr<Expression> IRGenerator::convertField(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002490 StringFragment field) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002491 if (base->kind() == Expression::Kind::kExternalValue) {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002492 const ExternalValue& ev = base->as<ExternalValueReference>().value();
Ethan Nicholas91164d12019-05-15 15:29:54 -04002493 ExternalValue* result = ev.getChild(String(field).c_str());
2494 if (!result) {
2495 fErrors.error(base->fOffset, "external value does not have a child named '" + field +
2496 "'");
2497 return nullptr;
2498 }
2499 return std::unique_ptr<Expression>(new ExternalValueReference(base->fOffset, result));
2500 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002501 const Type& baseType = base->type();
2502 auto fields = baseType.fields();
ethannicholasb3058bd2016-07-01 08:22:01 -07002503 for (size_t i = 0; i < fields.size(); i++) {
2504 if (fields[i].fName == field) {
2505 return std::unique_ptr<Expression>(new FieldAccess(std::move(base), (int) i));
2506 }
2507 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002508 fErrors.error(base->fOffset, "type '" + baseType.displayName() + "' does not have a field "
John Stiles68861e32020-09-25 16:02:07 -04002509 "named '" + field + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002510 return nullptr;
2511}
2512
Brian Osman25647672020-09-15 15:16:56 -04002513// Swizzles are complicated due to constant components. The most difficult case is a mask like
John Stiles6e49a372020-09-16 13:40:54 -04002514// '.x1w0'. A naive approach might turn that into 'float4(base.x, 1, base.w, 0)', but that evaluates
2515// 'base' twice. We instead group the swizzle mask ('xw') and constants ('1, 0') together and use a
Brian Osman25647672020-09-15 15:16:56 -04002516// 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 -04002517// 'float4(base.xw, 1, 0).xzyw'.
ethannicholasb3058bd2016-07-01 08:22:01 -07002518std::unique_ptr<Expression> IRGenerator::convertSwizzle(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002519 StringFragment fields) {
Brian Osman25647672020-09-15 15:16:56 -04002520 const int offset = base->fOffset;
Ethan Nicholas30d30222020-09-11 12:27:26 -04002521 const Type& baseType = base->type();
2522 if (baseType.typeKind() != Type::TypeKind::kVector && !baseType.isNumber()) {
Brian Osman25647672020-09-15 15:16:56 -04002523 fErrors.error(offset, "cannot swizzle value of type '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002524 return nullptr;
2525 }
Brian Osman25647672020-09-15 15:16:56 -04002526
2527 if (fields.fLength > 4) {
2528 fErrors.error(offset, "too many components in swizzle mask '" + fields + "'");
2529 return nullptr;
2530 }
2531
John Stiles750109b2020-10-30 13:45:46 -04002532 ComponentArray maskComponents;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002533 for (size_t i = 0; i < fields.fLength; i++) {
Ethan Nicholas9e1138d2016-11-21 10:39:35 -05002534 switch (fields[i]) {
Ethan Nicholasac285b12019-02-12 16:05:18 -05002535 case '0':
Ethan Nicholasac285b12019-02-12 16:05:18 -05002536 case '1':
John Stiles6e49a372020-09-16 13:40:54 -04002537 // Skip over constant fields for now.
Ethan Nicholasac285b12019-02-12 16:05:18 -05002538 break;
Ethan Nicholase455f652019-09-13 12:52:55 -04002539 case 'x':
2540 case 'r':
Ethan Nicholas11d53972016-11-28 11:23:23 -05002541 case 's':
Ethan Nicholase455f652019-09-13 12:52:55 -04002542 case 'L':
Brian Osman25647672020-09-15 15:16:56 -04002543 maskComponents.push_back(0);
ethannicholasb3058bd2016-07-01 08:22:01 -07002544 break;
Ethan Nicholase455f652019-09-13 12:52:55 -04002545 case 'y':
2546 case 'g':
ethannicholasb3058bd2016-07-01 08:22:01 -07002547 case 't':
Ethan Nicholase455f652019-09-13 12:52:55 -04002548 case 'T':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002549 if (baseType.columns() >= 2) {
Brian Osman25647672020-09-15 15:16:56 -04002550 maskComponents.push_back(1);
ethannicholasb3058bd2016-07-01 08:22:01 -07002551 break;
2552 }
John Stiles30212b72020-06-11 17:55:07 -04002553 [[fallthrough]];
Ethan Nicholase455f652019-09-13 12:52:55 -04002554 case 'z':
2555 case 'b':
Ethan Nicholas11d53972016-11-28 11:23:23 -05002556 case 'p':
Ethan Nicholase455f652019-09-13 12:52:55 -04002557 case 'R':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002558 if (baseType.columns() >= 3) {
Brian Osman25647672020-09-15 15:16:56 -04002559 maskComponents.push_back(2);
ethannicholasb3058bd2016-07-01 08:22:01 -07002560 break;
2561 }
John Stiles30212b72020-06-11 17:55:07 -04002562 [[fallthrough]];
Ethan Nicholase455f652019-09-13 12:52:55 -04002563 case 'w':
2564 case 'a':
ethannicholasb3058bd2016-07-01 08:22:01 -07002565 case 'q':
Ethan Nicholase455f652019-09-13 12:52:55 -04002566 case 'B':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002567 if (baseType.columns() >= 4) {
Brian Osman25647672020-09-15 15:16:56 -04002568 maskComponents.push_back(3);
ethannicholasb3058bd2016-07-01 08:22:01 -07002569 break;
2570 }
John Stiles30212b72020-06-11 17:55:07 -04002571 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -07002572 default:
Brian Osman25647672020-09-15 15:16:56 -04002573 fErrors.error(offset, String::printf("invalid swizzle component '%c'", fields[i]));
ethannicholasb3058bd2016-07-01 08:22:01 -07002574 return nullptr;
2575 }
2576 }
Brian Osman25647672020-09-15 15:16:56 -04002577 if (maskComponents.empty()) {
2578 fErrors.error(offset, "swizzle must refer to base expression");
ethannicholasb3058bd2016-07-01 08:22:01 -07002579 return nullptr;
2580 }
Brian Osman25647672020-09-15 15:16:56 -04002581
2582 // First, we need a vector expression that is the non-constant portion of the swizzle, packed:
2583 // scalar.xxx -> type3(scalar)
2584 // scalar.x0x0 -> type2(scalar)
2585 // vector.zyx -> vector.zyx
2586 // vector.x0y0 -> vector.xy
2587 std::unique_ptr<Expression> expr;
Ethan Nicholas30d30222020-09-11 12:27:26 -04002588 if (baseType.isNumber()) {
John Stiles8e3b6be2020-10-13 11:14:08 -04002589 ExpressionArray scalarConstructorArgs;
Brian Osman25647672020-09-15 15:16:56 -04002590 scalarConstructorArgs.push_back(std::move(base));
2591 expr = std::make_unique<Constructor>(
2592 offset, &baseType.toCompound(fContext, maskComponents.size(), 1),
2593 std::move(scalarConstructorArgs));
2594 } else {
2595 expr = std::make_unique<Swizzle>(fContext, std::move(base), maskComponents);
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002596 }
Brian Osman25647672020-09-15 15:16:56 -04002597
John Stiles6e49a372020-09-16 13:40:54 -04002598 // If we have processed the entire swizzle, we're done.
2599 if (maskComponents.size() == fields.fLength) {
Brian Osman25647672020-09-15 15:16:56 -04002600 return expr;
2601 }
2602
2603 // Now we create a constructor that has the correct number of elements for the final swizzle,
John Stiles6e49a372020-09-16 13:40:54 -04002604 // with all fields at the start. It's not finished yet; constants we need will be added below.
2605 // scalar.x0x0 -> type4(type2(x), ...)
2606 // vector.y111 -> type4(vector.y, ...)
2607 // vector.z10x -> type4(vector.zx, ...)
Brian Osman25647672020-09-15 15:16:56 -04002608 //
John Stiles6e49a372020-09-16 13:40:54 -04002609 // We could create simpler IR in some cases by reordering here, if all fields are packed
Brian Osman25647672020-09-15 15:16:56 -04002610 // contiguously. The benefits are minor, so skip the optimization to keep the algorithm simple.
John Stiles6e49a372020-09-16 13:40:54 -04002611 // The constructor will have at most three arguments: { base value, constant 0, constant 1 }
John Stiles8e3b6be2020-10-13 11:14:08 -04002612 ExpressionArray constructorArgs;
John Stilesf4bda742020-10-14 16:57:41 -04002613 constructorArgs.reserve_back(3);
Brian Osman25647672020-09-15 15:16:56 -04002614 constructorArgs.push_back(std::move(expr));
John Stiles6e49a372020-09-16 13:40:54 -04002615
2616 // Apply another swizzle to shuffle the constants into the correct place. Any constant values we
2617 // need are also tacked on to the end of the constructor.
2618 // scalar.x0x0 -> type4(type2(x), 0).xyxy
2619 // vector.y111 -> type4(vector.y, 1).xyyy
2620 // vector.z10x -> type4(vector.zx, 1, 0).xzwy
Brian Osman25647672020-09-15 15:16:56 -04002621 const Type* numberType = baseType.isNumber() ? &baseType : &baseType.componentType();
John Stiles750109b2020-10-30 13:45:46 -04002622 ComponentArray swizzleComponents;
John Stiles6e49a372020-09-16 13:40:54 -04002623 int maskFieldIdx = 0;
2624 int constantFieldIdx = maskComponents.size();
2625 int constantZeroIdx = -1, constantOneIdx = -1;
Brian Osman25647672020-09-15 15:16:56 -04002626
Brian Osman25647672020-09-15 15:16:56 -04002627 for (size_t i = 0; i < fields.fLength; i++) {
John Stiles6e49a372020-09-16 13:40:54 -04002628 switch (fields[i]) {
2629 case '0':
2630 if (constantZeroIdx == -1) {
John Stilesd0e48402020-09-22 14:00:40 -04002631 // Synthesize a 'type(0)' argument at the end of the constructor.
John Stiles8e3b6be2020-10-13 11:14:08 -04002632 auto zero = std::make_unique<Constructor>(offset, numberType,
2633 ExpressionArray{});
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002634 zero->arguments().push_back(std::make_unique<IntLiteral>(fContext, offset,
2635 /*fValue=*/0));
John Stilesd0e48402020-09-22 14:00:40 -04002636 constructorArgs.push_back(std::move(zero));
John Stiles6e49a372020-09-16 13:40:54 -04002637 constantZeroIdx = constantFieldIdx++;
2638 }
2639 swizzleComponents.push_back(constantZeroIdx);
2640 break;
2641 case '1':
2642 if (constantOneIdx == -1) {
John Stilesd0e48402020-09-22 14:00:40 -04002643 // Synthesize a 'type(1)' argument at the end of the constructor.
John Stiles8e3b6be2020-10-13 11:14:08 -04002644 auto one = std::make_unique<Constructor>(offset, numberType, ExpressionArray{});
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002645 one->arguments().push_back(std::make_unique<IntLiteral>(fContext, offset,
2646 /*fValue=*/1));
John Stilesd0e48402020-09-22 14:00:40 -04002647 constructorArgs.push_back(std::move(one));
John Stiles6e49a372020-09-16 13:40:54 -04002648 constantOneIdx = constantFieldIdx++;
2649 }
2650 swizzleComponents.push_back(constantOneIdx);
2651 break;
2652 default:
2653 // The non-constant fields are already in the expected order.
2654 swizzleComponents.push_back(maskFieldIdx++);
2655 break;
Brian Osman25647672020-09-15 15:16:56 -04002656 }
2657 }
2658
John Stiles6e49a372020-09-16 13:40:54 -04002659 expr = std::make_unique<Constructor>(offset,
2660 &numberType->toCompound(fContext, constantFieldIdx, 1),
2661 std::move(constructorArgs));
2662
John Stilesb23ea382020-09-16 13:41:14 -04002663 // For some of our most common use cases ('.xyz0', '.xyz1'), we will now have an identity
2664 // swizzle; in those cases we can just return the constructor without the swizzle attached.
2665 for (size_t i = 0; i < swizzleComponents.size(); ++i) {
2666 if (swizzleComponents[i] != int(i)) {
2667 // The swizzle has an effect, so apply it.
John Stiles750109b2020-10-30 13:45:46 -04002668 return std::make_unique<Swizzle>(fContext, std::move(expr), swizzleComponents);
John Stilesb23ea382020-09-16 13:41:14 -04002669 }
2670 }
2671
2672 // The swizzle was a no-op; return the constructor expression directly.
2673 return expr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002674}
2675
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002676const Type* IRGenerator::typeForSetting(int offset, String name) const {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002677 auto found = fCapsMap.find(name);
2678 if (found == fCapsMap.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002679 fErrors.error(offset, "unknown capability flag '" + name + "'");
Ethan Nicholas3605ace2016-11-21 15:59:48 -05002680 return nullptr;
2681 }
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002682 switch (found->second.fKind) {
2683 case Program::Settings::Value::kBool_Kind: return fContext.fBool_Type.get();
2684 case Program::Settings::Value::kFloat_Kind: return fContext.fFloat_Type.get();
2685 case Program::Settings::Value::kInt_Kind: return fContext.fInt_Type.get();
2686 }
2687 SkUNREACHABLE;
2688 return nullptr;
2689}
2690
2691std::unique_ptr<Expression> IRGenerator::valueForSetting(int offset, String name) const {
2692 auto found = fCapsMap.find(name);
2693 if (found == fCapsMap.end()) {
2694 fErrors.error(offset, "unknown capability flag '" + name + "'");
2695 return nullptr;
2696 }
2697 return found->second.literal(fContext, offset);
Ethan Nicholas762466e2017-06-29 10:03:38 -04002698}
2699
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002700std::unique_ptr<Expression> IRGenerator::convertTypeField(int offset, const Type& type,
2701 StringFragment field) {
Brian Osman1313d1a2020-09-08 10:34:30 -04002702 // Find the Enum element that this type refers to (if any)
Brian Osman2b469eb2020-09-21 11:32:10 -04002703 const ProgramElement* enumElement = nullptr;
2704 for (const auto& e : *fProgramElements) {
Ethan Nicholasd83ded82020-09-29 17:05:54 -04002705 if (e->is<Enum>() && type.name() == e->as<Enum>().typeName()) {
Brian Osman2b469eb2020-09-21 11:32:10 -04002706 enumElement = e.get();
2707 break;
Brian Osman1313d1a2020-09-08 10:34:30 -04002708 }
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002709 }
Brian Osman1313d1a2020-09-08 10:34:30 -04002710
2711 if (enumElement) {
2712 // We found the Enum element. Look for 'field' as a member.
2713 std::shared_ptr<SymbolTable> old = fSymbolTable;
Ethan Nicholasd83ded82020-09-29 17:05:54 -04002714 fSymbolTable = enumElement->as<Enum>().symbols();
Brian Osman1313d1a2020-09-08 10:34:30 -04002715 std::unique_ptr<Expression> result = convertIdentifier(
2716 ASTNode(&fFile->fNodes, offset, ASTNode::Kind::kIdentifier, field));
2717 if (result) {
Ethan Nicholas78686922020-10-08 06:46:27 -04002718 const Variable& v = *result->as<VariableReference>().variable();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002719 SkASSERT(v.initialValue());
Brian Osman1313d1a2020-09-08 10:34:30 -04002720 result = std::make_unique<IntLiteral>(
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002721 offset, v.initialValue()->as<IntLiteral>().value(), &type);
Brian Osman1313d1a2020-09-08 10:34:30 -04002722 } else {
2723 fErrors.error(offset,
Ethan Nicholase2c49992020-10-05 11:49:11 -04002724 "type '" + type.name() + "' does not have a member named '" + field +
2725 "'");
Brian Osman1313d1a2020-09-08 10:34:30 -04002726 }
2727 fSymbolTable = old;
2728 return result;
2729 } else {
2730 // No Enum element? Check the intrinsics, clone it into the program, try again.
Brian Osman00a8b5b2020-10-02 09:06:04 -04002731 if (!fIsBuiltinCode && fIntrinsics) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002732 if (const ProgramElement* found = fIntrinsics->findAndInclude(type.name())) {
Brian Osman00a8b5b2020-10-02 09:06:04 -04002733 fProgramElements->push_back(found->clone());
2734 return this->convertTypeField(offset, type, field);
2735 }
Ethan Nicholasdb80f692019-11-22 14:06:12 -05002736 }
Brian Osman1313d1a2020-09-08 10:34:30 -04002737 fErrors.error(offset,
Ethan Nicholase2c49992020-10-05 11:49:11 -04002738 "type '" + type.displayName() + "' does not have a member named '" + field +
2739 "'");
Brian Osman1313d1a2020-09-08 10:34:30 -04002740 return nullptr;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002741 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002742}
2743
Ethan Nicholasfc994162019-06-06 10:04:27 -04002744std::unique_ptr<Expression> IRGenerator::convertIndexExpression(const ASTNode& index) {
2745 SkASSERT(index.fKind == ASTNode::Kind::kIndex);
2746 auto iter = index.begin();
2747 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07002748 if (!base) {
2749 return nullptr;
2750 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002751 if (iter != index.end()) {
2752 return this->convertIndex(std::move(base), *(iter++));
Ethan Nicholase6592142020-09-08 10:22:09 -04002753 } else if (base->kind() == Expression::Kind::kTypeReference) {
Ethan Nicholas5194a702020-10-12 11:12:12 -04002754 const Type& oldType = base->as<TypeReference>().value();
John Stiles3ae071e2020-08-05 15:29:29 -04002755 const Type* newType = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
Brian Osmane8c26082020-10-01 17:22:45 -04002756 oldType.name() + "[]", Type::TypeKind::kArray, oldType, Type::kUnsizedArray));
Ethan Nicholase6592142020-09-08 10:22:09 -04002757 return std::make_unique<TypeReference>(fContext, base->fOffset, newType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002758 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002759 fErrors.error(index.fOffset, "'[]' must follow a type name");
2760 return nullptr;
2761}
2762
2763std::unique_ptr<Expression> IRGenerator::convertCallExpression(const ASTNode& callNode) {
2764 SkASSERT(callNode.fKind == ASTNode::Kind::kCall);
2765 auto iter = callNode.begin();
2766 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
2767 if (!base) {
2768 return nullptr;
2769 }
John Stiles8e3b6be2020-10-13 11:14:08 -04002770 ExpressionArray arguments;
Ethan Nicholasfc994162019-06-06 10:04:27 -04002771 for (; iter != callNode.end(); ++iter) {
2772 std::unique_ptr<Expression> converted = this->convertExpression(*iter);
2773 if (!converted) {
2774 return nullptr;
2775 }
2776 arguments.push_back(std::move(converted));
2777 }
2778 return this->call(callNode.fOffset, std::move(base), std::move(arguments));
2779}
2780
2781std::unique_ptr<Expression> IRGenerator::convertFieldExpression(const ASTNode& fieldNode) {
2782 std::unique_ptr<Expression> base = this->convertExpression(*fieldNode.begin());
2783 if (!base) {
2784 return nullptr;
2785 }
2786 StringFragment field = fieldNode.getString();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002787 const Type& baseType = base->type();
2788 if (baseType == *fContext.fSkCaps_Type) {
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002789 const Type* type = this->typeForSetting(fieldNode.fOffset, field);
2790 if (!type) {
2791 return nullptr;
2792 }
2793 return std::make_unique<Setting>(fieldNode.fOffset, field, type);
Ethan Nicholasfc994162019-06-06 10:04:27 -04002794 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002795 if (base->kind() == Expression::Kind::kExternalValue) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002796 return this->convertField(std::move(base), field);
2797 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002798 switch (baseType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002799 case Type::TypeKind::kOther:
2800 case Type::TypeKind::kStruct:
Ethan Nicholasfc994162019-06-06 10:04:27 -04002801 return this->convertField(std::move(base), field);
2802 default:
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002803 return this->convertSwizzle(std::move(base), field);
Ethan Nicholasfc994162019-06-06 10:04:27 -04002804 }
2805}
2806
Brian Osman6518d772020-09-10 16:50:06 -04002807std::unique_ptr<Expression> IRGenerator::convertScopeExpression(const ASTNode& scopeNode) {
2808 std::unique_ptr<Expression> base = this->convertExpression(*scopeNode.begin());
2809 if (!base) {
2810 return nullptr;
2811 }
2812 if (!base->is<TypeReference>()) {
2813 fErrors.error(scopeNode.fOffset, "'::' must follow a type name");
2814 return nullptr;
2815 }
2816 StringFragment member = scopeNode.getString();
Ethan Nicholas5194a702020-10-12 11:12:12 -04002817 return this->convertTypeField(base->fOffset, base->as<TypeReference>().value(), member);
Brian Osman6518d772020-09-10 16:50:06 -04002818}
2819
Ethan Nicholasfc994162019-06-06 10:04:27 -04002820std::unique_ptr<Expression> IRGenerator::convertPostfixExpression(const ASTNode& expression) {
2821 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
2822 if (!base) {
2823 return nullptr;
2824 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002825 const Type& baseType = base->type();
2826 if (!baseType.isNumber()) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002827 fErrors.error(expression.fOffset,
2828 "'" + String(Compiler::OperatorName(expression.getToken().fKind)) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002829 "' cannot operate on '" + baseType.displayName() + "'");
Ethan Nicholasfc994162019-06-06 10:04:27 -04002830 return nullptr;
2831 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002832 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002833 return nullptr;
2834 }
2835 return std::make_unique<PostfixExpression>(std::move(base), expression.getToken().fKind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002836}
2837
2838void IRGenerator::checkValid(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002839 switch (expr.kind()) {
2840 case Expression::Kind::kFunctionReference:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002841 fErrors.error(expr.fOffset, "expected '(' to begin function call");
ethannicholasb3058bd2016-07-01 08:22:01 -07002842 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002843 case Expression::Kind::kTypeReference:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002844 fErrors.error(expr.fOffset, "expected '(' to begin constructor invocation");
ethannicholasb3058bd2016-07-01 08:22:01 -07002845 break;
2846 default:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002847 if (expr.type() == *fContext.fInvalid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002848 fErrors.error(expr.fOffset, "invalid expression");
ethannicholasea4567c2016-10-17 11:24:37 -07002849 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002850 }
2851}
2852
John Stilesdce4d3e2020-09-25 14:35:13 -04002853bool IRGenerator::setRefKind(Expression& expr, VariableReference::RefKind kind) {
John Stilesa976da72020-09-25 23:06:26 -04002854 VariableReference* assignableVar = nullptr;
2855 if (!Analysis::IsAssignable(expr, &assignableVar, &fErrors)) {
John Stilesdce4d3e2020-09-25 14:35:13 -04002856 return false;
2857 }
John Stilesa976da72020-09-25 23:06:26 -04002858 if (assignableVar) {
2859 assignableVar->setRefKind(kind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002860 }
Ethan Nicholascb0f4092019-04-19 11:26:50 -04002861 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07002862}
2863
Brian Osman8e2ef022020-09-30 13:26:43 -04002864void IRGenerator::cloneBuiltinVariables() {
2865 class BuiltinVariableRemapper : public ProgramWriter {
2866 public:
2867 BuiltinVariableRemapper(IRGenerator* generator) : fGenerator(generator) {}
2868
Brian Osman00a8b5b2020-10-02 09:06:04 -04002869 void cloneVariable(const String& name) {
2870 // If this is the *first* time we've seen this builtin, findAndInclude will return
2871 // the corresponding ProgramElement.
Brian Osmanafa18ee2020-10-07 17:47:45 -04002872 if (const ProgramElement* sharedDecl = fGenerator->fIntrinsics->findAndInclude(name)) {
2873 SkASSERT(sharedDecl->is<GlobalVarDeclaration>() ||
2874 sharedDecl->is<InterfaceBlock>());
Brian Osman00a8b5b2020-10-02 09:06:04 -04002875
Brian Osmanafa18ee2020-10-07 17:47:45 -04002876 // Clone the ProgramElement that declares this variable
2877 std::unique_ptr<ProgramElement> clonedDecl = sharedDecl->clone();
2878 const Variable* sharedVar = nullptr;
2879 const Expression* initialValue = nullptr;
2880
2881 if (clonedDecl->is<GlobalVarDeclaration>()) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002882 GlobalVarDeclaration& global = clonedDecl->as<GlobalVarDeclaration>();
2883 VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2884 sharedVar = &decl.var();
2885 initialValue = decl.value().get();
Brian Osmanafa18ee2020-10-07 17:47:45 -04002886 } else {
2887 SkASSERT(clonedDecl->is<InterfaceBlock>());
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002888 sharedVar = &clonedDecl->as<InterfaceBlock>().variable();
Brian Osmanafa18ee2020-10-07 17:47:45 -04002889 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002890
2891 // Now clone the Variable, and add the clone to the Program's symbol table.
Brian Osmanc0213602020-10-06 14:43:32 -04002892 // Any initial value expression was cloned as part of the GlobalVarDeclaration,
Brian Osman00a8b5b2020-10-02 09:06:04 -04002893 // so we're pointing at a Program-owned expression.
2894 const Variable* clonedVar =
2895 fGenerator->fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Variable>(
John Stiles586df952020-11-12 18:27:13 -05002896 sharedVar->fOffset, &sharedVar->modifiers(), sharedVar->name(),
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002897 &sharedVar->type(), /*builtin=*/false, sharedVar->storage(),
Brian Osmanafa18ee2020-10-07 17:47:45 -04002898 initialValue));
Brian Osman00a8b5b2020-10-02 09:06:04 -04002899
Brian Osmanafa18ee2020-10-07 17:47:45 -04002900 // Go back and update the declaring element to point at the cloned Variable.
2901 if (clonedDecl->is<GlobalVarDeclaration>()) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002902 GlobalVarDeclaration& global = clonedDecl->as<GlobalVarDeclaration>();
2903 global.declaration()->as<VarDeclaration>().setVar(clonedVar);
Brian Osmanafa18ee2020-10-07 17:47:45 -04002904 } else {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002905 clonedDecl->as<InterfaceBlock>().setVariable(clonedVar);
Brian Osmanafa18ee2020-10-07 17:47:45 -04002906 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002907
2908 // Remember this new re-mapping...
2909 fRemap.insert({sharedVar, clonedVar});
2910
Brian Osmanafa18ee2020-10-07 17:47:45 -04002911 // Add the declaring element to this Program
2912 fNewElements.push_back(std::move(clonedDecl));
Brian Osman00a8b5b2020-10-02 09:06:04 -04002913 }
2914 }
2915
Brian Osman8e2ef022020-09-30 13:26:43 -04002916 bool visitExpression(Expression& e) override {
2917 // Look for references to builtin variables.
Ethan Nicholas78686922020-10-08 06:46:27 -04002918 if (e.is<VariableReference>() && e.as<VariableReference>().variable()->isBuiltin()) {
2919 const Variable* sharedVar = e.as<VariableReference>().variable();
Brian Osman8e2ef022020-09-30 13:26:43 -04002920
Ethan Nicholase2c49992020-10-05 11:49:11 -04002921 this->cloneVariable(sharedVar->name());
Brian Osman8e2ef022020-09-30 13:26:43 -04002922
2923 // TODO: SkASSERT(found), once all pre-includes are converted?
2924 auto found = fRemap.find(sharedVar);
2925 if (found != fRemap.end()) {
2926 e.as<VariableReference>().setVariable(found->second);
2927 }
2928 }
2929
2930 return INHERITED::visitExpression(e);
2931 }
2932
2933 IRGenerator* fGenerator;
2934 std::unordered_map<const Variable*, const Variable*> fRemap;
2935 std::vector<std::unique_ptr<ProgramElement>> fNewElements;
2936
2937 using INHERITED = ProgramWriter;
2938 using INHERITED::visitProgramElement;
2939 };
2940
Brian Osman00a8b5b2020-10-02 09:06:04 -04002941 BuiltinVariableRemapper remapper(this);
2942 for (auto& e : *fProgramElements) {
2943 remapper.visitProgramElement(*e);
Brian Osman8e2ef022020-09-30 13:26:43 -04002944 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002945
2946 // Vulkan requires certain builtin variables be present, even if they're unused. At one time,
2947 // validation errors would result if they were missing. Now, it's just (Adreno) driver bugs
2948 // that drop or corrupt draws if they're missing.
2949 switch (fKind) {
2950 case Program::kFragment_Kind:
2951 remapper.cloneVariable("sk_Clockwise");
2952 break;
2953 default:
2954 break;
2955 }
2956
2957 fProgramElements->insert(fProgramElements->begin(),
Brian Osmanafa18ee2020-10-07 17:47:45 -04002958 std::make_move_iterator(remapper.fNewElements.begin()),
2959 std::make_move_iterator(remapper.fNewElements.end()));
Brian Osman8e2ef022020-09-30 13:26:43 -04002960}
2961
Brian Osman88cda172020-10-09 12:05:16 -04002962IRGenerator::IRBundle IRGenerator::convertProgram(
2963 Program::Kind kind,
2964 const Program::Settings* settings,
Brian Osmand7e76592020-11-02 12:26:22 -05002965 const ShaderCapsClass* caps,
Brian Osman88cda172020-10-09 12:05:16 -04002966 const ParsedModule& base,
2967 bool isBuiltinCode,
2968 const char* text,
2969 size_t length,
2970 const std::vector<std::unique_ptr<ExternalValue>>* externalValues) {
Robert Phillipsfe8da172018-01-24 14:52:02 +00002971 fKind = kind;
Brian Osman88cda172020-10-09 12:05:16 -04002972 fSettings = settings;
Brian Osmand7e76592020-11-02 12:26:22 -05002973 fCaps = caps;
Brian Osman88cda172020-10-09 12:05:16 -04002974 fSymbolTable = base.fSymbols;
2975 fIntrinsics = base.fIntrinsics.get();
2976 if (fIntrinsics) {
2977 fIntrinsics->resetAlreadyIncluded();
2978 }
2979 fIsBuiltinCode = isBuiltinCode;
2980
2981 std::vector<std::unique_ptr<ProgramElement>> elements;
2982 fProgramElements = &elements;
2983
2984 fInputs.reset();
2985 fInvocations = -1;
2986 fRTAdjust = nullptr;
2987 fRTAdjustInterfaceBlock = nullptr;
2988
2989 fCapsMap.clear();
Brian Osmand7e76592020-11-02 12:26:22 -05002990 if (fCaps) {
2991 fill_caps(*fCaps, &fCapsMap);
Brian Osman88cda172020-10-09 12:05:16 -04002992 } else {
2993 fCapsMap.insert({String("integerSupport"), Program::Settings::Value(true)});
2994 }
2995
John Stilese51b6a32020-10-21 15:02:37 -04002996 AutoSymbolTable table(this);
Brian Osman88cda172020-10-09 12:05:16 -04002997
Brian Osman68c1d402020-10-12 16:36:38 -04002998 if (kind == Program::kGeometry_Kind && !fIsBuiltinCode) {
2999 // Declare sk_InvocationID programmatically. With invocations support, it's an 'in' builtin.
3000 // If we're applying the workaround, then it's a plain global.
Brian Osmand7e76592020-11-02 12:26:22 -05003001 bool workaround = fCaps && !fCaps->gsInvocationsSupport();
Brian Osman68c1d402020-10-12 16:36:38 -04003002 Modifiers m;
3003 if (!workaround) {
3004 m.fFlags = Modifiers::kIn_Flag;
3005 m.fLayout.fBuiltin = SK_INVOCATIONID_BUILTIN;
3006 }
John Stiles586df952020-11-12 18:27:13 -05003007 auto var = std::make_unique<Variable>(-1, fModifiers->addToPool(m), "sk_InvocationID",
Brian Osman68c1d402020-10-12 16:36:38 -04003008 fContext.fInt_Type.get(), false,
3009 Variable::Storage::kGlobal);
John Stiles87ae34e2020-10-13 12:50:11 -04003010 auto decl = std::make_unique<VarDeclaration>(var.get(), fContext.fInt_Type.get(),
3011 /*sizes=*/ExpressionArray{},
3012 /*value=*/nullptr);
Brian Osman68c1d402020-10-12 16:36:38 -04003013 fSymbolTable->add(std::move(var));
3014 fProgramElements->push_back(
3015 std::make_unique<GlobalVarDeclaration>(/*offset=*/-1, std::move(decl)));
3016 }
3017
Brian Osman88cda172020-10-09 12:05:16 -04003018 if (externalValues) {
3019 // Add any external values to the new symbol table, so they're only visible to this Program
3020 for (const auto& ev : *externalValues) {
3021 fSymbolTable->addWithoutOwnership(ev.get());
3022 }
3023 }
3024
Ethan Nicholasc18bb512020-07-28 14:46:53 -04003025 Parser parser(text, length, *fSymbolTable, fErrors);
Ethan Nicholasba9a04f2020-11-06 09:28:04 -05003026 fFile = parser.compilationUnit();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003027 if (fErrors.errorCount()) {
Brian Osman88cda172020-10-09 12:05:16 -04003028 return {};
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003029 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003030 SkASSERT(fFile);
3031 for (const auto& decl : fFile->root()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003032 switch (decl.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04003033 case ASTNode::Kind::kVarDeclarations: {
John Stiles8f2a0cf2020-10-13 12:48:21 -04003034 StatementArray decls = this->convertVarDeclarations(decl,
3035 Variable::Storage::kGlobal);
Brian Osmanc0213602020-10-06 14:43:32 -04003036 for (auto& varDecl : decls) {
3037 fProgramElements->push_back(std::make_unique<GlobalVarDeclaration>(
3038 decl.fOffset, std::move(varDecl)));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003039 }
3040 break;
3041 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003042 case ASTNode::Kind::kEnum: {
3043 this->convertEnum(decl);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003044 break;
3045 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003046 case ASTNode::Kind::kFunction: {
3047 this->convertFunction(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003048 break;
3049 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003050 case ASTNode::Kind::kModifiers: {
3051 std::unique_ptr<ModifiersDeclaration> f = this->convertModifiersDeclaration(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003052 if (f) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003053 fProgramElements->push_back(std::move(f));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003054 }
3055 break;
3056 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003057 case ASTNode::Kind::kInterfaceBlock: {
3058 std::unique_ptr<InterfaceBlock> i = this->convertInterfaceBlock(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003059 if (i) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003060 fProgramElements->push_back(std::move(i));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003061 }
3062 break;
3063 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003064 case ASTNode::Kind::kExtension: {
3065 std::unique_ptr<Extension> e = this->convertExtension(decl.fOffset,
3066 decl.getString());
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003067 if (e) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003068 fProgramElements->push_back(std::move(e));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003069 }
3070 break;
3071 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003072 case ASTNode::Kind::kSection: {
3073 std::unique_ptr<Section> s = this->convertSection(decl);
Ethan Nicholas762466e2017-06-29 10:03:38 -04003074 if (s) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003075 fProgramElements->push_back(std::move(s));
Ethan Nicholas762466e2017-06-29 10:03:38 -04003076 }
3077 break;
3078 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003079 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003080#ifdef SK_DEBUG
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003081 ABORT("unsupported declaration: %s\n", decl.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003082#endif
3083 break;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003084 }
3085 }
Brian Osmanc95d3a12020-09-09 10:56:27 -04003086
Brian Osman8e2ef022020-09-30 13:26:43 -04003087 // Any variables defined in the pre-includes need to be cloned into the Program
Brian Osman00a8b5b2020-10-02 09:06:04 -04003088 if (!fIsBuiltinCode && fIntrinsics) {
3089 this->cloneBuiltinVariables();
3090 }
Brian Osman8e2ef022020-09-30 13:26:43 -04003091
Brian Osmanc95d3a12020-09-09 10:56:27 -04003092 // Do a final pass looking for dangling FunctionReference or TypeReference expressions
3093 class FindIllegalExpressions : public ProgramVisitor {
3094 public:
3095 FindIllegalExpressions(IRGenerator* generator) : fGenerator(generator) {}
3096
3097 bool visitExpression(const Expression& e) override {
3098 fGenerator->checkValid(e);
3099 return INHERITED::visitExpression(e);
3100 }
3101
3102 IRGenerator* fGenerator;
3103 using INHERITED = ProgramVisitor;
3104 using INHERITED::visitProgramElement;
3105 };
3106 for (const auto& pe : *fProgramElements) {
3107 FindIllegalExpressions{this}.visitProgramElement(*pe);
3108 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003109
Brian Osman88cda172020-10-09 12:05:16 -04003110 fSettings = nullptr;
3111
John Stilese51b6a32020-10-21 15:02:37 -04003112 return IRBundle{std::move(elements), this->releaseModifiers(), fSymbolTable, fInputs};
Brian Osman88cda172020-10-09 12:05:16 -04003113}
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003114
John Stilesa6841be2020-08-06 14:11:56 -04003115} // namespace SkSL