blob: 7c6095d9d01d755b3f84737947472ea10bc097e4 [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;
Ethan Nicholase6592142020-09-08 10:22:09 -0400398 if (size->kind() == Expression::Kind::kIntLiteral) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400399 count = size->as<IntLiteral>().value();
ethannicholasb3058bd2016-07-01 08:22:01 -0700400 if (count <= 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700401 fErrors.error(size->fOffset, "array size must be positive");
Brian Osmanc0213602020-10-06 14:43:32 -0400402 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700403 }
404 name += "[" + to_string(count) + "]";
405 } else {
Ethan Nicholas66d80062019-09-09 14:50:51 -0400406 fErrors.error(size->fOffset, "array size must be specified");
Brian Osmanc0213602020-10-06 14:43:32 -0400407 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700408 }
John Stiles3ae071e2020-08-05 15:29:29 -0400409 type = fSymbolTable->takeOwnershipOfSymbol(
Ethan Nicholase6592142020-09-08 10:22:09 -0400410 std::make_unique<Type>(name, Type::TypeKind::kArray, *type, (int)count));
ethannicholas14fe8cc2016-09-07 13:37:16 -0700411 sizes.push_back(std::move(size));
ethannicholasb3058bd2016-07-01 08:22:01 -0700412 } else {
John Stiles3ae071e2020-08-05 15:29:29 -0400413 type = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
Brian Osmane8c26082020-10-01 17:22:45 -0400414 type->name() + "[]", Type::TypeKind::kArray, *type, Type::kUnsizedArray));
ethannicholas14fe8cc2016-09-07 13:37:16 -0700415 sizes.push_back(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700416 }
417 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400418 auto var = std::make_unique<Variable>(varDecl.fOffset, fModifiers->handle(modifiers),
419 varData.fName, type, fIsBuiltinCode, storage);
Ethan Nicholase2c49992020-10-05 11:49:11 -0400420 if (var->name() == Compiler::RTADJUST_NAME) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400421 SkASSERT(!fRTAdjust);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400422 SkASSERT(var->type() == *fContext.fFloat4_Type);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000423 fRTAdjust = var.get();
424 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700425 std::unique_ptr<Expression> value;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400426 if (iter != varDecl.end()) {
427 value = this->convertExpression(*iter);
ethannicholasb3058bd2016-07-01 08:22:01 -0700428 if (!value) {
Brian Osmanc0213602020-10-06 14:43:32 -0400429 return {};
ethannicholasb3058bd2016-07-01 08:22:01 -0700430 }
ethannicholasd598f792016-07-25 10:08:54 -0700431 value = this->coerce(std::move(value), *type);
Ethan Nicholas68dd2c12018-03-01 15:05:17 -0500432 if (!value) {
Brian Osmanc0213602020-10-06 14:43:32 -0400433 return {};
Ethan Nicholas68dd2c12018-03-01 15:05:17 -0500434 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400435 var->setInitialValue(value.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700436 }
Brian Osman8dbdf232020-10-12 14:40:24 -0400437 const Symbol* symbol = (*fSymbolTable)[var->name()];
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400438 if (symbol && storage == Variable::Storage::kGlobal && var->name() == "sk_FragColor") {
John Stilesce591b72020-08-27 11:47:30 -0400439 // Already defined, ignore.
ethannicholasf789b382016-08-03 12:43:36 -0700440 } else {
John Stilesb8cc6652020-10-08 09:12:07 -0400441 varDecls.push_back(std::make_unique<VarDeclaration>(
Brian Osmanc0213602020-10-06 14:43:32 -0400442 var.get(), baseType, std::move(sizes), std::move(value)));
John Stilesb8cc6652020-10-08 09:12:07 -0400443 fSymbolTable->add(std::move(var));
ethannicholasf789b382016-08-03 12:43:36 -0700444 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700445 }
Brian Osmanc0213602020-10-06 14:43:32 -0400446 return varDecls;
ethannicholasb3058bd2016-07-01 08:22:01 -0700447}
448
Ethan Nicholasfc994162019-06-06 10:04:27 -0400449std::unique_ptr<ModifiersDeclaration> IRGenerator::convertModifiersDeclaration(const ASTNode& m) {
Brian Osman16f376f2020-09-02 12:30:59 -0400450 if (fKind != Program::kFragment_Kind &&
451 fKind != Program::kVertex_Kind &&
452 fKind != Program::kGeometry_Kind) {
453 fErrors.error(m.fOffset, "layout qualifiers are not allowed here");
454 return nullptr;
455 }
456
Ethan Nicholasfc994162019-06-06 10:04:27 -0400457 SkASSERT(m.fKind == ASTNode::Kind::kModifiers);
458 Modifiers modifiers = m.getModifiers();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400459 if (modifiers.fLayout.fInvocations != -1) {
Ethan Nicholasf06576b2019-04-03 15:45:25 -0400460 if (fKind != Program::kGeometry_Kind) {
461 fErrors.error(m.fOffset, "'invocations' is only legal in geometry shaders");
462 return nullptr;
463 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400464 fInvocations = modifiers.fLayout.fInvocations;
Brian Osmand7e76592020-11-02 12:26:22 -0500465 if (fCaps && !fCaps->gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400466 modifiers.fLayout.fInvocations = -1;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400467 if (modifiers.fLayout.description() == "") {
468 return nullptr;
469 }
470 }
471 }
Brian Osmand7e76592020-11-02 12:26:22 -0500472 if (modifiers.fLayout.fMaxVertices != -1 && fInvocations > 0 && fCaps &&
473 !fCaps->gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400474 modifiers.fLayout.fMaxVertices *= fInvocations;
475 }
Ethan Nicholas077050b2020-10-13 10:30:20 -0400476 return std::make_unique<ModifiersDeclaration>(fModifiers->handle(modifiers));
ethannicholas5961bc92016-10-12 06:39:56 -0700477}
478
John Stilesad2319f2020-09-02 15:01:47 -0400479std::unique_ptr<Statement> IRGenerator::convertIf(const ASTNode& n) {
480 SkASSERT(n.fKind == ASTNode::Kind::kIf);
481 auto iter = n.begin();
482 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
483 *fContext.fBool_Type);
484 if (!test) {
485 return nullptr;
486 }
487 std::unique_ptr<Statement> ifTrue = this->convertStatement(*(iter++));
488 if (!ifTrue) {
489 return nullptr;
490 }
John Stilesad2319f2020-09-02 15:01:47 -0400491 std::unique_ptr<Statement> ifFalse;
492 if (iter != n.end()) {
493 ifFalse = this->convertStatement(*(iter++));
494 if (!ifFalse) {
495 return nullptr;
496 }
John Stilesad2319f2020-09-02 15:01:47 -0400497 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400498 if (test->kind() == Expression::Kind::kBoolLiteral) {
John Stilesad2319f2020-09-02 15:01:47 -0400499 // static boolean value, fold down to a single branch
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400500 if (test->as<BoolLiteral>().value()) {
John Stilesad2319f2020-09-02 15:01:47 -0400501 return ifTrue;
502 } else if (ifFalse) {
503 return ifFalse;
504 } else {
505 // False & no else clause. Not an error, so don't return null!
John Stiles2ff97062020-09-02 15:02:01 -0400506 return std::make_unique<Nop>();
John Stilesad2319f2020-09-02 15:01:47 -0400507 }
508 }
John Stiles4c412bc2020-10-13 11:19:41 -0400509 auto ifStmt = std::make_unique<IfStatement>(n.fOffset, n.getBool(), std::move(test),
510 std::move(ifTrue), std::move(ifFalse));
511 fInliner->ensureScopedBlocks(ifStmt->ifTrue().get(), ifStmt.get());
512 fInliner->ensureScopedBlocks(ifStmt->ifFalse().get(), ifStmt.get());
513 return std::move(ifStmt);
John Stilesad2319f2020-09-02 15:01:47 -0400514}
515
Ethan Nicholasfc994162019-06-06 10:04:27 -0400516std::unique_ptr<Statement> IRGenerator::convertFor(const ASTNode& f) {
517 SkASSERT(f.fKind == ASTNode::Kind::kFor);
ethannicholas22f939e2016-10-13 13:25:34 -0700518 AutoLoopLevel level(this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700519 AutoSymbolTable table(this);
ethannicholas22f939e2016-10-13 13:25:34 -0700520 std::unique_ptr<Statement> initializer;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400521 auto iter = f.begin();
522 if (*iter) {
523 initializer = this->convertStatement(*iter);
ethannicholas22f939e2016-10-13 13:25:34 -0700524 if (!initializer) {
525 return nullptr;
526 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700527 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400528 ++iter;
ethannicholas22f939e2016-10-13 13:25:34 -0700529 std::unique_ptr<Expression> test;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400530 if (*iter) {
John Stiles4c412bc2020-10-13 11:19:41 -0400531 AutoDisableInline disableInline(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400532 test = this->coerce(this->convertExpression(*iter), *fContext.fBool_Type);
ethannicholas22f939e2016-10-13 13:25:34 -0700533 if (!test) {
534 return nullptr;
535 }
John Stiles4c412bc2020-10-13 11:19:41 -0400536
ethannicholasb3058bd2016-07-01 08:22:01 -0700537 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400538 ++iter;
ethannicholas22f939e2016-10-13 13:25:34 -0700539 std::unique_ptr<Expression> next;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400540 if (*iter) {
John Stiles4c412bc2020-10-13 11:19:41 -0400541 AutoDisableInline disableInline(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400542 next = this->convertExpression(*iter);
ethannicholas22f939e2016-10-13 13:25:34 -0700543 if (!next) {
544 return nullptr;
545 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700546 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400547 ++iter;
548 std::unique_ptr<Statement> statement = this->convertStatement(*iter);
ethannicholasb3058bd2016-07-01 08:22:01 -0700549 if (!statement) {
550 return nullptr;
551 }
John Stiles4c412bc2020-10-13 11:19:41 -0400552 auto forStmt = std::make_unique<ForStatement>(f.fOffset, std::move(initializer),
553 std::move(test), std::move(next),
554 std::move(statement), fSymbolTable);
555 fInliner->ensureScopedBlocks(forStmt->statement().get(), forStmt.get());
556 return std::move(forStmt);
ethannicholasb3058bd2016-07-01 08:22:01 -0700557}
558
Ethan Nicholasfc994162019-06-06 10:04:27 -0400559std::unique_ptr<Statement> IRGenerator::convertWhile(const ASTNode& w) {
560 SkASSERT(w.fKind == ASTNode::Kind::kWhile);
ethannicholas22f939e2016-10-13 13:25:34 -0700561 AutoLoopLevel level(this);
John Stiles4c412bc2020-10-13 11:19:41 -0400562 std::unique_ptr<Expression> test;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400563 auto iter = w.begin();
John Stiles4c412bc2020-10-13 11:19:41 -0400564 {
565 AutoDisableInline disableInline(this);
566 test = this->coerce(this->convertExpression(*(iter++)), *fContext.fBool_Type);
567 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700568 if (!test) {
569 return nullptr;
570 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400571 std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700572 if (!statement) {
573 return nullptr;
574 }
John Stiles4c412bc2020-10-13 11:19:41 -0400575 auto whileStmt = std::make_unique<WhileStatement>(w.fOffset, std::move(test),
576 std::move(statement));
577 fInliner->ensureScopedBlocks(whileStmt->statement().get(), whileStmt.get());
578 return std::move(whileStmt);
ethannicholasb3058bd2016-07-01 08:22:01 -0700579}
580
Ethan Nicholasfc994162019-06-06 10:04:27 -0400581std::unique_ptr<Statement> IRGenerator::convertDo(const ASTNode& d) {
582 SkASSERT(d.fKind == ASTNode::Kind::kDo);
ethannicholas22f939e2016-10-13 13:25:34 -0700583 AutoLoopLevel level(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400584 auto iter = d.begin();
585 std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
586 if (!statement) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700587 return nullptr;
588 }
John Stiles4c412bc2020-10-13 11:19:41 -0400589 std::unique_ptr<Expression> test;
590 {
591 AutoDisableInline disableInline(this);
592 test = this->coerce(this->convertExpression(*(iter++)), *fContext.fBool_Type);
593 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400594 if (!test) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700595 return nullptr;
596 }
John Stiles4c412bc2020-10-13 11:19:41 -0400597 auto doStmt = std::make_unique<DoStatement>(d.fOffset, std::move(statement), std::move(test));
598 fInliner->ensureScopedBlocks(doStmt->statement().get(), doStmt.get());
599 return std::move(doStmt);
ethannicholasb3058bd2016-07-01 08:22:01 -0700600}
601
Ethan Nicholasfc994162019-06-06 10:04:27 -0400602std::unique_ptr<Statement> IRGenerator::convertSwitch(const ASTNode& s) {
603 SkASSERT(s.fKind == ASTNode::Kind::kSwitch);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500604 AutoSwitchLevel level(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400605 auto iter = s.begin();
606 std::unique_ptr<Expression> value = this->convertExpression(*(iter++));
Ethan Nicholasaf197692017-02-27 13:26:45 -0500607 if (!value) {
608 return nullptr;
609 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400610 if (value->type() != *fContext.fUInt_Type &&
611 value->type().typeKind() != Type::TypeKind::kEnum) {
Ethan Nicholasaf197692017-02-27 13:26:45 -0500612 value = this->coerce(std::move(value), *fContext.fInt_Type);
613 if (!value) {
614 return nullptr;
615 }
616 }
617 AutoSymbolTable table(this);
618 std::unordered_set<int> caseValues;
619 std::vector<std::unique_ptr<SwitchCase>> cases;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400620 for (; iter != s.end(); ++iter) {
621 const ASTNode& c = *iter;
622 SkASSERT(c.fKind == ASTNode::Kind::kSwitchCase);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500623 std::unique_ptr<Expression> caseValue;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400624 auto childIter = c.begin();
625 if (*childIter) {
626 caseValue = this->convertExpression(*childIter);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500627 if (!caseValue) {
628 return nullptr;
629 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400630 caseValue = this->coerce(std::move(caseValue), value->type());
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500631 if (!caseValue) {
632 return nullptr;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500633 }
Brian Osman3e3db6c2020-08-14 09:42:12 -0400634 int64_t v = 0;
635 if (!this->getConstantInt(*caseValue, &v)) {
636 fErrors.error(caseValue->fOffset, "case value must be a constant integer");
Ethan Nicholasaf197692017-02-27 13:26:45 -0500637 return nullptr;
638 }
Ethan Nicholasaf197692017-02-27 13:26:45 -0500639 if (caseValues.find(v) != caseValues.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700640 fErrors.error(caseValue->fOffset, "duplicate case value");
Ethan Nicholasaf197692017-02-27 13:26:45 -0500641 }
642 caseValues.insert(v);
643 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400644 ++childIter;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400645 StatementArray statements;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400646 for (; childIter != c.end(); ++childIter) {
647 std::unique_ptr<Statement> converted = this->convertStatement(*childIter);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500648 if (!converted) {
649 return nullptr;
650 }
651 statements.push_back(std::move(converted));
652 }
John Stiles8f2a0cf2020-10-13 12:48:21 -0400653 cases.push_back(std::make_unique<SwitchCase>(c.fOffset, std::move(caseValue),
654 std::move(statements)));
Ethan Nicholasaf197692017-02-27 13:26:45 -0500655 }
John Stiles8f2a0cf2020-10-13 12:48:21 -0400656 return std::make_unique<SwitchStatement>(s.fOffset, s.getBool(), std::move(value),
657 std::move(cases), fSymbolTable);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500658}
659
Ethan Nicholasfc994162019-06-06 10:04:27 -0400660std::unique_ptr<Statement> IRGenerator::convertExpressionStatement(const ASTNode& s) {
661 std::unique_ptr<Expression> e = this->convertExpression(s);
ethannicholasb3058bd2016-07-01 08:22:01 -0700662 if (!e) {
663 return nullptr;
664 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700665 return std::unique_ptr<Statement>(new ExpressionStatement(std::move(e)));
666}
667
Ethan Nicholasfc994162019-06-06 10:04:27 -0400668std::unique_ptr<Statement> IRGenerator::convertReturn(const ASTNode& r) {
669 SkASSERT(r.fKind == ASTNode::Kind::kReturn);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400670 SkASSERT(fCurrentFunction);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000671 // early returns from a vertex main function will bypass the sk_Position normalization, so
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400672 // 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 +0000673 // normalization before each return, but it will probably never actually be necessary.
Ethan Nicholase2c49992020-10-05 11:49:11 -0400674 SkASSERT(Program::kVertex_Kind != fKind || !fRTAdjust || "main" != fCurrentFunction->name());
Ethan Nicholasfc994162019-06-06 10:04:27 -0400675 if (r.begin() != r.end()) {
676 std::unique_ptr<Expression> result = this->convertExpression(*r.begin());
ethannicholasb3058bd2016-07-01 08:22:01 -0700677 if (!result) {
678 return nullptr;
679 }
Ethan Nicholased84b732020-10-08 11:45:44 -0400680 if (fCurrentFunction->returnType() == *fContext.fVoid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700681 fErrors.error(result->fOffset, "may not return a value from a void function");
Brian Osman5eea6ae2020-09-09 16:05:18 -0400682 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -0700683 } else {
Ethan Nicholased84b732020-10-08 11:45:44 -0400684 result = this->coerce(std::move(result), fCurrentFunction->returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700685 if (!result) {
686 return nullptr;
687 }
688 }
689 return std::unique_ptr<Statement>(new ReturnStatement(std::move(result)));
690 } else {
Ethan Nicholased84b732020-10-08 11:45:44 -0400691 if (fCurrentFunction->returnType() != *fContext.fVoid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700692 fErrors.error(r.fOffset, "expected function to return '" +
Ethan Nicholased84b732020-10-08 11:45:44 -0400693 fCurrentFunction->returnType().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -0700694 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700695 return std::unique_ptr<Statement>(new ReturnStatement(r.fOffset));
ethannicholasb3058bd2016-07-01 08:22:01 -0700696 }
697}
698
Ethan Nicholasfc994162019-06-06 10:04:27 -0400699std::unique_ptr<Statement> IRGenerator::convertBreak(const ASTNode& b) {
700 SkASSERT(b.fKind == ASTNode::Kind::kBreak);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500701 if (fLoopLevel > 0 || fSwitchLevel > 0) {
John Stilesb61ee902020-09-21 12:26:59 -0400702 return std::make_unique<BreakStatement>(b.fOffset);
ethannicholas22f939e2016-10-13 13:25:34 -0700703 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700704 fErrors.error(b.fOffset, "break statement must be inside a loop or switch");
ethannicholas22f939e2016-10-13 13:25:34 -0700705 return nullptr;
706 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700707}
708
Ethan Nicholasfc994162019-06-06 10:04:27 -0400709std::unique_ptr<Statement> IRGenerator::convertContinue(const ASTNode& c) {
710 SkASSERT(c.fKind == ASTNode::Kind::kContinue);
ethannicholas22f939e2016-10-13 13:25:34 -0700711 if (fLoopLevel > 0) {
John Stilesb61ee902020-09-21 12:26:59 -0400712 return std::make_unique<ContinueStatement>(c.fOffset);
ethannicholas22f939e2016-10-13 13:25:34 -0700713 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700714 fErrors.error(c.fOffset, "continue statement must be inside a loop");
ethannicholas22f939e2016-10-13 13:25:34 -0700715 return nullptr;
716 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700717}
718
Ethan Nicholasfc994162019-06-06 10:04:27 -0400719std::unique_ptr<Statement> IRGenerator::convertDiscard(const ASTNode& d) {
720 SkASSERT(d.fKind == ASTNode::Kind::kDiscard);
John Stilesb61ee902020-09-21 12:26:59 -0400721 return std::make_unique<DiscardStatement>(d.fOffset);
ethannicholasb3058bd2016-07-01 08:22:01 -0700722}
723
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500724std::unique_ptr<Block> IRGenerator::applyInvocationIDWorkaround(std::unique_ptr<Block> main) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400725 Layout invokeLayout;
726 Modifiers invokeModifiers(invokeLayout, Modifiers::kHasSideEffects_Flag);
John Stilesb8cc6652020-10-08 09:12:07 -0400727 const FunctionDeclaration* invokeDecl =
Ethan Nicholased84b732020-10-08 11:45:44 -0400728 fSymbolTable->add(std::make_unique<FunctionDeclaration>(
729 /*offset=*/-1,
730 fModifiers->handle(invokeModifiers),
731 "_invoke",
Brian Osman5bf3e202020-10-13 10:34:18 -0400732 std::vector<const Variable*>(),
Ethan Nicholased84b732020-10-08 11:45:44 -0400733 fContext.fVoid_Type.get(),
John Stiles7c3515b2020-10-16 18:38:39 -0400734 fIsBuiltinCode));
John Stilesb9af7232020-08-20 15:57:48 -0400735 fProgramElements->push_back(std::make_unique<FunctionDefinition>(/*offset=*/-1,
John Stiles607d36b2020-10-19 15:00:01 -0400736 invokeDecl, fIsBuiltinCode,
John Stilesb9af7232020-08-20 15:57:48 -0400737 std::move(main)));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400738
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000739 std::vector<std::unique_ptr<VarDeclaration>> variables;
John Stilesb9af7232020-08-20 15:57:48 -0400740 const Variable* loopIdx = &(*fSymbolTable)["sk_InvocationID"]->as<Variable>();
John Stiles8e3b6be2020-10-13 11:14:08 -0400741 auto test = std::make_unique<BinaryExpression>(/*offset=*/-1,
742 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx),
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400743 Token::Kind::TK_LT,
John Stiles8e3b6be2020-10-13 11:14:08 -0400744 std::make_unique<IntLiteral>(fContext, /*offset=*/-1, fInvocations),
745 fContext.fBool_Type.get());
746 auto next = std::make_unique<PostfixExpression>(
747 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx,
748 VariableReference::RefKind::kReadWrite),
749 Token::Kind::TK_PLUSPLUS);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400750 ASTNode endPrimitiveID(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier, "EndPrimitive");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400751 std::unique_ptr<Expression> endPrimitive = this->convertExpression(endPrimitiveID);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400752 SkASSERT(endPrimitive);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400753
John Stiles8f2a0cf2020-10-13 12:48:21 -0400754 StatementArray loopBody;
John Stilesf4bda742020-10-14 16:57:41 -0400755 loopBody.reserve_back(2);
John Stiles8e3b6be2020-10-13 11:14:08 -0400756 loopBody.push_back(std::make_unique<ExpressionStatement>(this->call(
757 /*offset=*/-1, *invokeDecl,
758 ExpressionArray{})));
759 loopBody.push_back(std::make_unique<ExpressionStatement>(this->call(
760 /*offset=*/-1, std::move(endPrimitive),
761 ExpressionArray{})));
762 auto assignment = std::make_unique<BinaryExpression>(/*offset=*/-1,
763 std::make_unique<VariableReference>(/*offset=*/-1, loopIdx,
764 VariableReference::RefKind::kWrite),
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400765 Token::Kind::TK_EQ,
John Stiles8e3b6be2020-10-13 11:14:08 -0400766 std::make_unique<IntLiteral>(fContext, /*offset=*/-1, /*value=*/0),
767 fContext.fInt_Type.get());
768 auto initializer = std::make_unique<ExpressionStatement>(std::move(assignment));
769 auto loop = std::make_unique<ForStatement>(/*offset=*/-1,
770 std::move(initializer),
771 std::move(test), std::move(next),
772 std::make_unique<Block>(-1, std::move(loopBody)),
773 fSymbolTable);
John Stiles8f2a0cf2020-10-13 12:48:21 -0400774 StatementArray children;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400775 children.push_back(std::move(loop));
John Stilesfbd050b2020-08-03 13:21:46 -0400776 return std::make_unique<Block>(-1, std::move(children));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400777}
778
Robert Phillipsfe8da172018-01-24 14:52:02 +0000779std::unique_ptr<Statement> IRGenerator::getNormalizeSkPositionCode() {
Brian Osman88cda172020-10-09 12:05:16 -0400780 const Variable* skPerVertex = nullptr;
781 if (const ProgramElement* perVertexDecl = fIntrinsics->find(Compiler::PERVERTEX_NAME)) {
782 SkASSERT(perVertexDecl->is<InterfaceBlock>());
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400783 skPerVertex = &perVertexDecl->as<InterfaceBlock>().variable();
Brian Osman88cda172020-10-09 12:05:16 -0400784 }
785
Ethan Nicholasb809efb2018-04-12 14:39:21 -0400786 // sk_Position = float4(sk_Position.xy * rtAdjust.xz + sk_Position.ww * rtAdjust.yw,
Robert Phillipsfe8da172018-01-24 14:52:02 +0000787 // 0,
788 // sk_Position.w);
Brian Osman88cda172020-10-09 12:05:16 -0400789 SkASSERT(skPerVertex && fRTAdjust);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000790 #define REF(var) std::unique_ptr<Expression>(\
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400791 new VariableReference(-1, var, VariableReference::RefKind::kRead))
Ethan Nicholas4fadce42020-07-30 13:29:30 -0400792 #define WREF(var) std::unique_ptr<Expression>(\
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400793 new VariableReference(-1, var, VariableReference::RefKind::kWrite))
Robert Phillipsfe8da172018-01-24 14:52:02 +0000794 #define FIELD(var, idx) std::unique_ptr<Expression>(\
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400795 new FieldAccess(REF(var), idx, FieldAccess::OwnerKind::kAnonymousInterfaceBlock))
Brian Osman88cda172020-10-09 12:05:16 -0400796 #define POS std::unique_ptr<Expression>(new FieldAccess(WREF(skPerVertex), 0, \
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400797 FieldAccess::OwnerKind::kAnonymousInterfaceBlock))
Robert Phillipsfe8da172018-01-24 14:52:02 +0000798 #define ADJUST (fRTAdjustInterfaceBlock ? \
799 FIELD(fRTAdjustInterfaceBlock, fRTAdjustFieldIndex) : \
800 REF(fRTAdjust))
John Stiles750109b2020-10-30 13:45:46 -0400801 #define SWIZZLE(expr, comp) std::unique_ptr<Expression>( \
802 new Swizzle(fContext, expr, ComponentArray(comp, SK_ARRAY_COUNT(comp))))
Ethan Nicholasb809efb2018-04-12 14:39:21 -0400803 #define OP(left, op, right) std::unique_ptr<Expression>( \
804 new BinaryExpression(-1, left, op, right, \
Ethan Nicholas30d30222020-09-11 12:27:26 -0400805 fContext.fFloat2_Type.get()))
John Stiles750109b2020-10-30 13:45:46 -0400806
807 static constexpr int8_t kXYIndices[] = {0, 1};
808 static constexpr int8_t kXZIndices[] = {0, 2};
809 static constexpr int8_t kYWIndices[] = {1, 3};
810 static constexpr int8_t kWWIndices[] = {3, 3};
811 static constexpr int8_t kWIndex[] = {3};
812
John Stiles8e3b6be2020-10-13 11:14:08 -0400813 ExpressionArray children;
John Stilesf4bda742020-10-14 16:57:41 -0400814 children.reserve_back(3);
John Stiles750109b2020-10-30 13:45:46 -0400815 children.push_back(
816 OP(OP(SWIZZLE(POS, kXYIndices), Token::Kind::TK_STAR, SWIZZLE(ADJUST, kXZIndices)),
817 Token::Kind::TK_PLUS,
818 OP(SWIZZLE(POS, kWWIndices), Token::Kind::TK_STAR, SWIZZLE(ADJUST, kYWIndices))));
John Stiles8e3b6be2020-10-13 11:14:08 -0400819 children.push_back(std::make_unique<FloatLiteral>(fContext, /*offset=*/-1, /*value=*/0.0));
John Stiles750109b2020-10-30 13:45:46 -0400820 children.push_back(SWIZZLE(POS, kWIndex));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400821 std::unique_ptr<Expression> result = OP(POS, Token::Kind::TK_EQ,
John Stiles8e3b6be2020-10-13 11:14:08 -0400822 std::make_unique<Constructor>(/*offset=*/-1,
823 fContext.fFloat4_Type.get(),
824 std::move(children)));
825 return std::make_unique<ExpressionStatement>(std::move(result));
Robert Phillipsfe8da172018-01-24 14:52:02 +0000826}
827
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400828template<typename T>
829class AutoClear {
830public:
831 AutoClear(T* container)
832 : fContainer(container) {
833 SkASSERT(container->empty());
834 }
835
836 ~AutoClear() {
837 fContainer->clear();
838 }
839
840private:
841 T* fContainer;
842};
843
John Stilesb8e010c2020-08-11 18:05:39 -0400844template <typename T> AutoClear(T* c) -> AutoClear<T>;
845
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400846void IRGenerator::checkModifiers(int offset, const Modifiers& modifiers, int permitted) {
847 int flags = modifiers.fFlags;
848 #define CHECK(flag, name) \
849 if (!flags) return; \
850 if (flags & flag) { \
851 if (!(permitted & flag)) { \
852 fErrors.error(offset, "'" name "' is not permitted here"); \
853 } \
854 flags &= ~flag; \
855 }
856 CHECK(Modifiers::kConst_Flag, "const")
857 CHECK(Modifiers::kIn_Flag, "in")
858 CHECK(Modifiers::kOut_Flag, "out")
859 CHECK(Modifiers::kUniform_Flag, "uniform")
860 CHECK(Modifiers::kFlat_Flag, "flat")
861 CHECK(Modifiers::kNoPerspective_Flag, "noperspective")
862 CHECK(Modifiers::kReadOnly_Flag, "readonly")
863 CHECK(Modifiers::kWriteOnly_Flag, "writeonly")
864 CHECK(Modifiers::kCoherent_Flag, "coherent")
865 CHECK(Modifiers::kVolatile_Flag, "volatile")
866 CHECK(Modifiers::kRestrict_Flag, "restrict")
867 CHECK(Modifiers::kBuffer_Flag, "buffer")
868 CHECK(Modifiers::kHasSideEffects_Flag, "sk_has_side_effects")
869 CHECK(Modifiers::kPLS_Flag, "__pixel_localEXT")
870 CHECK(Modifiers::kPLSIn_Flag, "__pixel_local_inEXT")
871 CHECK(Modifiers::kPLSOut_Flag, "__pixel_local_outEXT")
872 CHECK(Modifiers::kVarying_Flag, "varying")
Ethan Nicholasf3c8f5d2020-08-20 13:09:14 +0000873 CHECK(Modifiers::kInline_Flag, "inline")
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400874 SkASSERT(flags == 0);
875}
876
Ethan Nicholasfc994162019-06-06 10:04:27 -0400877void IRGenerator::convertFunction(const ASTNode& f) {
John Stilesb8e010c2020-08-11 18:05:39 -0400878 AutoClear clear(&fReferencedIntrinsics);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400879 auto iter = f.begin();
Brian Osmand8070392020-09-09 15:50:02 -0400880 const Type* returnType = this->convertType(*(iter++), /*allowVoid=*/true);
John Stilesb9af7232020-08-20 15:57:48 -0400881 if (returnType == nullptr) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400882 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700883 }
Brian Osman3000d6b2020-07-31 15:57:28 -0400884 auto type_is_allowed = [&](const Type* t) {
885#if defined(SKSL_STANDALONE)
886 return true;
887#else
888 GrSLType unusedSLType;
889 return fKind != Program::kPipelineStage_Kind ||
890 type_to_grsltype(fContext, *t, &unusedSLType);
891#endif
892 };
893 if (returnType->nonnullable() == *fContext.fFragmentProcessor_Type ||
894 !type_is_allowed(returnType)) {
Brian Osman82329002020-07-21 09:39:27 -0400895 fErrors.error(f.fOffset,
896 "functions may not return type '" + returnType->displayName() + "'");
897 return;
898 }
John Stilesb9af7232020-08-20 15:57:48 -0400899 const ASTNode::FunctionData& funcData = f.getFunctionData();
900 this->checkModifiers(f.fOffset, funcData.fModifiers, Modifiers::kHasSideEffects_Flag |
901 Modifiers::kInline_Flag);
Brian Osman5bf3e202020-10-13 10:34:18 -0400902 std::vector<const Variable*> parameters;
John Stilesb9af7232020-08-20 15:57:48 -0400903 for (size_t i = 0; i < funcData.fParameterCount; ++i) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400904 const ASTNode& param = *(iter++);
905 SkASSERT(param.fKind == ASTNode::Kind::kParameter);
906 ASTNode::ParameterData pd = param.getParameterData();
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400907 this->checkModifiers(param.fOffset, pd.fModifiers, Modifiers::kIn_Flag |
908 Modifiers::kOut_Flag);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400909 auto paramIter = param.begin();
910 const Type* type = this->convertType(*(paramIter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700911 if (!type) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400912 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700913 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400914 for (int j = (int) pd.fSizeCount; j >= 1; j--) {
915 int size = (param.begin() + j)->getInt();
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400916 String name = type->name() + "[" + to_string(size) + "]";
John Stiles3ae071e2020-08-05 15:29:29 -0400917 type = fSymbolTable->takeOwnershipOfSymbol(
Ethan Nicholase6592142020-09-08 10:22:09 -0400918 std::make_unique<Type>(std::move(name), Type::TypeKind::kArray, *type, size));
ethannicholasb3058bd2016-07-01 08:22:01 -0700919 }
Brian Osman3000d6b2020-07-31 15:57:28 -0400920 // Only the (builtin) declarations of 'sample' are allowed to have FP parameters
921 if ((type->nonnullable() == *fContext.fFragmentProcessor_Type && !fIsBuiltinCode) ||
922 !type_is_allowed(type)) {
923 fErrors.error(param.fOffset,
924 "parameters of type '" + type->displayName() + "' not allowed");
925 return;
926 }
Brian Osman8dbdf232020-10-12 14:40:24 -0400927
928 Modifiers m = pd.fModifiers;
929 if (funcData.fName == "main" && (fKind == Program::kPipelineStage_Kind ||
930 fKind == Program::kFragmentProcessor_Kind)) {
931 if (i == 0) {
932 // We verify that the type is correct later, for now, if there is a parameter to
933 // a .fp or runtime-effect main(), it's supposed to be the coords:
934 m.fLayout.fBuiltin = SK_MAIN_COORDS_BUILTIN;
935 }
936 }
937
Brian Osman5bf3e202020-10-13 10:34:18 -0400938 const Variable* var = fSymbolTable->takeOwnershipOfSymbol(
Brian Osman8dbdf232020-10-12 14:40:24 -0400939 std::make_unique<Variable>(param.fOffset, fModifiers->handle(m), pd.fName, type,
940 fIsBuiltinCode, Variable::Storage::kParameter));
ethannicholasd598f792016-07-25 10:08:54 -0700941 parameters.push_back(var);
ethannicholasb3058bd2016-07-01 08:22:01 -0700942 }
943
Brian Osman767f4442020-08-13 16:59:48 -0400944 auto paramIsCoords = [&](int idx) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400945 return parameters[idx]->type() == *fContext.fFloat2_Type &&
Brian Osman8dbdf232020-10-12 14:40:24 -0400946 parameters[idx]->modifiers().fFlags == 0 &&
947 parameters[idx]->modifiers().fLayout.fBuiltin == SK_MAIN_COORDS_BUILTIN;
Brian Osman767f4442020-08-13 16:59:48 -0400948 };
Brian Osman767f4442020-08-13 16:59:48 -0400949
John Stilesb9af7232020-08-20 15:57:48 -0400950 if (funcData.fName == "main") {
Ethan Nicholas0d997662019-04-08 09:46:01 -0400951 switch (fKind) {
952 case Program::kPipelineStage_Kind: {
Brian Osman767f4442020-08-13 16:59:48 -0400953 // half4 main() -or- half4 main(float2)
954 bool valid = (*returnType == *fContext.fHalf4_Type) &&
955 ((parameters.size() == 0) ||
956 (parameters.size() == 1 && paramIsCoords(0)));
957 if (!valid) {
958 fErrors.error(f.fOffset, "pipeline stage 'main' must be declared "
959 "half4 main() or half4 main(float2)");
960 return;
961 }
962 break;
Brian Osman44820a92020-08-26 09:27:39 -0400963 }
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400964 case Program::kFragmentProcessor_Kind: {
Brian Osman44820a92020-08-26 09:27:39 -0400965 bool valid = (parameters.size() == 0) ||
966 (parameters.size() == 1 && paramIsCoords(0));
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400967 if (!valid) {
968 fErrors.error(f.fOffset, ".fp 'main' must be declared main() or main(float2)");
969 return;
970 }
971 break;
972 }
Ethan Nicholas746035a2019-04-23 13:31:09 -0400973 case Program::kGeneric_Kind:
Ethan Nicholas0d997662019-04-08 09:46:01 -0400974 break;
Ethan Nicholas0d997662019-04-08 09:46:01 -0400975 default:
976 if (parameters.size()) {
977 fErrors.error(f.fOffset, "shader 'main' must have zero parameters");
978 }
Ethan Nicholas00543112018-07-31 09:44:36 -0400979 }
980 }
981
ethannicholasb3058bd2016-07-01 08:22:01 -0700982 // find existing declaration
ethannicholasd598f792016-07-25 10:08:54 -0700983 const FunctionDeclaration* decl = nullptr;
John Stilesb9af7232020-08-20 15:57:48 -0400984 const Symbol* entry = (*fSymbolTable)[funcData.fName];
ethannicholasb3058bd2016-07-01 08:22:01 -0700985 if (entry) {
ethannicholasd598f792016-07-25 10:08:54 -0700986 std::vector<const FunctionDeclaration*> functions;
Ethan Nicholase6592142020-09-08 10:22:09 -0400987 switch (entry->kind()) {
988 case Symbol::Kind::kUnresolvedFunction:
Ethan Nicholasceb62142020-10-09 16:51:18 -0400989 functions = entry->as<UnresolvedFunction>().functions();
ethannicholasb3058bd2016-07-01 08:22:01 -0700990 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400991 case Symbol::Kind::kFunctionDeclaration:
John Stiles17c5b702020-08-18 10:40:03 -0400992 functions.push_back(&entry->as<FunctionDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -0700993 break;
994 default:
John Stilesb9af7232020-08-20 15:57:48 -0400995 fErrors.error(f.fOffset, "symbol '" + funcData.fName + "' was already defined");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400996 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700997 }
John Stilesb9af7232020-08-20 15:57:48 -0400998 for (const FunctionDeclaration* other : functions) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400999 SkASSERT(other->name() == funcData.fName);
Ethan Nicholased84b732020-10-08 11:45:44 -04001000 if (parameters.size() == other->parameters().size()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001001 bool match = true;
1002 for (size_t i = 0; i < parameters.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001003 if (parameters[i]->type() != other->parameters()[i]->type()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001004 match = false;
1005 break;
1006 }
1007 }
1008 if (match) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001009 if (*returnType != other->returnType()) {
1010 FunctionDeclaration newDecl(f.fOffset,
1011 fModifiers->handle(funcData.fModifiers),
1012 funcData.fName,
1013 parameters,
1014 returnType,
1015 fIsBuiltinCode);
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001016 fErrors.error(f.fOffset, "functions '" + newDecl.description() +
1017 "' and '" + other->description() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001018 "' differ only in return type");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001019 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001020 }
1021 decl = other;
1022 for (size_t i = 0; i < parameters.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001023 if (parameters[i]->modifiers() != other->parameters()[i]->modifiers()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001024 fErrors.error(f.fOffset, "modifiers on parameter " +
1025 to_string((uint64_t) i + 1) +
John Stilesb9af7232020-08-20 15:57:48 -04001026 " differ between declaration and definition");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001027 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001028 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001029 }
Ethan Nicholased84b732020-10-08 11:45:44 -04001030 if (other->definition() && !other->isBuiltin()) {
John Stilesb9af7232020-08-20 15:57:48 -04001031 fErrors.error(f.fOffset, "duplicate definition of " + other->description());
ethannicholasb3058bd2016-07-01 08:22:01 -07001032 }
1033 break;
1034 }
1035 }
1036 }
1037 }
1038 if (!decl) {
John Stilesb9af7232020-08-20 15:57:48 -04001039 // Conservatively assume all user-defined functions have side effects.
1040 Modifiers declModifiers = funcData.fModifiers;
1041 if (!fIsBuiltinCode) {
1042 declModifiers.fFlags |= Modifiers::kHasSideEffects_Flag;
1043 }
1044
1045 // Create a new declaration.
Ethan Nicholased84b732020-10-08 11:45:44 -04001046 decl = fSymbolTable->add(std::make_unique<FunctionDeclaration>(
1047 f.fOffset,
1048 fModifiers->handle(declModifiers),
1049 funcData.fName,
1050 parameters,
1051 returnType,
1052 fIsBuiltinCode));
ethannicholasb3058bd2016-07-01 08:22:01 -07001053 }
John Stiles569249b2020-11-03 12:18:22 -05001054 if (iter == f.end()) {
1055 // If there's no body, we've found a prototype.
1056 fProgramElements->push_back(std::make_unique<FunctionPrototype>(f.fOffset, decl,
1057 fIsBuiltinCode));
1058 } else {
1059 // Compile function body.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001060 SkASSERT(!fCurrentFunction);
ethannicholasd598f792016-07-25 10:08:54 -07001061 fCurrentFunction = decl;
John Stiles569249b2020-11-03 12:18:22 -05001062
ethannicholasd598f792016-07-25 10:08:54 -07001063 AutoSymbolTable table(this);
John Stiles569249b2020-11-03 12:18:22 -05001064 for (const Variable* param : decl->parameters()) {
1065 fSymbolTable->addWithoutOwnership(param);
ethannicholasb3058bd2016-07-01 08:22:01 -07001066 }
John Stilesb9af7232020-08-20 15:57:48 -04001067 bool needInvocationIDWorkaround = fInvocations != -1 && funcData.fName == "main" &&
Brian Osmand7e76592020-11-02 12:26:22 -05001068 fCaps && !fCaps->gsInvocationsSupport();
Ethan Nicholasfc994162019-06-06 10:04:27 -04001069 std::unique_ptr<Block> body = this->convertBlock(*iter);
ethannicholasd598f792016-07-25 10:08:54 -07001070 fCurrentFunction = nullptr;
1071 if (!body) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001072 return;
1073 }
1074 if (needInvocationIDWorkaround) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001075 body = this->applyInvocationIDWorkaround(std::move(body));
ethannicholasd598f792016-07-25 10:08:54 -07001076 }
John Stilesb9af7232020-08-20 15:57:48 -04001077 if (Program::kVertex_Kind == fKind && funcData.fName == "main" && fRTAdjust) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001078 body->children().push_back(this->getNormalizeSkPositionCode());
Robert Phillipsfe8da172018-01-24 14:52:02 +00001079 }
John Stiles607d36b2020-10-19 15:00:01 -04001080 auto result = std::make_unique<FunctionDefinition>(
1081 f.fOffset, decl, fIsBuiltinCode, std::move(body), std::move(fReferencedIntrinsics));
Ethan Nicholased84b732020-10-08 11:45:44 -04001082 decl->setDefinition(result.get());
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001083 result->setSource(&f);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001084 fProgramElements->push_back(std::move(result));
ethannicholasb3058bd2016-07-01 08:22:01 -07001085 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001086}
1087
Ethan Nicholasfc994162019-06-06 10:04:27 -04001088std::unique_ptr<InterfaceBlock> IRGenerator::convertInterfaceBlock(const ASTNode& intf) {
Brian Osman16f376f2020-09-02 12:30:59 -04001089 if (fKind != Program::kFragment_Kind &&
1090 fKind != Program::kVertex_Kind &&
1091 fKind != Program::kGeometry_Kind) {
1092 fErrors.error(intf.fOffset, "interface block is not allowed here");
1093 return nullptr;
1094 }
1095
Ethan Nicholasfc994162019-06-06 10:04:27 -04001096 SkASSERT(intf.fKind == ASTNode::Kind::kInterfaceBlock);
1097 ASTNode::InterfaceBlockData id = intf.getInterfaceBlockData();
ethannicholasb3058bd2016-07-01 08:22:01 -07001098 std::shared_ptr<SymbolTable> old = fSymbolTable;
John Stiles869cdef2020-10-30 14:24:24 -04001099 std::shared_ptr<SymbolTable> symbols;
ethannicholasb3058bd2016-07-01 08:22:01 -07001100 std::vector<Type::Field> fields;
Robert Phillipsfe8da172018-01-24 14:52:02 +00001101 bool foundRTAdjust = false;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001102 auto iter = intf.begin();
John Stiles869cdef2020-10-30 14:24:24 -04001103 {
1104 AutoSymbolTable table(this);
1105 symbols = fSymbolTable;
1106 bool haveRuntimeArray = false;
1107 for (size_t i = 0; i < id.fDeclarationCount; ++i) {
1108 StatementArray decls = this->convertVarDeclarations(*(iter++),
1109 Variable::Storage::kInterfaceBlock);
1110 if (decls.empty()) {
1111 return nullptr;
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001112 }
John Stiles869cdef2020-10-30 14:24:24 -04001113 for (const auto& decl : decls) {
1114 const VarDeclaration& vd = decl->as<VarDeclaration>();
1115 if (haveRuntimeArray) {
1116 fErrors.error(decl->fOffset,
1117 "only the last entry in an interface block may be a runtime-sized "
1118 "array");
1119 }
1120 if (&vd.var() == fRTAdjust) {
1121 foundRTAdjust = true;
1122 SkASSERT(vd.var().type() == *fContext.fFloat4_Type);
1123 fRTAdjustFieldIndex = fields.size();
1124 }
1125 fields.push_back(Type::Field(vd.var().modifiers(), vd.var().name(),
1126 &vd.var().type()));
1127 if (vd.value()) {
1128 fErrors.error(decl->fOffset,
1129 "initializers are not permitted on interface block fields");
1130 }
1131 if (vd.var().type().typeKind() == Type::TypeKind::kArray &&
1132 vd.var().type().columns() == Type::kUnsizedArray) {
1133 haveRuntimeArray = true;
1134 }
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001135 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001136 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001137 }
John Stiles3ae071e2020-08-05 15:29:29 -04001138 const Type* type =
1139 old->takeOwnershipOfSymbol(std::make_unique<Type>(intf.fOffset, id.fTypeName, fields));
John Stiles87ae34e2020-10-13 12:50:11 -04001140 ExpressionArray sizes;
John Stilesf4bda742020-10-14 16:57:41 -04001141 sizes.reserve_back(id.fSizeCount);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001142 for (size_t i = 0; i < id.fSizeCount; ++i) {
1143 const ASTNode& size = *(iter++);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001144 if (size) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001145 std::unique_ptr<Expression> converted = this->convertExpression(size);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001146 if (!converted) {
1147 return nullptr;
1148 }
Ethan Nicholase2c49992020-10-05 11:49:11 -04001149 String name = type->name();
Ethan Nicholas50afc172017-02-16 14:49:57 -05001150 int64_t count;
Ethan Nicholase6592142020-09-08 10:22:09 -04001151 if (converted->kind() == Expression::Kind::kIntLiteral) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001152 count = converted->as<IntLiteral>().value();
Ethan Nicholas50afc172017-02-16 14:49:57 -05001153 if (count <= 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001154 fErrors.error(converted->fOffset, "array size must be positive");
Ethan Nicholas66d80062019-09-09 14:50:51 -04001155 return nullptr;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001156 }
1157 name += "[" + to_string(count) + "]";
1158 } else {
Ethan Nicholas66d80062019-09-09 14:50:51 -04001159 fErrors.error(intf.fOffset, "array size must be specified");
1160 return nullptr;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001161 }
John Stiles3ae071e2020-08-05 15:29:29 -04001162 type = symbols->takeOwnershipOfSymbol(
Ethan Nicholase6592142020-09-08 10:22:09 -04001163 std::make_unique<Type>(name, Type::TypeKind::kArray, *type, (int)count));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001164 sizes.push_back(std::move(converted));
1165 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001166 String name = String(type->name()) + "[]";
Brian Osmane8c26082020-10-01 17:22:45 -04001167 type = symbols->takeOwnershipOfSymbol(std::make_unique<Type>(
1168 name, Type::TypeKind::kArray, *type, Type::kUnsizedArray));
1169 sizes.push_back(nullptr);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001170 }
1171 }
Brian Osman5bf3e202020-10-13 10:34:18 -04001172 const Variable* var = old->takeOwnershipOfSymbol(
John Stiles3ae071e2020-08-05 15:29:29 -04001173 std::make_unique<Variable>(intf.fOffset,
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001174 fModifiers->handle(id.fModifiers),
John Stiles3ae071e2020-08-05 15:29:29 -04001175 id.fInstanceName.fLength ? id.fInstanceName : id.fTypeName,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001176 type,
Brian Osman3887a012020-09-30 13:22:27 -04001177 fIsBuiltinCode,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001178 Variable::Storage::kGlobal));
Robert Phillipsfe8da172018-01-24 14:52:02 +00001179 if (foundRTAdjust) {
1180 fRTAdjustInterfaceBlock = var;
1181 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001182 if (id.fInstanceName.fLength) {
John Stilesb8cc6652020-10-08 09:12:07 -04001183 old->addWithoutOwnership(var);
ethannicholasb3058bd2016-07-01 08:22:01 -07001184 } else {
1185 for (size_t i = 0; i < fields.size(); i++) {
John Stilesb8cc6652020-10-08 09:12:07 -04001186 old->add(std::make_unique<Field>(intf.fOffset, var, (int)i));
ethannicholasb3058bd2016-07-01 08:22:01 -07001187 }
1188 }
John Stilesfbd050b2020-08-03 13:21:46 -04001189 return std::make_unique<InterfaceBlock>(intf.fOffset,
1190 var,
1191 id.fTypeName,
1192 id.fInstanceName,
1193 std::move(sizes),
1194 symbols);
ethannicholasb3058bd2016-07-01 08:22:01 -07001195}
1196
Brian Osman3e3db6c2020-08-14 09:42:12 -04001197bool IRGenerator::getConstantInt(const Expression& value, int64_t* out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001198 switch (value.kind()) {
1199 case Expression::Kind::kIntLiteral:
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001200 *out = value.as<IntLiteral>().value();
Brian Osman3e3db6c2020-08-14 09:42:12 -04001201 return true;
Ethan Nicholase6592142020-09-08 10:22:09 -04001202 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001203 const Variable& var = *value.as<VariableReference>().variable();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001204 return (var.modifiers().fFlags & Modifiers::kConst_Flag) &&
1205 var.initialValue() && this->getConstantInt(*var.initialValue(), out);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001206 }
1207 default:
Brian Osman3e3db6c2020-08-14 09:42:12 -04001208 return false;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001209 }
1210}
1211
Ethan Nicholasfc994162019-06-06 10:04:27 -04001212void IRGenerator::convertEnum(const ASTNode& e) {
Brian Osman16f376f2020-09-02 12:30:59 -04001213 if (fKind == Program::kPipelineStage_Kind) {
1214 fErrors.error(e.fOffset, "enum is not allowed here");
1215 return;
1216 }
1217
Ethan Nicholasfc994162019-06-06 10:04:27 -04001218 SkASSERT(e.fKind == ASTNode::Kind::kEnum);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001219 int64_t currentValue = 0;
1220 Layout layout;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001221 ASTNode enumType(e.fNodes, e.fOffset, ASTNode::Kind::kType,
1222 ASTNode::TypeData(e.getString(), false, false));
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001223 const Type* type = this->convertType(enumType);
1224 Modifiers modifiers(layout, Modifiers::kConst_Flag);
Brian Osman1313d1a2020-09-08 10:34:30 -04001225 std::shared_ptr<SymbolTable> oldTable = fSymbolTable;
John Stiles7c3515b2020-10-16 18:38:39 -04001226 fSymbolTable = std::make_shared<SymbolTable>(fSymbolTable, fIsBuiltinCode);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001227 for (auto iter = e.begin(); iter != e.end(); ++iter) {
1228 const ASTNode& child = *iter;
1229 SkASSERT(child.fKind == ASTNode::Kind::kEnumCase);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001230 std::unique_ptr<Expression> value;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001231 if (child.begin() != child.end()) {
1232 value = this->convertExpression(*child.begin());
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001233 if (!value) {
Brian Osman1313d1a2020-09-08 10:34:30 -04001234 fSymbolTable = oldTable;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001235 return;
1236 }
Brian Osman3e3db6c2020-08-14 09:42:12 -04001237 if (!this->getConstantInt(*value, &currentValue)) {
1238 fErrors.error(value->fOffset, "enum value must be a constant integer");
Brian Osman1313d1a2020-09-08 10:34:30 -04001239 fSymbolTable = oldTable;
Brian Osman3e3db6c2020-08-14 09:42:12 -04001240 return;
1241 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001242 }
1243 value = std::unique_ptr<Expression>(new IntLiteral(fContext, e.fOffset, currentValue));
1244 ++currentValue;
John Stilesb8cc6652020-10-08 09:12:07 -04001245 fSymbolTable->add(std::make_unique<Variable>(e.fOffset, fModifiers->handle(modifiers),
1246 child.getString(), type, fIsBuiltinCode,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001247 Variable::Storage::kGlobal, value.get()));
Brian Osman3e3db6c2020-08-14 09:42:12 -04001248 fSymbolTable->takeOwnershipOfIRNode(std::move(value));
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001249 }
Brian Osman1313d1a2020-09-08 10:34:30 -04001250 // Now we orphanize the Enum's symbol table, so that future lookups in it are strict
1251 fSymbolTable->fParent = nullptr;
John Stiles1c823672020-10-20 10:23:50 -04001252 fProgramElements->push_back(std::make_unique<Enum>(e.fOffset, e.getString(), fSymbolTable,
1253 /*isSharedWithCpp=*/fIsBuiltinCode,
1254 /*isBuiltin=*/fIsBuiltinCode));
Brian Osman1313d1a2020-09-08 10:34:30 -04001255 fSymbolTable = oldTable;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001256}
1257
Brian Osmand8070392020-09-09 15:50:02 -04001258const Type* IRGenerator::convertType(const ASTNode& type, bool allowVoid) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001259 ASTNode::TypeData td = type.getTypeData();
1260 const Symbol* result = (*fSymbolTable)[td.fName];
Brian Osmand8070392020-09-09 15:50:02 -04001261 if (result && result->is<Type>()) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001262 if (td.fIsNullable) {
John Stiles17c5b702020-08-18 10:40:03 -04001263 if (result->as<Type>() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001264 if (type.begin() != type.end()) {
1265 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be used in "
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001266 "an array");
1267 }
John Stiles3ae071e2020-08-05 15:29:29 -04001268 result = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
Ethan Nicholase2c49992020-10-05 11:49:11 -04001269 String(result->name()) + "?", Type::TypeKind::kNullable,
1270 result->as<Type>()));
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001271 } else {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001272 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be nullable");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001273 }
1274 }
Brian Osmand8070392020-09-09 15:50:02 -04001275 if (result->as<Type>() == *fContext.fVoid_Type) {
1276 if (!allowVoid) {
1277 fErrors.error(type.fOffset, "type '" + td.fName + "' not allowed in this context");
1278 return nullptr;
1279 }
1280 if (type.begin() != type.end()) {
1281 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be used in an array");
1282 return nullptr;
1283 }
1284 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001285 for (const auto& size : type) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001286 String name(result->name());
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001287 name += "[";
Ethan Nicholasfc994162019-06-06 10:04:27 -04001288 if (size) {
1289 name += to_string(size.getInt());
Ethan Nicholas50afc172017-02-16 14:49:57 -05001290 }
1291 name += "]";
Brian Osmane8c26082020-10-01 17:22:45 -04001292 result = fSymbolTable->takeOwnershipOfSymbol(
1293 std::make_unique<Type>(name, Type::TypeKind::kArray, result->as<Type>(),
1294 size ? size.getInt() : Type::kUnsizedArray));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001295 }
John Stiles17c5b702020-08-18 10:40:03 -04001296 return &result->as<Type>();
ethannicholasb3058bd2016-07-01 08:22:01 -07001297 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001298 fErrors.error(type.fOffset, "unknown type '" + td.fName + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001299 return nullptr;
1300}
1301
Ethan Nicholasfc994162019-06-06 10:04:27 -04001302std::unique_ptr<Expression> IRGenerator::convertExpression(const ASTNode& expr) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001303 switch (expr.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001304 case ASTNode::Kind::kBinary:
1305 return this->convertBinaryExpression(expr);
1306 case ASTNode::Kind::kBool:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001307 return std::unique_ptr<Expression>(new BoolLiteral(fContext, expr.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04001308 expr.getBool()));
1309 case ASTNode::Kind::kCall:
1310 return this->convertCallExpression(expr);
1311 case ASTNode::Kind::kField:
1312 return this->convertFieldExpression(expr);
1313 case ASTNode::Kind::kFloat:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001314 return std::unique_ptr<Expression>(new FloatLiteral(fContext, expr.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04001315 expr.getFloat()));
1316 case ASTNode::Kind::kIdentifier:
1317 return this->convertIdentifier(expr);
1318 case ASTNode::Kind::kIndex:
1319 return this->convertIndexExpression(expr);
1320 case ASTNode::Kind::kInt:
1321 return std::unique_ptr<Expression>(new IntLiteral(fContext, expr.fOffset,
1322 expr.getInt()));
1323 case ASTNode::Kind::kNull:
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001324 return std::unique_ptr<Expression>(new NullLiteral(fContext, expr.fOffset));
Ethan Nicholasfc994162019-06-06 10:04:27 -04001325 case ASTNode::Kind::kPostfix:
1326 return this->convertPostfixExpression(expr);
1327 case ASTNode::Kind::kPrefix:
1328 return this->convertPrefixExpression(expr);
Brian Osman6518d772020-09-10 16:50:06 -04001329 case ASTNode::Kind::kScope:
1330 return this->convertScopeExpression(expr);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001331 case ASTNode::Kind::kTernary:
1332 return this->convertTernaryExpression(expr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001333 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001334#ifdef SK_DEBUG
Ethan Nicholasfc994162019-06-06 10:04:27 -04001335 ABORT("unsupported expression: %s\n", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001336#endif
1337 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001338 }
1339}
1340
Ethan Nicholasfc994162019-06-06 10:04:27 -04001341std::unique_ptr<Expression> IRGenerator::convertIdentifier(const ASTNode& identifier) {
1342 SkASSERT(identifier.fKind == ASTNode::Kind::kIdentifier);
1343 const Symbol* result = (*fSymbolTable)[identifier.getString()];
ethannicholasb3058bd2016-07-01 08:22:01 -07001344 if (!result) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001345 fErrors.error(identifier.fOffset, "unknown identifier '" + identifier.getString() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001346 return nullptr;
1347 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001348 switch (result->kind()) {
1349 case Symbol::Kind::kFunctionDeclaration: {
ethannicholasd598f792016-07-25 10:08:54 -07001350 std::vector<const FunctionDeclaration*> f = {
John Stiles17c5b702020-08-18 10:40:03 -04001351 &result->as<FunctionDeclaration>()
ethannicholasb3058bd2016-07-01 08:22:01 -07001352 };
John Stilesfbd050b2020-08-03 13:21:46 -04001353 return std::make_unique<FunctionReference>(fContext, identifier.fOffset, f);
ethannicholasb3058bd2016-07-01 08:22:01 -07001354 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001355 case Symbol::Kind::kUnresolvedFunction: {
John Stiles17c5b702020-08-18 10:40:03 -04001356 const UnresolvedFunction* f = &result->as<UnresolvedFunction>();
Ethan Nicholasceb62142020-10-09 16:51:18 -04001357 return std::make_unique<FunctionReference>(fContext, identifier.fOffset,
1358 f->functions());
ethannicholasb3058bd2016-07-01 08:22:01 -07001359 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001360 case Symbol::Kind::kVariable: {
John Stiles17c5b702020-08-18 10:40:03 -04001361 const Variable* var = &result->as<Variable>();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001362 const Modifiers& modifiers = var->modifiers();
1363 switch (modifiers.fLayout.fBuiltin) {
Ethan Nicholascd700e92018-08-24 16:43:57 -04001364 case SK_WIDTH_BUILTIN:
1365 fInputs.fRTWidth = true;
1366 break;
1367 case SK_HEIGHT_BUILTIN:
Greg Daniele6ab9982018-08-22 13:56:32 +00001368 fInputs.fRTHeight = true;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001369 break;
1370#ifndef SKSL_STANDALONE
1371 case SK_FRAGCOORD_BUILTIN:
Brian Osman9f313b62019-10-02 12:03:11 -04001372 fInputs.fFlipY = true;
1373 if (fSettings->fFlipY &&
Brian Osmand7e76592020-11-02 12:26:22 -05001374 (!fCaps || !fCaps->fragCoordConventionsExtensionString())) {
Brian Osman9f313b62019-10-02 12:03:11 -04001375 fInputs.fRTHeight = true;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001376 }
Greg Daniele6ab9982018-08-22 13:56:32 +00001377#endif
Ethan Nicholascd700e92018-08-24 16:43:57 -04001378 }
Ethan Nicholas33c59ed2019-08-13 10:21:38 -04001379 if (fKind == Program::kFragmentProcessor_Kind &&
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001380 (modifiers.fFlags & Modifiers::kIn_Flag) &&
1381 !(modifiers.fFlags & Modifiers::kUniform_Flag) &&
1382 !modifiers.fLayout.fKey &&
1383 modifiers.fLayout.fBuiltin == -1 &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001384 var->type().nonnullable() != *fContext.fFragmentProcessor_Type &&
1385 var->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholas33c59ed2019-08-13 10:21:38 -04001386 bool valid = false;
1387 for (const auto& decl : fFile->root()) {
1388 if (decl.fKind == ASTNode::Kind::kSection) {
1389 ASTNode::SectionData section = decl.getSectionData();
1390 if (section.fName == "setData") {
1391 valid = true;
1392 break;
1393 }
1394 }
1395 }
1396 if (!valid) {
1397 fErrors.error(identifier.fOffset, "'in' variable must be either 'uniform' or "
1398 "'layout(key)', or there must be a custom "
1399 "@setData function");
1400 }
1401 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001402 // default to kRead_RefKind; this will be corrected later if the variable is written to
John Stilesfbd050b2020-08-03 13:21:46 -04001403 return std::make_unique<VariableReference>(identifier.fOffset,
Brian Osman79457ef2020-09-24 15:01:27 -04001404 var,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001405 VariableReference::RefKind::kRead);
ethannicholasb3058bd2016-07-01 08:22:01 -07001406 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001407 case Symbol::Kind::kField: {
John Stiles17c5b702020-08-18 10:40:03 -04001408 const Field* field = &result->as<Field>();
Brian Osman6a204db2020-10-08 09:29:02 -04001409 auto base = std::make_unique<VariableReference>(identifier.fOffset, &field->owner(),
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001410 VariableReference::RefKind::kRead);
Brian Osman6a204db2020-10-08 09:29:02 -04001411 return std::make_unique<FieldAccess>(std::move(base),
1412 field->fieldIndex(),
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001413 FieldAccess::OwnerKind::kAnonymousInterfaceBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -07001414 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001415 case Symbol::Kind::kType: {
John Stiles17c5b702020-08-18 10:40:03 -04001416 const Type* t = &result->as<Type>();
Ethan Nicholase6592142020-09-08 10:22:09 -04001417 return std::make_unique<TypeReference>(fContext, identifier.fOffset, t);
ethannicholasb3058bd2016-07-01 08:22:01 -07001418 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001419 case Symbol::Kind::kExternal: {
John Stiles17c5b702020-08-18 10:40:03 -04001420 const ExternalValue* r = &result->as<ExternalValue>();
John Stilesfbd050b2020-08-03 13:21:46 -04001421 return std::make_unique<ExternalValueReference>(identifier.fOffset, r);
Ethan Nicholas91164d12019-05-15 15:29:54 -04001422 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001423 default:
Ethan Nicholase6592142020-09-08 10:22:09 -04001424 ABORT("unsupported symbol type %d\n", (int) result->kind());
ethannicholasb3058bd2016-07-01 08:22:01 -07001425 }
Ethan Nicholasc0709392017-06-27 11:20:22 -04001426}
1427
Ethan Nicholasfc994162019-06-06 10:04:27 -04001428std::unique_ptr<Section> IRGenerator::convertSection(const ASTNode& s) {
Brian Osman16f376f2020-09-02 12:30:59 -04001429 if (fKind != Program::kFragmentProcessor_Kind) {
1430 fErrors.error(s.fOffset, "syntax error");
1431 return nullptr;
1432 }
1433
Ethan Nicholasfc994162019-06-06 10:04:27 -04001434 ASTNode::SectionData section = s.getSectionData();
John Stilesfbd050b2020-08-03 13:21:46 -04001435 return std::make_unique<Section>(s.fOffset, section.fName, section.fArgument,
1436 section.fText);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001437}
1438
Ethan Nicholas11d53972016-11-28 11:23:23 -05001439std::unique_ptr<Expression> IRGenerator::coerce(std::unique_ptr<Expression> expr,
ethannicholasd598f792016-07-25 10:08:54 -07001440 const Type& type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001441 if (!expr) {
1442 return nullptr;
1443 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001444 if (expr->type() == type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001445 return expr;
1446 }
1447 this->checkValid(*expr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001448 if (expr->type() == *fContext.fInvalid_Type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001449 return nullptr;
1450 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001451 if (!expr->coercionCost(type).isPossible(fSettings->fAllowNarrowingConversions)) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001452 fErrors.error(expr->fOffset, "expected '" + type.displayName() + "', but found '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04001453 expr->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001454 return nullptr;
1455 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001456 if (type.typeKind() == Type::TypeKind::kScalar) {
John Stiles8e3b6be2020-10-13 11:14:08 -04001457 ExpressionArray args;
ethannicholasb3058bd2016-07-01 08:22:01 -07001458 args.push_back(std::move(expr));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001459 std::unique_ptr<Expression> ctor;
1460 if (type == *fContext.fFloatLiteral_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001461 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
1462 "float"));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001463 } else if (type == *fContext.fIntLiteral_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001464 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
1465 "int"));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001466 } else {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001467 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
Ethan Nicholase2c49992020-10-05 11:49:11 -04001468 type.name()));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001469 }
1470 if (!ctor) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001471 printf("error, null identifier: %s\n", String(type.name()).c_str());
Ethan Nicholase1f55022019-02-05 17:17:40 -05001472 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001473 SkASSERT(ctor);
John Stiles8e3b6be2020-10-13 11:14:08 -04001474 return this->call(/*offset=*/-1, std::move(ctor), std::move(args));
ethannicholasb3058bd2016-07-01 08:22:01 -07001475 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001476 if (expr->kind() == Expression::Kind::kNullLiteral) {
1477 SkASSERT(type.typeKind() == Type::TypeKind::kNullable);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001478 return std::unique_ptr<Expression>(new NullLiteral(expr->fOffset, &type));
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001479 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001480 ExpressionArray args;
ethannicholas5961bc92016-10-12 06:39:56 -07001481 args.push_back(std::move(expr));
John Stiles8e3b6be2020-10-13 11:14:08 -04001482 return std::make_unique<Constructor>(/*offset=*/-1, &type, std::move(args));
ethannicholasb3058bd2016-07-01 08:22:01 -07001483}
1484
ethannicholasf789b382016-08-03 12:43:36 -07001485static bool is_matrix_multiply(const Type& left, const Type& right) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001486 if (left.typeKind() == Type::TypeKind::kMatrix) {
1487 return right.typeKind() == Type::TypeKind::kMatrix ||
1488 right.typeKind() == Type::TypeKind::kVector;
ethannicholasf789b382016-08-03 12:43:36 -07001489 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001490 return left.typeKind() == Type::TypeKind::kVector &&
1491 right.typeKind() == Type::TypeKind::kMatrix;
ethannicholasf789b382016-08-03 12:43:36 -07001492}
ethannicholasea4567c2016-10-17 11:24:37 -07001493
ethannicholasb3058bd2016-07-01 08:22:01 -07001494/**
1495 * Determines the operand and result types of a binary expression. Returns true if the expression is
1496 * legal, false otherwise. If false, the values of the out parameters are undefined.
1497 */
Ethan Nicholas11d53972016-11-28 11:23:23 -05001498static bool determine_binary_type(const Context& context,
Brian Osman0acb5b52020-09-02 13:45:47 -04001499 bool allowNarrowing,
Ethan Nicholas11d53972016-11-28 11:23:23 -05001500 Token::Kind op,
1501 const Type& left,
1502 const Type& right,
ethannicholasd598f792016-07-25 10:08:54 -07001503 const Type** outLeftType,
1504 const Type** outRightType,
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001505 const Type** outResultType) {
1506 bool isLogical = false;
Brian Osmanbf2163f2020-09-16 16:21:40 -04001507 bool isBitwise = false;
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001508 bool validMatrixOrVectorOp = false;
1509 bool isAssignment = Compiler::IsAssignment(op);
1510
ethannicholasb3058bd2016-07-01 08:22:01 -07001511 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001512 case Token::Kind::TK_EQ:
ethannicholasea4567c2016-10-17 11:24:37 -07001513 *outLeftType = &left;
1514 *outRightType = &left;
1515 *outResultType = &left;
Brian Osman0acb5b52020-09-02 13:45:47 -04001516 return right.canCoerceTo(left, allowNarrowing);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001517 case Token::Kind::TK_EQEQ: // fall through
Brian Osman0acb5b52020-09-02 13:45:47 -04001518 case Token::Kind::TK_NEQ: {
1519 CoercionCost rightToLeft = right.coercionCost(left),
1520 leftToRight = left.coercionCost(right);
1521 if (rightToLeft < leftToRight) {
1522 if (rightToLeft.isPossible(allowNarrowing)) {
1523 *outLeftType = &left;
1524 *outRightType = &left;
1525 *outResultType = context.fBool_Type.get();
1526 return true;
1527 }
1528 } else {
1529 if (leftToRight.isPossible(allowNarrowing)) {
1530 *outLeftType = &right;
1531 *outRightType = &right;
1532 *outResultType = context.fBool_Type.get();
1533 return true;
1534 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001535 }
Ethan Nicholas23463002018-03-28 15:16:15 -04001536 return false;
Brian Osman0acb5b52020-09-02 13:45:47 -04001537 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001538 case Token::Kind::TK_LT: // fall through
1539 case Token::Kind::TK_GT: // fall through
1540 case Token::Kind::TK_LTEQ: // fall through
1541 case Token::Kind::TK_GTEQ:
ethannicholasb3058bd2016-07-01 08:22:01 -07001542 isLogical = true;
1543 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001544 case Token::Kind::TK_LOGICALOR: // fall through
1545 case Token::Kind::TK_LOGICALAND: // fall through
1546 case Token::Kind::TK_LOGICALXOR: // fall through
1547 case Token::Kind::TK_LOGICALOREQ: // fall through
1548 case Token::Kind::TK_LOGICALANDEQ: // fall through
1549 case Token::Kind::TK_LOGICALXOREQ:
ethannicholasd598f792016-07-25 10:08:54 -07001550 *outLeftType = context.fBool_Type.get();
1551 *outRightType = context.fBool_Type.get();
1552 *outResultType = context.fBool_Type.get();
Brian Osman0acb5b52020-09-02 13:45:47 -04001553 return left.canCoerceTo(*context.fBool_Type, allowNarrowing) &&
1554 right.canCoerceTo(*context.fBool_Type, allowNarrowing);
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001555 case Token::Kind::TK_STAREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001556 case Token::Kind::TK_STAR:
ethannicholasf789b382016-08-03 12:43:36 -07001557 if (is_matrix_multiply(left, right)) {
1558 // determine final component type
Brian Osman3ed22a92020-09-17 15:10:25 -04001559 if (determine_binary_type(context, allowNarrowing, op,
Brian Osman0acb5b52020-09-02 13:45:47 -04001560 left.componentType(), right.componentType(),
1561 outLeftType, outRightType, outResultType)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001562 *outLeftType = &(*outResultType)->toCompound(context, left.columns(),
Brian Salomon23356442018-11-30 15:33:19 -05001563 left.rows());
Ethan Nicholas11d53972016-11-28 11:23:23 -05001564 *outRightType = &(*outResultType)->toCompound(context, right.columns(),
Brian Salomon23356442018-11-30 15:33:19 -05001565 right.rows());
ethannicholasf789b382016-08-03 12:43:36 -07001566 int leftColumns = left.columns();
1567 int leftRows = left.rows();
1568 int rightColumns;
1569 int rightRows;
Ethan Nicholase6592142020-09-08 10:22:09 -04001570 if (right.typeKind() == Type::TypeKind::kVector) {
ethannicholasf789b382016-08-03 12:43:36 -07001571 // matrix * vector treats the vector as a column vector, so we need to
1572 // transpose it
1573 rightColumns = right.rows();
1574 rightRows = right.columns();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001575 SkASSERT(rightColumns == 1);
ethannicholasf789b382016-08-03 12:43:36 -07001576 } else {
1577 rightColumns = right.columns();
1578 rightRows = right.rows();
1579 }
1580 if (rightColumns > 1) {
1581 *outResultType = &(*outResultType)->toCompound(context, rightColumns,
1582 leftRows);
1583 } else {
1584 // result was a column vector, transpose it back to a row
1585 *outResultType = &(*outResultType)->toCompound(context, leftRows,
1586 rightColumns);
1587 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001588 if (isAssignment && ((*outResultType)->columns() != leftColumns ||
1589 (*outResultType)->rows() != leftRows)) {
1590 return false;
1591 }
ethannicholasf789b382016-08-03 12:43:36 -07001592 return leftColumns == rightRows;
1593 } else {
1594 return false;
1595 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001596 }
ethannicholasea4567c2016-10-17 11:24:37 -07001597 validMatrixOrVectorOp = true;
1598 break;
Brian Osmanbf2163f2020-09-16 16:21:40 -04001599 case Token::Kind::TK_SHLEQ:
1600 case Token::Kind::TK_SHREQ:
1601 case Token::Kind::TK_BITWISEANDEQ:
1602 case Token::Kind::TK_BITWISEOREQ:
1603 case Token::Kind::TK_BITWISEXOREQ:
1604 case Token::Kind::TK_SHL:
1605 case Token::Kind::TK_SHR:
1606 case Token::Kind::TK_BITWISEAND:
1607 case Token::Kind::TK_BITWISEOR:
1608 case Token::Kind::TK_BITWISEXOR:
1609 isBitwise = true;
1610 validMatrixOrVectorOp = true;
1611 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001612 case Token::Kind::TK_PLUSEQ:
1613 case Token::Kind::TK_MINUSEQ:
1614 case Token::Kind::TK_SLASHEQ:
1615 case Token::Kind::TK_PERCENTEQ:
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001616 case Token::Kind::TK_PLUS:
1617 case Token::Kind::TK_MINUS:
1618 case Token::Kind::TK_SLASH:
1619 case Token::Kind::TK_PERCENT:
ethannicholasea4567c2016-10-17 11:24:37 -07001620 validMatrixOrVectorOp = true;
1621 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001622 case Token::Kind::TK_COMMA:
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001623 *outLeftType = &left;
1624 *outRightType = &right;
1625 *outResultType = &right;
1626 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001627 default:
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001628 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001629 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001630
1631 bool leftIsVectorOrMatrix = left.typeKind() == Type::TypeKind::kVector ||
1632 left.typeKind() == Type::TypeKind::kMatrix,
1633 rightIsVectorOrMatrix = right.typeKind() == Type::TypeKind::kVector ||
1634 right.typeKind() == Type::TypeKind::kMatrix;
1635
1636 if (leftIsVectorOrMatrix && validMatrixOrVectorOp &&
1637 right.typeKind() == Type::TypeKind::kScalar) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001638 if (determine_binary_type(context, allowNarrowing, op, left.componentType(), right,
1639 outLeftType, outRightType, outResultType)) {
ethannicholasd598f792016-07-25 10:08:54 -07001640 *outLeftType = &(*outLeftType)->toCompound(context, left.columns(), left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001641 if (!isLogical) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001642 *outResultType =
1643 &(*outResultType)->toCompound(context, left.columns(), left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001644 }
1645 return true;
1646 }
1647 return false;
1648 }
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001649
1650 if (!isAssignment && rightIsVectorOrMatrix && validMatrixOrVectorOp &&
1651 left.typeKind() == Type::TypeKind::kScalar) {
Brian Osman0acb5b52020-09-02 13:45:47 -04001652 if (determine_binary_type(context, allowNarrowing, op, left, right.componentType(),
1653 outLeftType, outRightType, outResultType)) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001654 *outRightType = &(*outRightType)->toCompound(context, right.columns(), right.rows());
1655 if (!isLogical) {
1656 *outResultType =
1657 &(*outResultType)->toCompound(context, right.columns(), right.rows());
1658 }
1659 return true;
1660 }
1661 return false;
1662 }
1663
Brian Osman0acb5b52020-09-02 13:45:47 -04001664 CoercionCost rightToLeftCost = right.coercionCost(left);
1665 CoercionCost leftToRightCost = isAssignment ? CoercionCost::Impossible()
1666 : left.coercionCost(right);
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001667
1668 if ((left.typeKind() == Type::TypeKind::kScalar &&
1669 right.typeKind() == Type::TypeKind::kScalar) ||
1670 (leftIsVectorOrMatrix && validMatrixOrVectorOp)) {
Brian Osmanbf2163f2020-09-16 16:21:40 -04001671 if (isBitwise) {
1672 const Type& leftNumberType(leftIsVectorOrMatrix ? left.componentType() : left);
1673 const Type& rightNumberType(rightIsVectorOrMatrix ? right.componentType() : right);
1674 if (!leftNumberType.isInteger() || !rightNumberType.isInteger()) {
1675 return false;
1676 }
1677 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001678 if (rightToLeftCost.isPossible(allowNarrowing) && rightToLeftCost < leftToRightCost) {
1679 // Right-to-Left conversion is possible and cheaper
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001680 *outLeftType = &left;
1681 *outRightType = &left;
1682 *outResultType = &left;
Brian Osman0acb5b52020-09-02 13:45:47 -04001683 } else if (leftToRightCost.isPossible(allowNarrowing)) {
Brian Osmanc4cb3a62020-09-03 16:52:28 -04001684 // Left-to-Right conversion is possible (and at least as cheap as Right-to-Left)
1685 *outLeftType = &right;
1686 *outRightType = &right;
1687 *outResultType = &right;
1688 } else {
1689 return false;
1690 }
1691 if (isLogical) {
1692 *outResultType = context.fBool_Type.get();
1693 }
1694 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001695 }
1696 return false;
1697}
1698
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001699static std::unique_ptr<Expression> short_circuit_boolean(const Context& context,
1700 const Expression& left,
1701 Token::Kind op,
1702 const Expression& right) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001703 SkASSERT(left.kind() == Expression::Kind::kBoolLiteral);
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001704 bool leftVal = left.as<BoolLiteral>().value();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001705 if (op == Token::Kind::TK_LOGICALAND) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001706 // (true && expr) -> (expr) and (false && expr) -> (false)
1707 return leftVal ? right.clone()
1708 : std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, false));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001709 } else if (op == Token::Kind::TK_LOGICALOR) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001710 // (true || expr) -> (true) and (false || expr) -> (expr)
1711 return leftVal ? std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, true))
1712 : right.clone();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001713 } else if (op == Token::Kind::TK_LOGICALXOR) {
Noah Lavine334d0ba2019-12-18 23:03:49 -05001714 // (true ^^ expr) -> !(expr) and (false ^^ expr) -> (expr)
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001715 return leftVal ? std::unique_ptr<Expression>(new PrefixExpression(
1716 Token::Kind::TK_LOGICALNOT,
1717 right.clone()))
Noah Lavine334d0ba2019-12-18 23:03:49 -05001718 : right.clone();
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001719 } else {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001720 return nullptr;
1721 }
1722}
1723
ethannicholas08a92112016-11-09 13:26:45 -08001724std::unique_ptr<Expression> IRGenerator::constantFold(const Expression& left,
1725 Token::Kind op,
Ethan Nicholas86a43402017-01-19 13:32:00 -05001726 const Expression& right) const {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001727 // If the left side is a constant boolean literal, the right side does not need to be constant
1728 // for short circuit optimizations to allow the constant to be folded.
John Stiles95acbbc2020-11-04 16:23:26 -05001729 if (left.is<BoolLiteral>() && !right.isCompileTimeConstant()) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001730 return short_circuit_boolean(fContext, left, op, right);
John Stiles95acbbc2020-11-04 16:23:26 -05001731 } else if (right.is<BoolLiteral>() && !left.isCompileTimeConstant()) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001732 // There aren't side effects in SKSL within expressions, so (left OP right) is equivalent to
1733 // (right OP left) for short-circuit optimizations
1734 return short_circuit_boolean(fContext, right, op, left);
1735 }
1736
1737 // Other than the short-circuit cases above, constant folding requires both sides to be constant
Brian Osmanb6b95732020-06-30 11:44:27 -04001738 if (!left.isCompileTimeConstant() || !right.isCompileTimeConstant()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001739 return nullptr;
1740 }
ethannicholas08a92112016-11-09 13:26:45 -08001741 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
1742 // precision to calculate the results and hope the result makes sense. The plan is to move the
1743 // Skia caps into SkSL, so we have access to all of them including the precisions of the various
1744 // types, which will let us be more intelligent about this.
John Stiles95acbbc2020-11-04 16:23:26 -05001745 if (left.is<BoolLiteral>() && right.is<BoolLiteral>()) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001746 bool leftVal = left.as<BoolLiteral>().value();
1747 bool rightVal = right.as<BoolLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001748 bool result;
1749 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001750 case Token::Kind::TK_LOGICALAND: result = leftVal && rightVal; break;
1751 case Token::Kind::TK_LOGICALOR: result = leftVal || rightVal; break;
1752 case Token::Kind::TK_LOGICALXOR: result = leftVal ^ rightVal; break;
ethannicholas08a92112016-11-09 13:26:45 -08001753 default: return nullptr;
1754 }
John Stiles95acbbc2020-11-04 16:23:26 -05001755 return std::make_unique<BoolLiteral>(fContext, left.fOffset, result);
ethannicholas08a92112016-11-09 13:26:45 -08001756 }
John Stilesfbd050b2020-08-03 13:21:46 -04001757 #define RESULT(t, op) std::make_unique<t ## Literal>(fContext, left.fOffset, \
1758 leftVal op rightVal)
1759 #define URESULT(t, op) std::make_unique<t ## Literal>(fContext, left.fOffset, \
1760 (uint32_t) leftVal op \
1761 (uint32_t) rightVal)
John Stiles95acbbc2020-11-04 16:23:26 -05001762 if (left.is<IntLiteral>() && right.is<IntLiteral>()) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001763 int64_t leftVal = left.as<IntLiteral>().value();
1764 int64_t rightVal = right.as<IntLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001765 switch (op) {
Ethan Nicholas66869e92020-04-30 09:27:54 -04001766 case Token::Kind::TK_PLUS: return URESULT(Int, +);
1767 case Token::Kind::TK_MINUS: return URESULT(Int, -);
1768 case Token::Kind::TK_STAR: return URESULT(Int, *);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001769 case Token::Kind::TK_SLASH:
Ethan Nicholas66869e92020-04-30 09:27:54 -04001770 if (leftVal == std::numeric_limits<int64_t>::min() && rightVal == -1) {
1771 fErrors.error(right.fOffset, "arithmetic overflow");
1772 return nullptr;
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001773 }
Ethan Nicholas66869e92020-04-30 09:27:54 -04001774 if (!rightVal) {
1775 fErrors.error(right.fOffset, "division by zero");
1776 return nullptr;
1777 }
1778 return RESULT(Int, /);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001779 case Token::Kind::TK_PERCENT:
Ethan Nicholas66869e92020-04-30 09:27:54 -04001780 if (leftVal == std::numeric_limits<int64_t>::min() && rightVal == -1) {
1781 fErrors.error(right.fOffset, "arithmetic overflow");
1782 return nullptr;
Ethan Nicholas2503ab62017-01-05 10:44:25 -05001783 }
Ethan Nicholas66869e92020-04-30 09:27:54 -04001784 if (!rightVal) {
1785 fErrors.error(right.fOffset, "division by zero");
1786 return nullptr;
1787 }
1788 return RESULT(Int, %);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001789 case Token::Kind::TK_BITWISEAND: return RESULT(Int, &);
1790 case Token::Kind::TK_BITWISEOR: return RESULT(Int, |);
1791 case Token::Kind::TK_BITWISEXOR: return RESULT(Int, ^);
1792 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
1793 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
1794 case Token::Kind::TK_GT: return RESULT(Bool, >);
1795 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
1796 case Token::Kind::TK_LT: return RESULT(Bool, <);
1797 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
1798 case Token::Kind::TK_SHL:
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001799 if (rightVal >= 0 && rightVal <= 31) {
Ethan Nicholase4489002020-04-29 14:00:14 -04001800 return URESULT(Int, <<);
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001801 }
1802 fErrors.error(right.fOffset, "shift value out of range");
1803 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001804 case Token::Kind::TK_SHR:
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001805 if (rightVal >= 0 && rightVal <= 31) {
Ethan Nicholase4489002020-04-29 14:00:14 -04001806 return URESULT(Int, >>);
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001807 }
1808 fErrors.error(right.fOffset, "shift value out of range");
1809 return nullptr;
1810
1811 default:
1812 return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001813 }
1814 }
John Stiles95acbbc2020-11-04 16:23:26 -05001815 if (left.is<FloatLiteral>() && right.is<FloatLiteral>()) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001816 SKSL_FLOAT leftVal = left.as<FloatLiteral>().value();
1817 SKSL_FLOAT rightVal = right.as<FloatLiteral>().value();
ethannicholas08a92112016-11-09 13:26:45 -08001818 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001819 case Token::Kind::TK_PLUS: return RESULT(Float, +);
1820 case Token::Kind::TK_MINUS: return RESULT(Float, -);
1821 case Token::Kind::TK_STAR: return RESULT(Float, *);
1822 case Token::Kind::TK_SLASH:
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001823 if (rightVal) {
1824 return RESULT(Float, /);
1825 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001826 fErrors.error(right.fOffset, "division by zero");
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001827 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001828 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
1829 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
1830 case Token::Kind::TK_GT: return RESULT(Bool, >);
1831 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
1832 case Token::Kind::TK_LT: return RESULT(Bool, <);
1833 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
1834 default: return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001835 }
1836 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001837 const Type& leftType = left.type();
1838 const Type& rightType = right.type();
1839 if (leftType.typeKind() == Type::TypeKind::kVector && leftType.componentType().isFloat() &&
1840 leftType == rightType) {
John Stiles8e3b6be2020-10-13 11:14:08 -04001841 ExpressionArray args;
John Stiles95acbbc2020-11-04 16:23:26 -05001842 #define RETURN_VEC_COMPONENTWISE_RESULT(op) \
1843 for (int i = 0; i < leftType.columns(); i++) { \
1844 SKSL_FLOAT value = left.getFVecComponent(i) op right.getFVecComponent(i); \
1845 args.push_back(std::make_unique<FloatLiteral>(fContext, left.fOffset, value)); \
1846 } \
1847 return std::make_unique<Constructor>(left.fOffset, &leftType, std::move(args))
Ethan Nicholascb670962017-04-20 19:31:52 -04001848 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001849 case Token::Kind::TK_EQEQ:
John Stiles95acbbc2020-11-04 16:23:26 -05001850 if (left.kind() == right.kind()) {
1851 return std::make_unique<BoolLiteral>(fContext, left.fOffset,
1852 left.compareConstant(fContext, right));
1853 }
1854 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001855 case Token::Kind::TK_NEQ:
John Stiles95acbbc2020-11-04 16:23:26 -05001856 if (left.kind() == right.kind()) {
1857 return std::make_unique<BoolLiteral>(fContext, left.fOffset,
1858 !left.compareConstant(fContext, right));
1859 }
1860 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001861 case Token::Kind::TK_PLUS: RETURN_VEC_COMPONENTWISE_RESULT(+);
1862 case Token::Kind::TK_MINUS: RETURN_VEC_COMPONENTWISE_RESULT(-);
1863 case Token::Kind::TK_STAR: RETURN_VEC_COMPONENTWISE_RESULT(*);
1864 case Token::Kind::TK_SLASH:
Ethan Nicholas30d30222020-09-11 12:27:26 -04001865 for (int i = 0; i < leftType.columns(); i++) {
Ethan Nicholas4cf5fd92019-06-10 16:15:56 -04001866 SKSL_FLOAT rvalue = right.getFVecComponent(i);
1867 if (rvalue == 0.0) {
1868 fErrors.error(right.fOffset, "division by zero");
1869 return nullptr;
1870 }
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001871 SKSL_FLOAT value = left.getFVecComponent(i) / rvalue;
John Stiles8e3b6be2020-10-13 11:14:08 -04001872 args.push_back(std::make_unique<FloatLiteral>(fContext, /*offset=*/-1, value));
Ethan Nicholas4cf5fd92019-06-10 16:15:56 -04001873 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001874 return std::make_unique<Constructor>(/*offset=*/-1, &leftType, std::move(args));
Ethan Nicholase6592142020-09-08 10:22:09 -04001875 default:
1876 return nullptr;
Ethan Nicholascb670962017-04-20 19:31:52 -04001877 }
John Stiles95acbbc2020-11-04 16:23:26 -05001878 #undef RETURN_VEC_COMPONENTWISE_RESULT
Ethan Nicholascb670962017-04-20 19:31:52 -04001879 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001880 if (leftType.typeKind() == Type::TypeKind::kMatrix &&
1881 rightType.typeKind() == Type::TypeKind::kMatrix &&
Ethan Nicholase6592142020-09-08 10:22:09 -04001882 left.kind() == right.kind()) {
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001883 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001884 case Token::Kind::TK_EQEQ:
John Stiles95acbbc2020-11-04 16:23:26 -05001885 return std::make_unique<BoolLiteral>(fContext, left.fOffset,
John Stiles8e3b6be2020-10-13 11:14:08 -04001886 left.compareConstant(fContext, right));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001887 case Token::Kind::TK_NEQ:
John Stiles95acbbc2020-11-04 16:23:26 -05001888 return std::make_unique<BoolLiteral>(fContext, left.fOffset,
John Stiles8e3b6be2020-10-13 11:14:08 -04001889 !left.compareConstant(fContext, right));
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001890 default:
1891 return nullptr;
1892 }
1893 }
ethannicholas08a92112016-11-09 13:26:45 -08001894 #undef RESULT
1895 return nullptr;
1896}
1897
Ethan Nicholasfc994162019-06-06 10:04:27 -04001898std::unique_ptr<Expression> IRGenerator::convertBinaryExpression(const ASTNode& expression) {
1899 SkASSERT(expression.fKind == ASTNode::Kind::kBinary);
1900 auto iter = expression.begin();
1901 std::unique_ptr<Expression> left = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07001902 if (!left) {
1903 return nullptr;
1904 }
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001905 Token::Kind op = expression.getToken().fKind;
John Stiles4c412bc2020-10-13 11:19:41 -04001906 std::unique_ptr<Expression> right;
1907 {
1908 // Can't inline the right side of a short-circuiting boolean, because our inlining
1909 // approach runs things out of order.
1910 AutoDisableInline disableInline(this, /*canInline=*/(op != Token::Kind::TK_LOGICALAND &&
1911 op != Token::Kind::TK_LOGICALOR));
1912 right = this->convertExpression(*(iter++));
1913 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001914 if (!right) {
1915 return nullptr;
1916 }
ethannicholasd598f792016-07-25 10:08:54 -07001917 const Type* leftType;
1918 const Type* rightType;
1919 const Type* resultType;
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001920 const Type* rawLeftType;
John Stilesd0e48402020-09-22 14:00:40 -04001921 if (left->is<IntLiteral>() && right->type().isInteger()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001922 rawLeftType = &right->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001923 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001924 rawLeftType = &left->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001925 }
1926 const Type* rawRightType;
John Stilesd0e48402020-09-22 14:00:40 -04001927 if (right->is<IntLiteral>() && left->type().isInteger()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001928 rawRightType = &left->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001929 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001930 rawRightType = &right->type();
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001931 }
Brian Osman0acb5b52020-09-02 13:45:47 -04001932 if (!determine_binary_type(fContext, fSettings->fAllowNarrowingConversions, op,
1933 *rawLeftType, *rawRightType, &leftType, &rightType, &resultType)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001934 fErrors.error(expression.fOffset, String("type mismatch: '") +
Ethan Nicholasfc994162019-06-06 10:04:27 -04001935 Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04001936 "' cannot operate on '" + left->type().displayName() +
1937 "', '" + right->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001938 return nullptr;
1939 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001940 if (Compiler::IsAssignment(op)) {
Ethan Nicholas4fadce42020-07-30 13:29:30 -04001941 if (!this->setRefKind(*left, op != Token::Kind::TK_EQ
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001942 ? VariableReference::RefKind::kReadWrite
1943 : VariableReference::RefKind::kWrite)) {
Ethan Nicholas4fadce42020-07-30 13:29:30 -04001944 return nullptr;
1945 }
ethannicholasea4567c2016-10-17 11:24:37 -07001946 }
1947 left = this->coerce(std::move(left), *leftType);
1948 right = this->coerce(std::move(right), *rightType);
1949 if (!left || !right) {
1950 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001951 }
John Stilesa008b0f2020-08-16 08:48:02 -04001952 std::unique_ptr<Expression> result = this->constantFold(*left, op, *right);
ethannicholas08a92112016-11-09 13:26:45 -08001953 if (!result) {
John Stilesd1c4dac2020-08-11 18:50:50 -04001954 result = std::make_unique<BinaryExpression>(expression.fOffset, std::move(left), op,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001955 std::move(right), resultType);
ethannicholas08a92112016-11-09 13:26:45 -08001956 }
1957 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07001958}
1959
Ethan Nicholasfc994162019-06-06 10:04:27 -04001960std::unique_ptr<Expression> IRGenerator::convertTernaryExpression(const ASTNode& node) {
1961 SkASSERT(node.fKind == ASTNode::Kind::kTernary);
1962 auto iter = node.begin();
1963 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
ethannicholasd598f792016-07-25 10:08:54 -07001964 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -07001965 if (!test) {
1966 return nullptr;
1967 }
John Stiles4c412bc2020-10-13 11:19:41 -04001968 std::unique_ptr<Expression> ifTrue;
1969 std::unique_ptr<Expression> ifFalse;
1970 {
1971 AutoDisableInline disableInline(this);
1972 ifTrue = this->convertExpression(*(iter++));
1973 if (!ifTrue) {
1974 return nullptr;
1975 }
1976 ifFalse = this->convertExpression(*(iter++));
1977 if (!ifFalse) {
1978 return nullptr;
1979 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001980 }
ethannicholasd598f792016-07-25 10:08:54 -07001981 const Type* trueType;
1982 const Type* falseType;
1983 const Type* resultType;
Brian Osman0acb5b52020-09-02 13:45:47 -04001984 if (!determine_binary_type(fContext, fSettings->fAllowNarrowingConversions,
1985 Token::Kind::TK_EQEQ, ifTrue->type(), ifFalse->type(),
1986 &trueType, &falseType, &resultType) ||
1987 trueType != falseType) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001988 fErrors.error(node.fOffset, "ternary operator result mismatch: '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04001989 ifTrue->type().displayName() + "', '" +
1990 ifFalse->type().displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001991 return nullptr;
1992 }
Brian Osman82329002020-07-21 09:39:27 -04001993 if (trueType->nonnullable() == *fContext.fFragmentProcessor_Type) {
1994 fErrors.error(node.fOffset,
1995 "ternary expression of type '" + trueType->displayName() + "' not allowed");
1996 return nullptr;
1997 }
ethannicholasd598f792016-07-25 10:08:54 -07001998 ifTrue = this->coerce(std::move(ifTrue), *trueType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05001999 if (!ifTrue) {
2000 return nullptr;
2001 }
ethannicholasd598f792016-07-25 10:08:54 -07002002 ifFalse = this->coerce(std::move(ifFalse), *falseType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05002003 if (!ifFalse) {
2004 return nullptr;
2005 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002006 if (test->kind() == Expression::Kind::kBoolLiteral) {
ethannicholas08a92112016-11-09 13:26:45 -08002007 // static boolean test, just return one of the branches
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002008 if (test->as<BoolLiteral>().value()) {
ethannicholas08a92112016-11-09 13:26:45 -08002009 return ifTrue;
2010 } else {
2011 return ifFalse;
2012 }
2013 }
John Stiles8fa3b4e2020-09-02 11:27:23 -04002014 return std::make_unique<TernaryExpression>(node.fOffset,
2015 std::move(test),
2016 std::move(ifTrue),
2017 std::move(ifFalse));
ethannicholasb3058bd2016-07-01 08:22:01 -07002018}
2019
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002020void IRGenerator::copyIntrinsicIfNeeded(const FunctionDeclaration& function) {
Brian Osman00a8b5b2020-10-02 09:06:04 -04002021 if (const ProgramElement* found = fIntrinsics->findAndInclude(function.description())) {
Brian Osman2b469eb2020-09-21 11:32:10 -04002022 const FunctionDefinition& original = found->as<FunctionDefinition>();
John Stiles9878d9e2020-09-22 15:40:16 -04002023
2024 // Sort the referenced intrinsics into a consistent order; otherwise our output will become
2025 // non-deterministic.
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002026 std::vector<const FunctionDeclaration*> intrinsics(original.referencedIntrinsics().begin(),
2027 original.referencedIntrinsics().end());
John Stiles9878d9e2020-09-22 15:40:16 -04002028 std::sort(intrinsics.begin(), intrinsics.end(),
2029 [](const FunctionDeclaration* a, const FunctionDeclaration* b) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002030 if (a->isBuiltin() != b->isBuiltin()) {
2031 return a->isBuiltin() < b->isBuiltin();
John Stiles9878d9e2020-09-22 15:40:16 -04002032 }
2033 if (a->fOffset != b->fOffset) {
2034 return a->fOffset < b->fOffset;
2035 }
Ethan Nicholase2c49992020-10-05 11:49:11 -04002036 if (a->name() != b->name()) {
2037 return a->name() < b->name();
John Stiles9878d9e2020-09-22 15:40:16 -04002038 }
2039 return a->description() < b->description();
2040 });
2041 for (const FunctionDeclaration* f : intrinsics) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002042 this->copyIntrinsicIfNeeded(*f);
2043 }
John Stiles607d36b2020-10-19 15:00:01 -04002044
John Stiles1c823672020-10-20 10:23:50 -04002045 fProgramElements->push_back(original.clone());
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002046 }
2047}
2048
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002049std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05002050 const FunctionDeclaration& function,
John Stiles8e3b6be2020-10-13 11:14:08 -04002051 ExpressionArray arguments) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002052 if (function.isBuiltin()) {
2053 if (function.definition()) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002054 fReferencedIntrinsics.insert(&function);
2055 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002056 if (!fIsBuiltinCode && fIntrinsics) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002057 this->copyIntrinsicIfNeeded(function);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05002058 }
2059 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002060 if (function.parameters().size() != arguments.size()) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002061 String msg = "call to '" + function.name() + "' expected " +
Ethan Nicholased84b732020-10-08 11:45:44 -04002062 to_string((uint64_t) function.parameters().size()) +
ethannicholasb3058bd2016-07-01 08:22:01 -07002063 " argument";
Ethan Nicholased84b732020-10-08 11:45:44 -04002064 if (function.parameters().size() != 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002065 msg += "s";
2066 }
ethannicholas5961bc92016-10-12 06:39:56 -07002067 msg += ", but found " + to_string((uint64_t) arguments.size());
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002068 fErrors.error(offset, msg);
ethannicholasb3058bd2016-07-01 08:22:01 -07002069 return nullptr;
2070 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002071 if (fKind == Program::kPipelineStage_Kind && !function.definition() && !function.isBuiltin()) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002072 String msg = "call to undefined function '" + function.name() + "'";
Brian Osman5f6b41e2020-03-09 11:53:24 -04002073 fErrors.error(offset, msg);
2074 return nullptr;
2075 }
John Stilesfa889112020-10-12 19:03:43 -04002076 FunctionDeclaration::ParamTypes types;
ethannicholas471e8942016-10-28 09:02:46 -07002077 const Type* returnType;
2078 if (!function.determineFinalTypes(arguments, &types, &returnType)) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002079 String msg = "no match for " + function.name() + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002080 String separator;
ethannicholas471e8942016-10-28 09:02:46 -07002081 for (size_t i = 0; i < arguments.size(); i++) {
2082 msg += separator;
2083 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -04002084 msg += arguments[i]->type().displayName();
ethannicholas471e8942016-10-28 09:02:46 -07002085 }
2086 msg += ")";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002087 fErrors.error(offset, msg);
ethannicholas471e8942016-10-28 09:02:46 -07002088 return nullptr;
2089 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002090 for (size_t i = 0; i < arguments.size(); i++) {
ethannicholas471e8942016-10-28 09:02:46 -07002091 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
ethannicholasea4567c2016-10-17 11:24:37 -07002092 if (!arguments[i]) {
2093 return nullptr;
2094 }
Ethan Nicholased84b732020-10-08 11:45:44 -04002095 const Modifiers& paramModifiers = function.parameters()[i]->modifiers();
John Stiles978674a2020-09-23 15:24:51 -04002096 if (paramModifiers.fFlags & Modifiers::kOut_Flag) {
2097 if (!this->setRefKind(*arguments[i], paramModifiers.fFlags & Modifiers::kIn_Flag
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002098 ? VariableReference::RefKind::kReadWrite
2099 : VariableReference::RefKind::kPointer)) {
John Stiles978674a2020-09-23 15:24:51 -04002100 return nullptr;
2101 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002102 }
2103 }
John Stilesea9ab822020-08-31 09:55:04 -04002104
John Stiles4c412bc2020-10-13 11:19:41 -04002105 auto funcCall = std::make_unique<FunctionCall>(offset, returnType, &function,
2106 std::move(arguments));
2107 if (fCanInline &&
2108 fInliner->isSafeToInline(funcCall->function().definition()) &&
2109 !fInliner->isLargeFunction(funcCall->function().definition())) {
2110 Inliner::InlinedCall inlinedCall = fInliner->inlineCall(funcCall.get(), fSymbolTable.get(),
2111 fCurrentFunction);
2112 if (inlinedCall.fInlinedBody) {
2113 fExtraStatements.push_back(std::move(inlinedCall.fInlinedBody));
2114 }
2115 return std::move(inlinedCall.fReplacementExpr);
2116 }
2117
2118 return std::move(funcCall);
ethannicholasb3058bd2016-07-01 08:22:01 -07002119}
2120
2121/**
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002122 * Determines the cost of coercing the arguments of a function to the required types. Cost has no
Brian Osman0acb5b52020-09-02 13:45:47 -04002123 * particular meaning other than "lower costs are preferred". Returns CoercionCost::Impossible() if
2124 * the call is not valid.
ethannicholasb3058bd2016-07-01 08:22:01 -07002125 */
Brian Osman0acb5b52020-09-02 13:45:47 -04002126CoercionCost IRGenerator::callCost(const FunctionDeclaration& function,
John Stiles8e3b6be2020-10-13 11:14:08 -04002127 const ExpressionArray& arguments) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002128 if (function.parameters().size() != arguments.size()) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002129 return CoercionCost::Impossible();
ethannicholasb3058bd2016-07-01 08:22:01 -07002130 }
John Stilesfa889112020-10-12 19:03:43 -04002131 FunctionDeclaration::ParamTypes types;
ethannicholas471e8942016-10-28 09:02:46 -07002132 const Type* ignored;
2133 if (!function.determineFinalTypes(arguments, &types, &ignored)) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002134 return CoercionCost::Impossible();
ethannicholas471e8942016-10-28 09:02:46 -07002135 }
Brian Osman0acb5b52020-09-02 13:45:47 -04002136 CoercionCost total = CoercionCost::Free();
ethannicholasb3058bd2016-07-01 08:22:01 -07002137 for (size_t i = 0; i < arguments.size(); i++) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002138 total = total + arguments[i]->coercionCost(*types[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -07002139 }
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002140 return total;
ethannicholasb3058bd2016-07-01 08:22:01 -07002141}
2142
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002143std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05002144 std::unique_ptr<Expression> functionValue,
John Stiles8e3b6be2020-10-13 11:14:08 -04002145 ExpressionArray arguments) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002146 switch (functionValue->kind()) {
2147 case Expression::Kind::kTypeReference:
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002148 return this->convertConstructor(offset,
Ethan Nicholas5194a702020-10-12 11:12:12 -04002149 functionValue->as<TypeReference>().value(),
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002150 std::move(arguments));
Ethan Nicholase6592142020-09-08 10:22:09 -04002151 case Expression::Kind::kExternalValue: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002152 const ExternalValue& v = functionValue->as<ExternalValueReference>().value();
2153 if (!v.canCall()) {
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002154 fErrors.error(offset, "this external value is not a function");
2155 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002156 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002157 int count = v.callParameterCount();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002158 if (count != (int) arguments.size()) {
2159 fErrors.error(offset, "external function expected " + to_string(count) +
2160 " arguments, but found " + to_string((int) arguments.size()));
2161 return nullptr;
2162 }
2163 static constexpr int PARAMETER_MAX = 16;
2164 SkASSERT(count < PARAMETER_MAX);
2165 const Type* types[PARAMETER_MAX];
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002166 v.getCallParameterTypes(types);
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002167 for (int i = 0; i < count; ++i) {
2168 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
2169 if (!arguments[i]) {
2170 return nullptr;
2171 }
2172 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002173 return std::make_unique<ExternalFunctionCall>(offset, &v, std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07002174 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002175 case Expression::Kind::kFunctionReference: {
John Stilesce591b72020-08-27 11:47:30 -04002176 const FunctionReference& ref = functionValue->as<FunctionReference>();
Ethan Nicholas5194a702020-10-12 11:12:12 -04002177 const std::vector<const FunctionDeclaration*>& functions = ref.functions();
Brian Osman0acb5b52020-09-02 13:45:47 -04002178 CoercionCost bestCost = CoercionCost::Impossible();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002179 const FunctionDeclaration* best = nullptr;
Ethan Nicholas5194a702020-10-12 11:12:12 -04002180 if (functions.size() > 1) {
2181 for (const auto& f : functions) {
Brian Osman0acb5b52020-09-02 13:45:47 -04002182 CoercionCost cost = this->callCost(*f, arguments);
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002183 if (cost < bestCost) {
2184 bestCost = cost;
2185 best = f;
2186 }
2187 }
2188 if (best) {
2189 return this->call(offset, *best, std::move(arguments));
2190 }
Ethan Nicholas5194a702020-10-12 11:12:12 -04002191 String msg = "no match for " + functions[0]->name() + "(";
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002192 String separator;
2193 for (size_t i = 0; i < arguments.size(); i++) {
2194 msg += separator;
2195 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -04002196 msg += arguments[i]->type().displayName();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002197 }
2198 msg += ")";
2199 fErrors.error(offset, msg);
2200 return nullptr;
2201 }
Ethan Nicholas5194a702020-10-12 11:12:12 -04002202 return this->call(offset, *functions[0], std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07002203 }
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002204 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002205 fErrors.error(offset, "not a function");
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002206 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002207 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002208}
2209
John Stiles8e3b6be2020-10-13 11:14:08 -04002210std::unique_ptr<Expression> IRGenerator::convertNumberConstructor(int offset,
2211 const Type& type,
2212 ExpressionArray args) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04002213 SkASSERT(type.isNumber());
Ethan Nicholas84645e32017-02-09 13:57:14 -05002214 if (args.size() != 1) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002215 fErrors.error(offset, "invalid arguments to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002216 "' constructor, (expected exactly 1 argument, but found " +
2217 to_string((uint64_t) args.size()) + ")");
ethannicholasb3058bd2016-07-01 08:22:01 -07002218 return nullptr;
2219 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002220 const Type& argType = args[0]->type();
2221 if (type == argType) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002222 return std::move(args[0]);
2223 }
John Stilesd0e48402020-09-22 14:00:40 -04002224 if (type.isFloat() && args.size() == 1 && args[0]->is<FloatLiteral>()) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002225 SKSL_FLOAT value = args[0]->as<FloatLiteral>().value();
John Stilesd0e48402020-09-22 14:00:40 -04002226 return std::make_unique<FloatLiteral>(offset, value, &type);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002227 }
John Stilesd0e48402020-09-22 14:00:40 -04002228 if (type.isFloat() && args.size() == 1 && args[0]->is<IntLiteral>()) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002229 int64_t value = args[0]->as<IntLiteral>().value();
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002230 return std::make_unique<FloatLiteral>(offset, (float)value, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002231 }
John Stilesd0e48402020-09-22 14:00:40 -04002232 if (args[0]->is<IntLiteral>() && (type == *fContext.fInt_Type ||
2233 type == *fContext.fUInt_Type)) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002234 return std::make_unique<IntLiteral>(offset, args[0]->as<IntLiteral>().value(), &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002235 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002236 if (argType == *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002237 std::unique_ptr<IntLiteral> zero(new IntLiteral(fContext, offset, 0));
2238 std::unique_ptr<IntLiteral> one(new IntLiteral(fContext, offset, 1));
John Stilesd0e48402020-09-22 14:00:40 -04002239 return std::make_unique<TernaryExpression>(offset, std::move(args[0]),
2240 this->coerce(std::move(one), type),
2241 this->coerce(std::move(zero), type));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002242 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002243 if (!argType.isNumber()) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002244 fErrors.error(offset, "invalid argument to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002245 "' constructor (expected a number or bool, but found '" +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002246 argType.displayName() + "')");
Ethan Nicholas84645e32017-02-09 13:57:14 -05002247 return nullptr;
2248 }
John Stilesd0e48402020-09-22 14:00:40 -04002249 return std::make_unique<Constructor>(offset, &type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002250}
2251
John Stiles36374402020-08-13 12:16:44 -04002252static int component_count(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002253 switch (type.typeKind()) {
2254 case Type::TypeKind::kVector:
Ethan Nicholas84645e32017-02-09 13:57:14 -05002255 return type.columns();
Ethan Nicholase6592142020-09-08 10:22:09 -04002256 case Type::TypeKind::kMatrix:
Ethan Nicholas84645e32017-02-09 13:57:14 -05002257 return type.columns() * type.rows();
2258 default:
2259 return 1;
2260 }
2261}
2262
John Stiles8e3b6be2020-10-13 11:14:08 -04002263std::unique_ptr<Expression> IRGenerator::convertCompoundConstructor(int offset,
2264 const Type& type,
2265 ExpressionArray args) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002266 SkASSERT(type.typeKind() == Type::TypeKind::kVector ||
2267 type.typeKind() == Type::TypeKind::kMatrix);
2268 if (type.typeKind() == Type::TypeKind::kMatrix && args.size() == 1 &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04002269 args[0]->type().typeKind() == Type::TypeKind::kMatrix) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002270 // matrix from matrix is always legal
Ethan Nicholas30d30222020-09-11 12:27:26 -04002271 return std::unique_ptr<Expression>(new Constructor(offset, &type, std::move(args)));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002272 }
2273 int actual = 0;
2274 int expected = type.rows() * type.columns();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002275 if (args.size() != 1 || expected != component_count(args[0]->type()) ||
2276 type.componentType().isNumber() != args[0]->type().componentType().isNumber()) {
ethannicholas5961bc92016-10-12 06:39:56 -07002277 for (size_t i = 0; i < args.size(); i++) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002278 const Type& argType = args[i]->type();
2279 if (argType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002280 if (type.componentType().isNumber() !=
Ethan Nicholas30d30222020-09-11 12:27:26 -04002281 argType.componentType().isNumber()) {
2282 fErrors.error(offset, "'" + argType.displayName() + "' is not a valid "
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002283 "parameter to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002284 "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002285 return nullptr;
2286 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002287 actual += argType.columns();
2288 } else if (argType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002289 actual += 1;
Ethan Nicholase6592142020-09-08 10:22:09 -04002290 if (type.typeKind() != Type::TypeKind::kScalar) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002291 args[i] = this->coerce(std::move(args[i]), type.componentType());
2292 if (!args[i]) {
2293 return nullptr;
2294 }
2295 }
2296 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002297 fErrors.error(offset, "'" + argType.displayName() + "' is not a valid "
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002298 "parameter to '" + type.displayName() + "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002299 return nullptr;
2300 }
2301 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05002302 if (actual != 1 && actual != expected) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002303 fErrors.error(offset, "invalid arguments to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002304 "' constructor (expected " + to_string(expected) +
2305 " scalars, but found " + to_string(actual) + ")");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002306 return nullptr;
2307 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002308 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002309 return std::unique_ptr<Expression>(new Constructor(offset, &type, std::move(args)));
ethannicholasb3058bd2016-07-01 08:22:01 -07002310}
2311
John Stiles8e3b6be2020-10-13 11:14:08 -04002312std::unique_ptr<Expression> IRGenerator::convertConstructor(int offset,
2313 const Type& type,
2314 ExpressionArray args) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002315 // FIXME: add support for structs
Ethan Nicholas30d30222020-09-11 12:27:26 -04002316 if (args.size() == 1 && args[0]->type() == type &&
Brian Osman82329002020-07-21 09:39:27 -04002317 type.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002318 // argument is already the right type, just return it
2319 return std::move(args[0]);
2320 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002321 Type::TypeKind kind = type.typeKind();
Ethan Nicholas84645e32017-02-09 13:57:14 -05002322 if (type.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002323 return this->convertNumberConstructor(offset, type, std::move(args));
Ethan Nicholase6592142020-09-08 10:22:09 -04002324 } else if (kind == Type::TypeKind::kArray) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002325 const Type& base = type.componentType();
2326 for (size_t i = 0; i < args.size(); i++) {
2327 args[i] = this->coerce(std::move(args[i]), base);
2328 if (!args[i]) {
2329 return nullptr;
2330 }
2331 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002332 return std::make_unique<Constructor>(offset, &type, std::move(args));
Ethan Nicholase6592142020-09-08 10:22:09 -04002333 } else if (kind == Type::TypeKind::kVector || kind == Type::TypeKind::kMatrix) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002334 return this->convertCompoundConstructor(offset, type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002335 } else {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002336 fErrors.error(offset, "cannot construct '" + type.displayName() + "'");
Ethan Nicholas84645e32017-02-09 13:57:14 -05002337 return nullptr;
2338 }
2339}
2340
Ethan Nicholasfc994162019-06-06 10:04:27 -04002341std::unique_ptr<Expression> IRGenerator::convertPrefixExpression(const ASTNode& expression) {
2342 SkASSERT(expression.fKind == ASTNode::Kind::kPrefix);
2343 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
ethannicholasb3058bd2016-07-01 08:22:01 -07002344 if (!base) {
2345 return nullptr;
2346 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002347 const Type& baseType = base->type();
Ethan Nicholasfc994162019-06-06 10:04:27 -04002348 switch (expression.getToken().fKind) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002349 case Token::Kind::TK_PLUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002350 if (!baseType.isNumber() && baseType.typeKind() != Type::TypeKind::kVector &&
2351 baseType != *fContext.fFloatLiteral_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002352 fErrors.error(expression.fOffset,
Ethan Nicholas30d30222020-09-11 12:27:26 -04002353 "'+' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002354 return nullptr;
2355 }
2356 return base;
John Stiles978674a2020-09-23 15:24:51 -04002357
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002358 case Token::Kind::TK_MINUS:
John Stiles978674a2020-09-23 15:24:51 -04002359 if (base->is<IntLiteral>()) {
2360 return std::make_unique<IntLiteral>(fContext, base->fOffset,
Ethan Nicholase96cdd12020-09-28 16:27:18 -04002361 -base->as<IntLiteral>().value());
ethannicholasb3058bd2016-07-01 08:22:01 -07002362 }
John Stiles978674a2020-09-23 15:24:51 -04002363 if (base->is<FloatLiteral>()) {
2364 return std::make_unique<FloatLiteral>(fContext, base->fOffset,
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04002365 -base->as<FloatLiteral>().value());
ethannicholasb3058bd2016-07-01 08:22:01 -07002366 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002367 if (!baseType.isNumber() && baseType.typeKind() != Type::TypeKind::kVector) {
Ethan Nicholase1f55022019-02-05 17:17:40 -05002368 fErrors.error(expression.fOffset,
Ethan Nicholas30d30222020-09-11 12:27:26 -04002369 "'-' cannot operate on '" + baseType.displayName() + "'");
Ethan Nicholase1f55022019-02-05 17:17:40 -05002370 return nullptr;
2371 }
John Stiles978674a2020-09-23 15:24:51 -04002372 return std::make_unique<PrefixExpression>(Token::Kind::TK_MINUS, std::move(base));
2373
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002374 case Token::Kind::TK_PLUSPLUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002375 if (!baseType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002376 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002377 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002378 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002379 return nullptr;
2380 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002381 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002382 return nullptr;
2383 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002384 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002385 case Token::Kind::TK_MINUSMINUS:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002386 if (!baseType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002387 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002388 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002389 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002390 return nullptr;
2391 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002392 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002393 return nullptr;
2394 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002395 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002396 case Token::Kind::TK_LOGICALNOT:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002397 if (baseType != *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002398 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002399 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002400 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002401 return nullptr;
2402 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002403 if (base->kind() == Expression::Kind::kBoolLiteral) {
John Stiles978674a2020-09-23 15:24:51 -04002404 return std::make_unique<BoolLiteral>(fContext, base->fOffset,
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002405 !base->as<BoolLiteral>().value());
ethannicholas08a92112016-11-09 13:26:45 -08002406 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002407 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002408 case Token::Kind::TK_BITWISENOT:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002409 if (baseType != *fContext.fInt_Type && baseType != *fContext.fUInt_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002410 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002411 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002412 "' cannot operate on '" + baseType.displayName() + "'");
ethannicholas5961bc92016-10-12 06:39:56 -07002413 return nullptr;
2414 }
2415 break;
Ethan Nicholas11d53972016-11-28 11:23:23 -05002416 default:
ethannicholasb3058bd2016-07-01 08:22:01 -07002417 ABORT("unsupported prefix operator\n");
2418 }
John Stiles978674a2020-09-23 15:24:51 -04002419 return std::make_unique<PrefixExpression>(expression.getToken().fKind, std::move(base));
ethannicholasb3058bd2016-07-01 08:22:01 -07002420}
2421
2422std::unique_ptr<Expression> IRGenerator::convertIndex(std::unique_ptr<Expression> base,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002423 const ASTNode& index) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002424 if (base->kind() == Expression::Kind::kTypeReference) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002425 if (index.fKind == ASTNode::Kind::kInt) {
Ethan Nicholas5194a702020-10-12 11:12:12 -04002426 const Type& oldType = base->as<TypeReference>().value();
Ethan Nicholasfc994162019-06-06 10:04:27 -04002427 SKSL_INT size = index.getInt();
John Stiles3ae071e2020-08-05 15:29:29 -04002428 const Type* newType = fSymbolTable->takeOwnershipOfSymbol(
2429 std::make_unique<Type>(oldType.name() + "[" + to_string(size) + "]",
Ethan Nicholase6592142020-09-08 10:22:09 -04002430 Type::TypeKind::kArray, oldType, size));
2431 return std::make_unique<TypeReference>(fContext, base->fOffset, newType);
Ethan Nicholas50afc172017-02-16 14:49:57 -05002432
2433 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002434 fErrors.error(base->fOffset, "array size must be a constant");
Ethan Nicholas50afc172017-02-16 14:49:57 -05002435 return nullptr;
2436 }
2437 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002438 const Type& baseType = base->type();
2439 if (baseType.typeKind() != Type::TypeKind::kArray &&
2440 baseType.typeKind() != Type::TypeKind::kMatrix &&
2441 baseType.typeKind() != Type::TypeKind::kVector) {
2442 fErrors.error(base->fOffset, "expected array, but found '" + baseType.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002443 "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002444 return nullptr;
2445 }
2446 std::unique_ptr<Expression> converted = this->convertExpression(index);
2447 if (!converted) {
2448 return nullptr;
2449 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002450 if (converted->type() != *fContext.fUInt_Type) {
ethannicholas5961bc92016-10-12 06:39:56 -07002451 converted = this->coerce(std::move(converted), *fContext.fInt_Type);
2452 if (!converted) {
2453 return nullptr;
2454 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002455 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002456 return std::make_unique<IndexExpression>(fContext, std::move(base), std::move(converted));
ethannicholasb3058bd2016-07-01 08:22:01 -07002457}
2458
2459std::unique_ptr<Expression> IRGenerator::convertField(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002460 StringFragment field) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002461 if (base->kind() == Expression::Kind::kExternalValue) {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002462 const ExternalValue& ev = base->as<ExternalValueReference>().value();
Ethan Nicholas91164d12019-05-15 15:29:54 -04002463 ExternalValue* result = ev.getChild(String(field).c_str());
2464 if (!result) {
2465 fErrors.error(base->fOffset, "external value does not have a child named '" + field +
2466 "'");
2467 return nullptr;
2468 }
2469 return std::unique_ptr<Expression>(new ExternalValueReference(base->fOffset, result));
2470 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002471 const Type& baseType = base->type();
2472 auto fields = baseType.fields();
ethannicholasb3058bd2016-07-01 08:22:01 -07002473 for (size_t i = 0; i < fields.size(); i++) {
2474 if (fields[i].fName == field) {
2475 return std::unique_ptr<Expression>(new FieldAccess(std::move(base), (int) i));
2476 }
2477 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002478 fErrors.error(base->fOffset, "type '" + baseType.displayName() + "' does not have a field "
John Stiles68861e32020-09-25 16:02:07 -04002479 "named '" + field + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002480 return nullptr;
2481}
2482
Brian Osman25647672020-09-15 15:16:56 -04002483// Swizzles are complicated due to constant components. The most difficult case is a mask like
John Stiles6e49a372020-09-16 13:40:54 -04002484// '.x1w0'. A naive approach might turn that into 'float4(base.x, 1, base.w, 0)', but that evaluates
2485// 'base' twice. We instead group the swizzle mask ('xw') and constants ('1, 0') together and use a
Brian Osman25647672020-09-15 15:16:56 -04002486// 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 -04002487// 'float4(base.xw, 1, 0).xzyw'.
ethannicholasb3058bd2016-07-01 08:22:01 -07002488std::unique_ptr<Expression> IRGenerator::convertSwizzle(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002489 StringFragment fields) {
Brian Osman25647672020-09-15 15:16:56 -04002490 const int offset = base->fOffset;
Ethan Nicholas30d30222020-09-11 12:27:26 -04002491 const Type& baseType = base->type();
2492 if (baseType.typeKind() != Type::TypeKind::kVector && !baseType.isNumber()) {
Brian Osman25647672020-09-15 15:16:56 -04002493 fErrors.error(offset, "cannot swizzle value of type '" + baseType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002494 return nullptr;
2495 }
Brian Osman25647672020-09-15 15:16:56 -04002496
2497 if (fields.fLength > 4) {
2498 fErrors.error(offset, "too many components in swizzle mask '" + fields + "'");
2499 return nullptr;
2500 }
2501
John Stiles750109b2020-10-30 13:45:46 -04002502 ComponentArray maskComponents;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002503 for (size_t i = 0; i < fields.fLength; i++) {
Ethan Nicholas9e1138d2016-11-21 10:39:35 -05002504 switch (fields[i]) {
Ethan Nicholasac285b12019-02-12 16:05:18 -05002505 case '0':
Ethan Nicholasac285b12019-02-12 16:05:18 -05002506 case '1':
John Stiles6e49a372020-09-16 13:40:54 -04002507 // Skip over constant fields for now.
Ethan Nicholasac285b12019-02-12 16:05:18 -05002508 break;
Ethan Nicholase455f652019-09-13 12:52:55 -04002509 case 'x':
2510 case 'r':
Ethan Nicholas11d53972016-11-28 11:23:23 -05002511 case 's':
Ethan Nicholase455f652019-09-13 12:52:55 -04002512 case 'L':
Brian Osman25647672020-09-15 15:16:56 -04002513 maskComponents.push_back(0);
ethannicholasb3058bd2016-07-01 08:22:01 -07002514 break;
Ethan Nicholase455f652019-09-13 12:52:55 -04002515 case 'y':
2516 case 'g':
ethannicholasb3058bd2016-07-01 08:22:01 -07002517 case 't':
Ethan Nicholase455f652019-09-13 12:52:55 -04002518 case 'T':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002519 if (baseType.columns() >= 2) {
Brian Osman25647672020-09-15 15:16:56 -04002520 maskComponents.push_back(1);
ethannicholasb3058bd2016-07-01 08:22:01 -07002521 break;
2522 }
John Stiles30212b72020-06-11 17:55:07 -04002523 [[fallthrough]];
Ethan Nicholase455f652019-09-13 12:52:55 -04002524 case 'z':
2525 case 'b':
Ethan Nicholas11d53972016-11-28 11:23:23 -05002526 case 'p':
Ethan Nicholase455f652019-09-13 12:52:55 -04002527 case 'R':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002528 if (baseType.columns() >= 3) {
Brian Osman25647672020-09-15 15:16:56 -04002529 maskComponents.push_back(2);
ethannicholasb3058bd2016-07-01 08:22:01 -07002530 break;
2531 }
John Stiles30212b72020-06-11 17:55:07 -04002532 [[fallthrough]];
Ethan Nicholase455f652019-09-13 12:52:55 -04002533 case 'w':
2534 case 'a':
ethannicholasb3058bd2016-07-01 08:22:01 -07002535 case 'q':
Ethan Nicholase455f652019-09-13 12:52:55 -04002536 case 'B':
Ethan Nicholas30d30222020-09-11 12:27:26 -04002537 if (baseType.columns() >= 4) {
Brian Osman25647672020-09-15 15:16:56 -04002538 maskComponents.push_back(3);
ethannicholasb3058bd2016-07-01 08:22:01 -07002539 break;
2540 }
John Stiles30212b72020-06-11 17:55:07 -04002541 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -07002542 default:
Brian Osman25647672020-09-15 15:16:56 -04002543 fErrors.error(offset, String::printf("invalid swizzle component '%c'", fields[i]));
ethannicholasb3058bd2016-07-01 08:22:01 -07002544 return nullptr;
2545 }
2546 }
Brian Osman25647672020-09-15 15:16:56 -04002547 if (maskComponents.empty()) {
2548 fErrors.error(offset, "swizzle must refer to base expression");
ethannicholasb3058bd2016-07-01 08:22:01 -07002549 return nullptr;
2550 }
Brian Osman25647672020-09-15 15:16:56 -04002551
2552 // First, we need a vector expression that is the non-constant portion of the swizzle, packed:
2553 // scalar.xxx -> type3(scalar)
2554 // scalar.x0x0 -> type2(scalar)
2555 // vector.zyx -> vector.zyx
2556 // vector.x0y0 -> vector.xy
2557 std::unique_ptr<Expression> expr;
Ethan Nicholas30d30222020-09-11 12:27:26 -04002558 if (baseType.isNumber()) {
John Stiles8e3b6be2020-10-13 11:14:08 -04002559 ExpressionArray scalarConstructorArgs;
Brian Osman25647672020-09-15 15:16:56 -04002560 scalarConstructorArgs.push_back(std::move(base));
2561 expr = std::make_unique<Constructor>(
2562 offset, &baseType.toCompound(fContext, maskComponents.size(), 1),
2563 std::move(scalarConstructorArgs));
2564 } else {
2565 expr = std::make_unique<Swizzle>(fContext, std::move(base), maskComponents);
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002566 }
Brian Osman25647672020-09-15 15:16:56 -04002567
John Stiles6e49a372020-09-16 13:40:54 -04002568 // If we have processed the entire swizzle, we're done.
2569 if (maskComponents.size() == fields.fLength) {
Brian Osman25647672020-09-15 15:16:56 -04002570 return expr;
2571 }
2572
2573 // Now we create a constructor that has the correct number of elements for the final swizzle,
John Stiles6e49a372020-09-16 13:40:54 -04002574 // with all fields at the start. It's not finished yet; constants we need will be added below.
2575 // scalar.x0x0 -> type4(type2(x), ...)
2576 // vector.y111 -> type4(vector.y, ...)
2577 // vector.z10x -> type4(vector.zx, ...)
Brian Osman25647672020-09-15 15:16:56 -04002578 //
John Stiles6e49a372020-09-16 13:40:54 -04002579 // We could create simpler IR in some cases by reordering here, if all fields are packed
Brian Osman25647672020-09-15 15:16:56 -04002580 // contiguously. The benefits are minor, so skip the optimization to keep the algorithm simple.
John Stiles6e49a372020-09-16 13:40:54 -04002581 // The constructor will have at most three arguments: { base value, constant 0, constant 1 }
John Stiles8e3b6be2020-10-13 11:14:08 -04002582 ExpressionArray constructorArgs;
John Stilesf4bda742020-10-14 16:57:41 -04002583 constructorArgs.reserve_back(3);
Brian Osman25647672020-09-15 15:16:56 -04002584 constructorArgs.push_back(std::move(expr));
John Stiles6e49a372020-09-16 13:40:54 -04002585
2586 // Apply another swizzle to shuffle the constants into the correct place. Any constant values we
2587 // need are also tacked on to the end of the constructor.
2588 // scalar.x0x0 -> type4(type2(x), 0).xyxy
2589 // vector.y111 -> type4(vector.y, 1).xyyy
2590 // vector.z10x -> type4(vector.zx, 1, 0).xzwy
Brian Osman25647672020-09-15 15:16:56 -04002591 const Type* numberType = baseType.isNumber() ? &baseType : &baseType.componentType();
John Stiles750109b2020-10-30 13:45:46 -04002592 ComponentArray swizzleComponents;
John Stiles6e49a372020-09-16 13:40:54 -04002593 int maskFieldIdx = 0;
2594 int constantFieldIdx = maskComponents.size();
2595 int constantZeroIdx = -1, constantOneIdx = -1;
Brian Osman25647672020-09-15 15:16:56 -04002596
Brian Osman25647672020-09-15 15:16:56 -04002597 for (size_t i = 0; i < fields.fLength; i++) {
John Stiles6e49a372020-09-16 13:40:54 -04002598 switch (fields[i]) {
2599 case '0':
2600 if (constantZeroIdx == -1) {
John Stilesd0e48402020-09-22 14:00:40 -04002601 // Synthesize a 'type(0)' argument at the end of the constructor.
John Stiles8e3b6be2020-10-13 11:14:08 -04002602 auto zero = std::make_unique<Constructor>(offset, numberType,
2603 ExpressionArray{});
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002604 zero->arguments().push_back(std::make_unique<IntLiteral>(fContext, offset,
2605 /*fValue=*/0));
John Stilesd0e48402020-09-22 14:00:40 -04002606 constructorArgs.push_back(std::move(zero));
John Stiles6e49a372020-09-16 13:40:54 -04002607 constantZeroIdx = constantFieldIdx++;
2608 }
2609 swizzleComponents.push_back(constantZeroIdx);
2610 break;
2611 case '1':
2612 if (constantOneIdx == -1) {
John Stilesd0e48402020-09-22 14:00:40 -04002613 // Synthesize a 'type(1)' argument at the end of the constructor.
John Stiles8e3b6be2020-10-13 11:14:08 -04002614 auto one = std::make_unique<Constructor>(offset, numberType, ExpressionArray{});
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002615 one->arguments().push_back(std::make_unique<IntLiteral>(fContext, offset,
2616 /*fValue=*/1));
John Stilesd0e48402020-09-22 14:00:40 -04002617 constructorArgs.push_back(std::move(one));
John Stiles6e49a372020-09-16 13:40:54 -04002618 constantOneIdx = constantFieldIdx++;
2619 }
2620 swizzleComponents.push_back(constantOneIdx);
2621 break;
2622 default:
2623 // The non-constant fields are already in the expected order.
2624 swizzleComponents.push_back(maskFieldIdx++);
2625 break;
Brian Osman25647672020-09-15 15:16:56 -04002626 }
2627 }
2628
John Stiles6e49a372020-09-16 13:40:54 -04002629 expr = std::make_unique<Constructor>(offset,
2630 &numberType->toCompound(fContext, constantFieldIdx, 1),
2631 std::move(constructorArgs));
2632
John Stilesb23ea382020-09-16 13:41:14 -04002633 // For some of our most common use cases ('.xyz0', '.xyz1'), we will now have an identity
2634 // swizzle; in those cases we can just return the constructor without the swizzle attached.
2635 for (size_t i = 0; i < swizzleComponents.size(); ++i) {
2636 if (swizzleComponents[i] != int(i)) {
2637 // The swizzle has an effect, so apply it.
John Stiles750109b2020-10-30 13:45:46 -04002638 return std::make_unique<Swizzle>(fContext, std::move(expr), swizzleComponents);
John Stilesb23ea382020-09-16 13:41:14 -04002639 }
2640 }
2641
2642 // The swizzle was a no-op; return the constructor expression directly.
2643 return expr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002644}
2645
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002646const Type* IRGenerator::typeForSetting(int offset, String name) const {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002647 auto found = fCapsMap.find(name);
2648 if (found == fCapsMap.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002649 fErrors.error(offset, "unknown capability flag '" + name + "'");
Ethan Nicholas3605ace2016-11-21 15:59:48 -05002650 return nullptr;
2651 }
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002652 switch (found->second.fKind) {
2653 case Program::Settings::Value::kBool_Kind: return fContext.fBool_Type.get();
2654 case Program::Settings::Value::kFloat_Kind: return fContext.fFloat_Type.get();
2655 case Program::Settings::Value::kInt_Kind: return fContext.fInt_Type.get();
2656 }
2657 SkUNREACHABLE;
2658 return nullptr;
2659}
2660
2661std::unique_ptr<Expression> IRGenerator::valueForSetting(int offset, String name) const {
2662 auto found = fCapsMap.find(name);
2663 if (found == fCapsMap.end()) {
2664 fErrors.error(offset, "unknown capability flag '" + name + "'");
2665 return nullptr;
2666 }
2667 return found->second.literal(fContext, offset);
Ethan Nicholas762466e2017-06-29 10:03:38 -04002668}
2669
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002670std::unique_ptr<Expression> IRGenerator::convertTypeField(int offset, const Type& type,
2671 StringFragment field) {
Brian Osman1313d1a2020-09-08 10:34:30 -04002672 // Find the Enum element that this type refers to (if any)
Brian Osman2b469eb2020-09-21 11:32:10 -04002673 const ProgramElement* enumElement = nullptr;
2674 for (const auto& e : *fProgramElements) {
Ethan Nicholasd83ded82020-09-29 17:05:54 -04002675 if (e->is<Enum>() && type.name() == e->as<Enum>().typeName()) {
Brian Osman2b469eb2020-09-21 11:32:10 -04002676 enumElement = e.get();
2677 break;
Brian Osman1313d1a2020-09-08 10:34:30 -04002678 }
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002679 }
Brian Osman1313d1a2020-09-08 10:34:30 -04002680
2681 if (enumElement) {
2682 // We found the Enum element. Look for 'field' as a member.
2683 std::shared_ptr<SymbolTable> old = fSymbolTable;
Ethan Nicholasd83ded82020-09-29 17:05:54 -04002684 fSymbolTable = enumElement->as<Enum>().symbols();
Brian Osman1313d1a2020-09-08 10:34:30 -04002685 std::unique_ptr<Expression> result = convertIdentifier(
2686 ASTNode(&fFile->fNodes, offset, ASTNode::Kind::kIdentifier, field));
2687 if (result) {
Ethan Nicholas78686922020-10-08 06:46:27 -04002688 const Variable& v = *result->as<VariableReference>().variable();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002689 SkASSERT(v.initialValue());
Brian Osman1313d1a2020-09-08 10:34:30 -04002690 result = std::make_unique<IntLiteral>(
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002691 offset, v.initialValue()->as<IntLiteral>().value(), &type);
Brian Osman1313d1a2020-09-08 10:34:30 -04002692 } else {
2693 fErrors.error(offset,
Ethan Nicholase2c49992020-10-05 11:49:11 -04002694 "type '" + type.name() + "' does not have a member named '" + field +
2695 "'");
Brian Osman1313d1a2020-09-08 10:34:30 -04002696 }
2697 fSymbolTable = old;
2698 return result;
2699 } else {
2700 // No Enum element? Check the intrinsics, clone it into the program, try again.
Brian Osman00a8b5b2020-10-02 09:06:04 -04002701 if (!fIsBuiltinCode && fIntrinsics) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04002702 if (const ProgramElement* found = fIntrinsics->findAndInclude(type.name())) {
Brian Osman00a8b5b2020-10-02 09:06:04 -04002703 fProgramElements->push_back(found->clone());
2704 return this->convertTypeField(offset, type, field);
2705 }
Ethan Nicholasdb80f692019-11-22 14:06:12 -05002706 }
Brian Osman1313d1a2020-09-08 10:34:30 -04002707 fErrors.error(offset,
Ethan Nicholase2c49992020-10-05 11:49:11 -04002708 "type '" + type.displayName() + "' does not have a member named '" + field +
2709 "'");
Brian Osman1313d1a2020-09-08 10:34:30 -04002710 return nullptr;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002711 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05002712}
2713
Ethan Nicholasfc994162019-06-06 10:04:27 -04002714std::unique_ptr<Expression> IRGenerator::convertIndexExpression(const ASTNode& index) {
2715 SkASSERT(index.fKind == ASTNode::Kind::kIndex);
2716 auto iter = index.begin();
2717 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07002718 if (!base) {
2719 return nullptr;
2720 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002721 if (iter != index.end()) {
2722 return this->convertIndex(std::move(base), *(iter++));
Ethan Nicholase6592142020-09-08 10:22:09 -04002723 } else if (base->kind() == Expression::Kind::kTypeReference) {
Ethan Nicholas5194a702020-10-12 11:12:12 -04002724 const Type& oldType = base->as<TypeReference>().value();
John Stiles3ae071e2020-08-05 15:29:29 -04002725 const Type* newType = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
Brian Osmane8c26082020-10-01 17:22:45 -04002726 oldType.name() + "[]", Type::TypeKind::kArray, oldType, Type::kUnsizedArray));
Ethan Nicholase6592142020-09-08 10:22:09 -04002727 return std::make_unique<TypeReference>(fContext, base->fOffset, newType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002728 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002729 fErrors.error(index.fOffset, "'[]' must follow a type name");
2730 return nullptr;
2731}
2732
2733std::unique_ptr<Expression> IRGenerator::convertCallExpression(const ASTNode& callNode) {
2734 SkASSERT(callNode.fKind == ASTNode::Kind::kCall);
2735 auto iter = callNode.begin();
2736 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
2737 if (!base) {
2738 return nullptr;
2739 }
John Stiles8e3b6be2020-10-13 11:14:08 -04002740 ExpressionArray arguments;
Ethan Nicholasfc994162019-06-06 10:04:27 -04002741 for (; iter != callNode.end(); ++iter) {
2742 std::unique_ptr<Expression> converted = this->convertExpression(*iter);
2743 if (!converted) {
2744 return nullptr;
2745 }
2746 arguments.push_back(std::move(converted));
2747 }
2748 return this->call(callNode.fOffset, std::move(base), std::move(arguments));
2749}
2750
2751std::unique_ptr<Expression> IRGenerator::convertFieldExpression(const ASTNode& fieldNode) {
2752 std::unique_ptr<Expression> base = this->convertExpression(*fieldNode.begin());
2753 if (!base) {
2754 return nullptr;
2755 }
2756 StringFragment field = fieldNode.getString();
Ethan Nicholas30d30222020-09-11 12:27:26 -04002757 const Type& baseType = base->type();
2758 if (baseType == *fContext.fSkCaps_Type) {
Ethan Nicholas01ec7e82020-10-08 12:10:12 -04002759 const Type* type = this->typeForSetting(fieldNode.fOffset, field);
2760 if (!type) {
2761 return nullptr;
2762 }
2763 return std::make_unique<Setting>(fieldNode.fOffset, field, type);
Ethan Nicholasfc994162019-06-06 10:04:27 -04002764 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002765 if (base->kind() == Expression::Kind::kExternalValue) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002766 return this->convertField(std::move(base), field);
2767 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002768 switch (baseType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002769 case Type::TypeKind::kOther:
2770 case Type::TypeKind::kStruct:
Ethan Nicholasfc994162019-06-06 10:04:27 -04002771 return this->convertField(std::move(base), field);
2772 default:
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002773 return this->convertSwizzle(std::move(base), field);
Ethan Nicholasfc994162019-06-06 10:04:27 -04002774 }
2775}
2776
Brian Osman6518d772020-09-10 16:50:06 -04002777std::unique_ptr<Expression> IRGenerator::convertScopeExpression(const ASTNode& scopeNode) {
2778 std::unique_ptr<Expression> base = this->convertExpression(*scopeNode.begin());
2779 if (!base) {
2780 return nullptr;
2781 }
2782 if (!base->is<TypeReference>()) {
2783 fErrors.error(scopeNode.fOffset, "'::' must follow a type name");
2784 return nullptr;
2785 }
2786 StringFragment member = scopeNode.getString();
Ethan Nicholas5194a702020-10-12 11:12:12 -04002787 return this->convertTypeField(base->fOffset, base->as<TypeReference>().value(), member);
Brian Osman6518d772020-09-10 16:50:06 -04002788}
2789
Ethan Nicholasfc994162019-06-06 10:04:27 -04002790std::unique_ptr<Expression> IRGenerator::convertPostfixExpression(const ASTNode& expression) {
2791 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
2792 if (!base) {
2793 return nullptr;
2794 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002795 const Type& baseType = base->type();
2796 if (!baseType.isNumber()) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002797 fErrors.error(expression.fOffset,
2798 "'" + String(Compiler::OperatorName(expression.getToken().fKind)) +
Ethan Nicholas30d30222020-09-11 12:27:26 -04002799 "' cannot operate on '" + baseType.displayName() + "'");
Ethan Nicholasfc994162019-06-06 10:04:27 -04002800 return nullptr;
2801 }
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002802 if (!this->setRefKind(*base, VariableReference::RefKind::kReadWrite)) {
John Stiles978674a2020-09-23 15:24:51 -04002803 return nullptr;
2804 }
2805 return std::make_unique<PostfixExpression>(std::move(base), expression.getToken().fKind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002806}
2807
2808void IRGenerator::checkValid(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002809 switch (expr.kind()) {
2810 case Expression::Kind::kFunctionReference:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002811 fErrors.error(expr.fOffset, "expected '(' to begin function call");
ethannicholasb3058bd2016-07-01 08:22:01 -07002812 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002813 case Expression::Kind::kTypeReference:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002814 fErrors.error(expr.fOffset, "expected '(' to begin constructor invocation");
ethannicholasb3058bd2016-07-01 08:22:01 -07002815 break;
2816 default:
Ethan Nicholas30d30222020-09-11 12:27:26 -04002817 if (expr.type() == *fContext.fInvalid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002818 fErrors.error(expr.fOffset, "invalid expression");
ethannicholasea4567c2016-10-17 11:24:37 -07002819 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002820 }
2821}
2822
John Stilesdce4d3e2020-09-25 14:35:13 -04002823bool IRGenerator::setRefKind(Expression& expr, VariableReference::RefKind kind) {
John Stilesa976da72020-09-25 23:06:26 -04002824 VariableReference* assignableVar = nullptr;
2825 if (!Analysis::IsAssignable(expr, &assignableVar, &fErrors)) {
John Stilesdce4d3e2020-09-25 14:35:13 -04002826 return false;
2827 }
John Stilesa976da72020-09-25 23:06:26 -04002828 if (assignableVar) {
2829 assignableVar->setRefKind(kind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002830 }
Ethan Nicholascb0f4092019-04-19 11:26:50 -04002831 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07002832}
2833
Brian Osman8e2ef022020-09-30 13:26:43 -04002834void IRGenerator::cloneBuiltinVariables() {
2835 class BuiltinVariableRemapper : public ProgramWriter {
2836 public:
2837 BuiltinVariableRemapper(IRGenerator* generator) : fGenerator(generator) {}
2838
Brian Osman00a8b5b2020-10-02 09:06:04 -04002839 void cloneVariable(const String& name) {
2840 // If this is the *first* time we've seen this builtin, findAndInclude will return
2841 // the corresponding ProgramElement.
Brian Osmanafa18ee2020-10-07 17:47:45 -04002842 if (const ProgramElement* sharedDecl = fGenerator->fIntrinsics->findAndInclude(name)) {
2843 SkASSERT(sharedDecl->is<GlobalVarDeclaration>() ||
2844 sharedDecl->is<InterfaceBlock>());
Brian Osman00a8b5b2020-10-02 09:06:04 -04002845
Brian Osmanafa18ee2020-10-07 17:47:45 -04002846 // Clone the ProgramElement that declares this variable
2847 std::unique_ptr<ProgramElement> clonedDecl = sharedDecl->clone();
2848 const Variable* sharedVar = nullptr;
2849 const Expression* initialValue = nullptr;
2850
2851 if (clonedDecl->is<GlobalVarDeclaration>()) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002852 GlobalVarDeclaration& global = clonedDecl->as<GlobalVarDeclaration>();
2853 VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2854 sharedVar = &decl.var();
2855 initialValue = decl.value().get();
Brian Osmanafa18ee2020-10-07 17:47:45 -04002856 } else {
2857 SkASSERT(clonedDecl->is<InterfaceBlock>());
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002858 sharedVar = &clonedDecl->as<InterfaceBlock>().variable();
Brian Osmanafa18ee2020-10-07 17:47:45 -04002859 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002860
2861 // Now clone the Variable, and add the clone to the Program's symbol table.
Brian Osmanc0213602020-10-06 14:43:32 -04002862 // Any initial value expression was cloned as part of the GlobalVarDeclaration,
Brian Osman00a8b5b2020-10-02 09:06:04 -04002863 // so we're pointing at a Program-owned expression.
2864 const Variable* clonedVar =
2865 fGenerator->fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Variable>(
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002866 sharedVar->fOffset, sharedVar->modifiersHandle(), sharedVar->name(),
2867 &sharedVar->type(), /*builtin=*/false, sharedVar->storage(),
Brian Osmanafa18ee2020-10-07 17:47:45 -04002868 initialValue));
Brian Osman00a8b5b2020-10-02 09:06:04 -04002869
Brian Osmanafa18ee2020-10-07 17:47:45 -04002870 // Go back and update the declaring element to point at the cloned Variable.
2871 if (clonedDecl->is<GlobalVarDeclaration>()) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002872 GlobalVarDeclaration& global = clonedDecl->as<GlobalVarDeclaration>();
2873 global.declaration()->as<VarDeclaration>().setVar(clonedVar);
Brian Osmanafa18ee2020-10-07 17:47:45 -04002874 } else {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002875 clonedDecl->as<InterfaceBlock>().setVariable(clonedVar);
Brian Osmanafa18ee2020-10-07 17:47:45 -04002876 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002877
2878 // Remember this new re-mapping...
2879 fRemap.insert({sharedVar, clonedVar});
2880
Brian Osmanafa18ee2020-10-07 17:47:45 -04002881 // Add the declaring element to this Program
2882 fNewElements.push_back(std::move(clonedDecl));
Brian Osman00a8b5b2020-10-02 09:06:04 -04002883 }
2884 }
2885
Brian Osman8e2ef022020-09-30 13:26:43 -04002886 bool visitExpression(Expression& e) override {
2887 // Look for references to builtin variables.
Ethan Nicholas78686922020-10-08 06:46:27 -04002888 if (e.is<VariableReference>() && e.as<VariableReference>().variable()->isBuiltin()) {
2889 const Variable* sharedVar = e.as<VariableReference>().variable();
Brian Osman8e2ef022020-09-30 13:26:43 -04002890
Ethan Nicholase2c49992020-10-05 11:49:11 -04002891 this->cloneVariable(sharedVar->name());
Brian Osman8e2ef022020-09-30 13:26:43 -04002892
2893 // TODO: SkASSERT(found), once all pre-includes are converted?
2894 auto found = fRemap.find(sharedVar);
2895 if (found != fRemap.end()) {
2896 e.as<VariableReference>().setVariable(found->second);
2897 }
2898 }
2899
2900 return INHERITED::visitExpression(e);
2901 }
2902
2903 IRGenerator* fGenerator;
2904 std::unordered_map<const Variable*, const Variable*> fRemap;
2905 std::vector<std::unique_ptr<ProgramElement>> fNewElements;
2906
2907 using INHERITED = ProgramWriter;
2908 using INHERITED::visitProgramElement;
2909 };
2910
Brian Osman00a8b5b2020-10-02 09:06:04 -04002911 BuiltinVariableRemapper remapper(this);
2912 for (auto& e : *fProgramElements) {
2913 remapper.visitProgramElement(*e);
Brian Osman8e2ef022020-09-30 13:26:43 -04002914 }
Brian Osman00a8b5b2020-10-02 09:06:04 -04002915
2916 // Vulkan requires certain builtin variables be present, even if they're unused. At one time,
2917 // validation errors would result if they were missing. Now, it's just (Adreno) driver bugs
2918 // that drop or corrupt draws if they're missing.
2919 switch (fKind) {
2920 case Program::kFragment_Kind:
2921 remapper.cloneVariable("sk_Clockwise");
2922 break;
2923 default:
2924 break;
2925 }
2926
2927 fProgramElements->insert(fProgramElements->begin(),
Brian Osmanafa18ee2020-10-07 17:47:45 -04002928 std::make_move_iterator(remapper.fNewElements.begin()),
2929 std::make_move_iterator(remapper.fNewElements.end()));
Brian Osman8e2ef022020-09-30 13:26:43 -04002930}
2931
Brian Osman88cda172020-10-09 12:05:16 -04002932IRGenerator::IRBundle IRGenerator::convertProgram(
2933 Program::Kind kind,
2934 const Program::Settings* settings,
Brian Osmand7e76592020-11-02 12:26:22 -05002935 const ShaderCapsClass* caps,
Brian Osman88cda172020-10-09 12:05:16 -04002936 const ParsedModule& base,
2937 bool isBuiltinCode,
2938 const char* text,
2939 size_t length,
2940 const std::vector<std::unique_ptr<ExternalValue>>* externalValues) {
Robert Phillipsfe8da172018-01-24 14:52:02 +00002941 fKind = kind;
Brian Osman88cda172020-10-09 12:05:16 -04002942 fSettings = settings;
Brian Osmand7e76592020-11-02 12:26:22 -05002943 fCaps = caps;
Brian Osman88cda172020-10-09 12:05:16 -04002944 fSymbolTable = base.fSymbols;
2945 fIntrinsics = base.fIntrinsics.get();
2946 if (fIntrinsics) {
2947 fIntrinsics->resetAlreadyIncluded();
2948 }
2949 fIsBuiltinCode = isBuiltinCode;
2950
2951 std::vector<std::unique_ptr<ProgramElement>> elements;
2952 fProgramElements = &elements;
2953
2954 fInputs.reset();
2955 fInvocations = -1;
2956 fRTAdjust = nullptr;
2957 fRTAdjustInterfaceBlock = nullptr;
2958
2959 fCapsMap.clear();
Brian Osmand7e76592020-11-02 12:26:22 -05002960 if (fCaps) {
2961 fill_caps(*fCaps, &fCapsMap);
Brian Osman88cda172020-10-09 12:05:16 -04002962 } else {
2963 fCapsMap.insert({String("integerSupport"), Program::Settings::Value(true)});
2964 }
2965
John Stilese51b6a32020-10-21 15:02:37 -04002966 AutoSymbolTable table(this);
Brian Osman88cda172020-10-09 12:05:16 -04002967
Brian Osman68c1d402020-10-12 16:36:38 -04002968 if (kind == Program::kGeometry_Kind && !fIsBuiltinCode) {
2969 // Declare sk_InvocationID programmatically. With invocations support, it's an 'in' builtin.
2970 // If we're applying the workaround, then it's a plain global.
Brian Osmand7e76592020-11-02 12:26:22 -05002971 bool workaround = fCaps && !fCaps->gsInvocationsSupport();
Brian Osman68c1d402020-10-12 16:36:38 -04002972 Modifiers m;
2973 if (!workaround) {
2974 m.fFlags = Modifiers::kIn_Flag;
2975 m.fLayout.fBuiltin = SK_INVOCATIONID_BUILTIN;
2976 }
2977 auto var = std::make_unique<Variable>(-1, fModifiers->handle(m), "sk_InvocationID",
2978 fContext.fInt_Type.get(), false,
2979 Variable::Storage::kGlobal);
John Stiles87ae34e2020-10-13 12:50:11 -04002980 auto decl = std::make_unique<VarDeclaration>(var.get(), fContext.fInt_Type.get(),
2981 /*sizes=*/ExpressionArray{},
2982 /*value=*/nullptr);
Brian Osman68c1d402020-10-12 16:36:38 -04002983 fSymbolTable->add(std::move(var));
2984 fProgramElements->push_back(
2985 std::make_unique<GlobalVarDeclaration>(/*offset=*/-1, std::move(decl)));
2986 }
2987
Brian Osman88cda172020-10-09 12:05:16 -04002988 if (externalValues) {
2989 // Add any external values to the new symbol table, so they're only visible to this Program
2990 for (const auto& ev : *externalValues) {
2991 fSymbolTable->addWithoutOwnership(ev.get());
2992 }
2993 }
2994
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002995 Parser parser(text, length, *fSymbolTable, fErrors);
Ethan Nicholasba9a04f2020-11-06 09:28:04 -05002996 fFile = parser.compilationUnit();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002997 if (fErrors.errorCount()) {
Brian Osman88cda172020-10-09 12:05:16 -04002998 return {};
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04002999 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003000 SkASSERT(fFile);
3001 for (const auto& decl : fFile->root()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003002 switch (decl.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04003003 case ASTNode::Kind::kVarDeclarations: {
John Stiles8f2a0cf2020-10-13 12:48:21 -04003004 StatementArray decls = this->convertVarDeclarations(decl,
3005 Variable::Storage::kGlobal);
Brian Osmanc0213602020-10-06 14:43:32 -04003006 for (auto& varDecl : decls) {
3007 fProgramElements->push_back(std::make_unique<GlobalVarDeclaration>(
3008 decl.fOffset, std::move(varDecl)));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003009 }
3010 break;
3011 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003012 case ASTNode::Kind::kEnum: {
3013 this->convertEnum(decl);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003014 break;
3015 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003016 case ASTNode::Kind::kFunction: {
3017 this->convertFunction(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003018 break;
3019 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003020 case ASTNode::Kind::kModifiers: {
3021 std::unique_ptr<ModifiersDeclaration> f = this->convertModifiersDeclaration(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003022 if (f) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003023 fProgramElements->push_back(std::move(f));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003024 }
3025 break;
3026 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003027 case ASTNode::Kind::kInterfaceBlock: {
3028 std::unique_ptr<InterfaceBlock> i = this->convertInterfaceBlock(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003029 if (i) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003030 fProgramElements->push_back(std::move(i));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003031 }
3032 break;
3033 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003034 case ASTNode::Kind::kExtension: {
3035 std::unique_ptr<Extension> e = this->convertExtension(decl.fOffset,
3036 decl.getString());
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003037 if (e) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003038 fProgramElements->push_back(std::move(e));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003039 }
3040 break;
3041 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003042 case ASTNode::Kind::kSection: {
3043 std::unique_ptr<Section> s = this->convertSection(decl);
Ethan Nicholas762466e2017-06-29 10:03:38 -04003044 if (s) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003045 fProgramElements->push_back(std::move(s));
Ethan Nicholas762466e2017-06-29 10:03:38 -04003046 }
3047 break;
3048 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003049 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003050#ifdef SK_DEBUG
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003051 ABORT("unsupported declaration: %s\n", decl.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003052#endif
3053 break;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003054 }
3055 }
Brian Osmanc95d3a12020-09-09 10:56:27 -04003056
Brian Osman8e2ef022020-09-30 13:26:43 -04003057 // Any variables defined in the pre-includes need to be cloned into the Program
Brian Osman00a8b5b2020-10-02 09:06:04 -04003058 if (!fIsBuiltinCode && fIntrinsics) {
3059 this->cloneBuiltinVariables();
3060 }
Brian Osman8e2ef022020-09-30 13:26:43 -04003061
Brian Osmanc95d3a12020-09-09 10:56:27 -04003062 // Do a final pass looking for dangling FunctionReference or TypeReference expressions
3063 class FindIllegalExpressions : public ProgramVisitor {
3064 public:
3065 FindIllegalExpressions(IRGenerator* generator) : fGenerator(generator) {}
3066
3067 bool visitExpression(const Expression& e) override {
3068 fGenerator->checkValid(e);
3069 return INHERITED::visitExpression(e);
3070 }
3071
3072 IRGenerator* fGenerator;
3073 using INHERITED = ProgramVisitor;
3074 using INHERITED::visitProgramElement;
3075 };
3076 for (const auto& pe : *fProgramElements) {
3077 FindIllegalExpressions{this}.visitProgramElement(*pe);
3078 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003079
Brian Osman88cda172020-10-09 12:05:16 -04003080 fSettings = nullptr;
3081
John Stilese51b6a32020-10-21 15:02:37 -04003082 return IRBundle{std::move(elements), this->releaseModifiers(), fSymbolTable, fInputs};
Brian Osman88cda172020-10-09 12:05:16 -04003083}
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003084
John Stilesa6841be2020-08-06 14:11:56 -04003085} // namespace SkSL