blob: b13067937e0a430cc11d6e7f5130228d2cc0cfd3 [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 Stilesfbd050b2020-08-03 13:21:46 -040011#include <memory>
Ethan Nicholasaf197692017-02-27 13:26:45 -050012#include <unordered_set>
ethannicholasb3058bd2016-07-01 08:22:01 -070013
Ethan Nicholas6e0fa402020-08-20 14:08:23 -040014#include "src/sksl/SkSLAnalysis.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050015#include "src/sksl/SkSLCompiler.h"
16#include "src/sksl/SkSLParser.h"
Brian Osman3000d6b2020-07-31 15:57:28 -040017#include "src/sksl/SkSLUtil.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "src/sksl/ir/SkSLBinaryExpression.h"
19#include "src/sksl/ir/SkSLBoolLiteral.h"
20#include "src/sksl/ir/SkSLBreakStatement.h"
21#include "src/sksl/ir/SkSLConstructor.h"
22#include "src/sksl/ir/SkSLContinueStatement.h"
23#include "src/sksl/ir/SkSLDiscardStatement.h"
24#include "src/sksl/ir/SkSLDoStatement.h"
25#include "src/sksl/ir/SkSLEnum.h"
26#include "src/sksl/ir/SkSLExpressionStatement.h"
Ethan Nicholas9e6a3932019-05-17 16:31:21 -040027#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Ethan Nicholas91164d12019-05-15 15:29:54 -040028#include "src/sksl/ir/SkSLExternalValueReference.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050029#include "src/sksl/ir/SkSLField.h"
30#include "src/sksl/ir/SkSLFieldAccess.h"
31#include "src/sksl/ir/SkSLFloatLiteral.h"
32#include "src/sksl/ir/SkSLForStatement.h"
33#include "src/sksl/ir/SkSLFunctionCall.h"
34#include "src/sksl/ir/SkSLFunctionDeclaration.h"
35#include "src/sksl/ir/SkSLFunctionDefinition.h"
36#include "src/sksl/ir/SkSLFunctionReference.h"
37#include "src/sksl/ir/SkSLIfStatement.h"
38#include "src/sksl/ir/SkSLIndexExpression.h"
39#include "src/sksl/ir/SkSLIntLiteral.h"
40#include "src/sksl/ir/SkSLInterfaceBlock.h"
41#include "src/sksl/ir/SkSLLayout.h"
Chris Daltonb0fd4b12019-10-29 13:41:22 -060042#include "src/sksl/ir/SkSLNop.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050043#include "src/sksl/ir/SkSLNullLiteral.h"
44#include "src/sksl/ir/SkSLPostfixExpression.h"
45#include "src/sksl/ir/SkSLPrefixExpression.h"
46#include "src/sksl/ir/SkSLReturnStatement.h"
47#include "src/sksl/ir/SkSLSetting.h"
48#include "src/sksl/ir/SkSLSwitchCase.h"
49#include "src/sksl/ir/SkSLSwitchStatement.h"
50#include "src/sksl/ir/SkSLSwizzle.h"
51#include "src/sksl/ir/SkSLTernaryExpression.h"
52#include "src/sksl/ir/SkSLUnresolvedFunction.h"
53#include "src/sksl/ir/SkSLVarDeclarations.h"
54#include "src/sksl/ir/SkSLVarDeclarationsStatement.h"
55#include "src/sksl/ir/SkSLVariable.h"
56#include "src/sksl/ir/SkSLVariableReference.h"
57#include "src/sksl/ir/SkSLWhileStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070058
59namespace SkSL {
60
61class AutoSymbolTable {
62public:
Ethan Nicholas11d53972016-11-28 11:23:23 -050063 AutoSymbolTable(IRGenerator* ir)
ethannicholasb3058bd2016-07-01 08:22:01 -070064 : fIR(ir)
65 , fPrevious(fIR->fSymbolTable) {
66 fIR->pushSymbolTable();
67 }
68
69 ~AutoSymbolTable() {
70 fIR->popSymbolTable();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -040071 SkASSERT(fPrevious == fIR->fSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -070072 }
73
74 IRGenerator* fIR;
75 std::shared_ptr<SymbolTable> fPrevious;
76};
77
ethannicholas22f939e2016-10-13 13:25:34 -070078class AutoLoopLevel {
79public:
Ethan Nicholas11d53972016-11-28 11:23:23 -050080 AutoLoopLevel(IRGenerator* ir)
ethannicholas22f939e2016-10-13 13:25:34 -070081 : fIR(ir) {
82 fIR->fLoopLevel++;
83 }
84
85 ~AutoLoopLevel() {
86 fIR->fLoopLevel--;
87 }
88
89 IRGenerator* fIR;
90};
91
Ethan Nicholasaf197692017-02-27 13:26:45 -050092class AutoSwitchLevel {
93public:
94 AutoSwitchLevel(IRGenerator* ir)
95 : fIR(ir) {
96 fIR->fSwitchLevel++;
97 }
98
99 ~AutoSwitchLevel() {
100 fIR->fSwitchLevel--;
101 }
102
103 IRGenerator* fIR;
104};
105
John Stilesd1c4dac2020-08-11 18:50:50 -0400106class AutoDisableInline {
107public:
108 AutoDisableInline(IRGenerator* ir, bool canInline = false)
109 : fIR(ir) {
110 fOldCanInline = ir->fCanInline;
John Stiles46d17582020-08-12 11:48:48 -0400111 fIR->fCanInline &= canInline;
John Stilesd1c4dac2020-08-11 18:50:50 -0400112 }
113
114 ~AutoDisableInline() {
115 fIR->fCanInline = fOldCanInline;
116 }
117
118 IRGenerator* fIR;
119 bool fOldCanInline;
120};
121
Ethan Nicholas11d53972016-11-28 11:23:23 -0500122IRGenerator::IRGenerator(const Context* context, std::shared_ptr<SymbolTable> symbolTable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700123 ErrorReporter& errorReporter)
ethannicholasd598f792016-07-25 10:08:54 -0700124: fContext(*context)
125, fCurrentFunction(nullptr)
Ethan Nicholas762466e2017-06-29 10:03:38 -0400126, fRootSymbolTable(symbolTable)
127, fSymbolTable(symbolTable)
ethannicholas22f939e2016-10-13 13:25:34 -0700128, fLoopLevel(0)
Ethan Nicholasaf197692017-02-27 13:26:45 -0500129, fSwitchLevel(0)
ethannicholasd598f792016-07-25 10:08:54 -0700130, fErrors(errorReporter) {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700131
132void IRGenerator::pushSymbolTable() {
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400133 fSymbolTable.reset(new SymbolTable(std::move(fSymbolTable)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700134}
135
136void IRGenerator::popSymbolTable() {
137 fSymbolTable = fSymbolTable->fParent;
138}
139
Ethan Nicholas762466e2017-06-29 10:03:38 -0400140static void fill_caps(const SKSL_CAPS_CLASS& caps,
141 std::unordered_map<String, Program::Settings::Value>* capsMap) {
Brian Salomon23356442018-11-30 15:33:19 -0500142#define CAP(name) \
143 capsMap->insert(std::make_pair(String(#name), Program::Settings::Value(caps.name())))
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500144 CAP(fbFetchSupport);
Brian Salomond4013302018-04-04 13:58:33 +0000145 CAP(fbFetchNeedsCustomOutput);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500146 CAP(flatInterpolationSupport);
147 CAP(noperspectiveInterpolationSupport);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500148 CAP(externalTextureSupport);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500149 CAP(mustEnableAdvBlendEqs);
150 CAP(mustEnableSpecificAdvBlendEqs);
151 CAP(mustDeclareFragmentShaderOutput);
Michael Ludwig4f94ef62018-09-12 15:22:16 -0400152 CAP(mustDoOpBetweenFloorAndAbs);
Brian Salomonf8c187c2019-12-19 14:41:57 -0500153 CAP(mustGuardDivisionEvenAfterExplicitZeroCheck);
154 CAP(inBlendModesFailRandomlyForAllZeroVec);
Michael Ludwig24d438b2018-09-12 15:22:50 -0400155 CAP(atan2ImplementedAsAtanYOverX);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500156 CAP(canUseAnyFunctionInShader);
Chris Dalton47c8ed32017-11-15 18:27:09 -0700157 CAP(floatIs32Bits);
Ethan Nicholas07990de2017-07-18 09:47:43 -0400158 CAP(integerSupport);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500159#undef CAP
160}
161
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400162void IRGenerator::start(const Program::Settings* settings,
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400163 std::vector<std::unique_ptr<ProgramElement>>* inherited,
164 bool isBuiltinCode) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500165 fSettings = settings;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400166 fInherited = inherited;
167 fIsBuiltinCode = isBuiltinCode;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500168 fCapsMap.clear();
169 if (settings->fCaps) {
170 fill_caps(*settings->fCaps, &fCapsMap);
Ethan Nicholas00543112018-07-31 09:44:36 -0400171 } else {
172 fCapsMap.insert(std::make_pair(String("integerSupport"),
173 Program::Settings::Value(true)));
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500174 }
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500175 this->pushSymbolTable();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400176 fInvocations = -1;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500177 fInputs.reset();
Robert Phillipsfe8da172018-01-24 14:52:02 +0000178 fSkPerVertex = nullptr;
179 fRTAdjust = nullptr;
180 fRTAdjustInterfaceBlock = nullptr;
Michael Ludwig9861b7c2020-06-23 18:37:17 -0400181 fInlineVarCounter = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400182 if (inherited) {
183 for (const auto& e : *inherited) {
184 if (e->fKind == ProgramElement::kInterfaceBlock_Kind) {
John Stiles403a3632020-08-20 12:11:48 -0400185 InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400186 if (intf.fVariable.fName == Compiler::PERVERTEX_NAME) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400187 SkASSERT(!fSkPerVertex);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400188 fSkPerVertex = &intf.fVariable;
189 }
190 }
191 }
192 }
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500193 SkASSERT(fIntrinsics);
194 for (auto& pair : *fIntrinsics) {
John Stiles810c8cf2020-08-26 19:46:27 -0400195 pair.second.fAlreadyIncluded = false;
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500196 }
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500197}
198
Ethan Nicholasfc994162019-06-06 10:04:27 -0400199std::unique_ptr<Extension> IRGenerator::convertExtension(int offset, StringFragment name) {
John Stilesfbd050b2020-08-03 13:21:46 -0400200 return std::make_unique<Extension>(offset, name);
ethannicholasb3058bd2016-07-01 08:22:01 -0700201}
202
Ethan Nicholasfc994162019-06-06 10:04:27 -0400203void IRGenerator::finish() {
204 this->popSymbolTable();
205 fSettings = nullptr;
206}
207
Ethan Nicholas70728ef2020-05-28 07:09:00 -0400208std::unique_ptr<Statement> IRGenerator::convertSingleStatement(const ASTNode& statement) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700209 switch (statement.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400210 case ASTNode::Kind::kBlock:
211 return this->convertBlock(statement);
212 case ASTNode::Kind::kVarDeclarations:
213 return this->convertVarDeclarationStatement(statement);
214 case ASTNode::Kind::kIf:
215 return this->convertIf(statement);
216 case ASTNode::Kind::kFor:
217 return this->convertFor(statement);
218 case ASTNode::Kind::kWhile:
219 return this->convertWhile(statement);
220 case ASTNode::Kind::kDo:
221 return this->convertDo(statement);
222 case ASTNode::Kind::kSwitch:
223 return this->convertSwitch(statement);
224 case ASTNode::Kind::kReturn:
225 return this->convertReturn(statement);
226 case ASTNode::Kind::kBreak:
227 return this->convertBreak(statement);
228 case ASTNode::Kind::kContinue:
229 return this->convertContinue(statement);
230 case ASTNode::Kind::kDiscard:
231 return this->convertDiscard(statement);
232 default:
233 // it's an expression
234 std::unique_ptr<Statement> result = this->convertExpressionStatement(statement);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000235 if (fRTAdjust && Program::kGeometry_Kind == fKind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400236 SkASSERT(result->fKind == Statement::kExpression_Kind);
John Stiles403a3632020-08-20 12:11:48 -0400237 Expression& expr = *result->as<ExpressionStatement>().fExpression;
Robert Phillipsfe8da172018-01-24 14:52:02 +0000238 if (expr.fKind == Expression::kFunctionCall_Kind) {
John Stiles403a3632020-08-20 12:11:48 -0400239 FunctionCall& fc = expr.as<FunctionCall>();
Robert Phillipsfe8da172018-01-24 14:52:02 +0000240 if (fc.fFunction.fBuiltin && fc.fFunction.fName == "EmitVertex") {
241 std::vector<std::unique_ptr<Statement>> statements;
242 statements.push_back(getNormalizeSkPositionCode());
243 statements.push_back(std::move(result));
John Stilesfbd050b2020-08-03 13:21:46 -0400244 return std::make_unique<Block>(statement.fOffset, std::move(statements),
245 fSymbolTable);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000246 }
247 }
248 }
249 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700250 }
251}
252
Ethan Nicholas70728ef2020-05-28 07:09:00 -0400253std::unique_ptr<Statement> IRGenerator::convertStatement(const ASTNode& statement) {
254 std::vector<std::unique_ptr<Statement>> oldExtraStatements = std::move(fExtraStatements);
255 std::unique_ptr<Statement> result = this->convertSingleStatement(statement);
256 if (!result) {
257 fExtraStatements = std::move(oldExtraStatements);
258 return nullptr;
259 }
260 if (fExtraStatements.size()) {
261 fExtraStatements.push_back(std::move(result));
262 std::unique_ptr<Statement> block(new Block(-1, std::move(fExtraStatements), nullptr,
263 false));
264 fExtraStatements = std::move(oldExtraStatements);
265 return block;
266 }
267 fExtraStatements = std::move(oldExtraStatements);
268 return result;
269}
270
Ethan Nicholasfc994162019-06-06 10:04:27 -0400271std::unique_ptr<Block> IRGenerator::convertBlock(const ASTNode& block) {
272 SkASSERT(block.fKind == ASTNode::Kind::kBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700273 AutoSymbolTable table(this);
274 std::vector<std::unique_ptr<Statement>> statements;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400275 for (const auto& child : block) {
276 std::unique_ptr<Statement> statement = this->convertStatement(child);
ethannicholasb3058bd2016-07-01 08:22:01 -0700277 if (!statement) {
278 return nullptr;
279 }
280 statements.push_back(std::move(statement));
281 }
John Stilesfbd050b2020-08-03 13:21:46 -0400282 return std::make_unique<Block>(block.fOffset, std::move(statements), fSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -0700283}
284
Ethan Nicholasfc994162019-06-06 10:04:27 -0400285std::unique_ptr<Statement> IRGenerator::convertVarDeclarationStatement(const ASTNode& s) {
286 SkASSERT(s.fKind == ASTNode::Kind::kVarDeclarations);
287 auto decl = this->convertVarDeclarations(s, Variable::kLocal_Storage);
ethannicholasb3058bd2016-07-01 08:22:01 -0700288 if (!decl) {
289 return nullptr;
290 }
ethannicholas14fe8cc2016-09-07 13:37:16 -0700291 return std::unique_ptr<Statement>(new VarDeclarationsStatement(std::move(decl)));
ethannicholasb3058bd2016-07-01 08:22:01 -0700292}
293
Ethan Nicholasfc994162019-06-06 10:04:27 -0400294std::unique_ptr<VarDeclarations> IRGenerator::convertVarDeclarations(const ASTNode& decls,
ethannicholas14fe8cc2016-09-07 13:37:16 -0700295 Variable::Storage storage) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400296 SkASSERT(decls.fKind == ASTNode::Kind::kVarDeclarations);
John Stilesf621e232020-08-25 13:33:02 -0400297 auto declarationsIter = decls.begin();
298 const Modifiers& modifiers = declarationsIter++->getModifiers();
299 const ASTNode& rawType = *(declarationsIter++);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000300 std::vector<std::unique_ptr<VarDeclaration>> variables;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400301 const Type* baseType = this->convertType(rawType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700302 if (!baseType) {
303 return nullptr;
304 }
Brian Osman82329002020-07-21 09:39:27 -0400305 if (baseType->nonnullable() == *fContext.fFragmentProcessor_Type &&
306 storage != Variable::kGlobal_Storage) {
307 fErrors.error(decls.fOffset,
308 "variables of type '" + baseType->displayName() + "' must be global");
309 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500310 if (fKind != Program::kFragmentProcessor_Kind) {
311 if ((modifiers.fFlags & Modifiers::kIn_Flag) &&
312 baseType->kind() == Type::Kind::kMatrix_Kind) {
313 fErrors.error(decls.fOffset, "'in' variables may not have matrix type");
314 }
Brian Osman088913a2019-12-19 15:44:56 -0500315 if ((modifiers.fFlags & Modifiers::kIn_Flag) &&
316 (modifiers.fFlags & Modifiers::kUniform_Flag)) {
317 fErrors.error(decls.fOffset,
318 "'in uniform' variables only permitted within fragment processors");
319 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500320 if (modifiers.fLayout.fWhen.fLength) {
321 fErrors.error(decls.fOffset, "'when' is only permitted within fragment processors");
322 }
323 if (modifiers.fLayout.fFlags & Layout::kTracked_Flag) {
324 fErrors.error(decls.fOffset, "'tracked' is only permitted within fragment processors");
325 }
326 if (modifiers.fLayout.fCType != Layout::CType::kDefault) {
327 fErrors.error(decls.fOffset, "'ctype' is only permitted within fragment processors");
328 }
329 if (modifiers.fLayout.fKey) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400330 fErrors.error(decls.fOffset, "'key' is only permitted within fragment processors");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400331 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500332 }
Brian Osmana4b91692020-08-10 14:26:16 -0400333 if (fKind == Program::kPipelineStage_Kind) {
334 if ((modifiers.fFlags & Modifiers::kIn_Flag) &&
335 baseType->nonnullable() != *fContext.fFragmentProcessor_Type) {
336 fErrors.error(decls.fOffset, "'in' variables not permitted in runtime effects");
337 }
338 }
Brian Osman2fe83fe2019-12-16 13:17:59 -0500339 if (modifiers.fLayout.fKey && (modifiers.fFlags & Modifiers::kUniform_Flag)) {
340 fErrors.error(decls.fOffset, "'key' is not permitted on 'uniform' variables");
Ethan Nicholasbcd51e82019-04-09 10:40:41 -0400341 }
Brian Osmanf59a9612020-04-15 14:18:13 -0400342 if (modifiers.fLayout.fMarker.fLength) {
343 if (fKind != Program::kPipelineStage_Kind) {
344 fErrors.error(decls.fOffset, "'marker' is only permitted in runtime effects");
345 }
346 if (!(modifiers.fFlags & Modifiers::kUniform_Flag)) {
347 fErrors.error(decls.fOffset, "'marker' is only permitted on 'uniform' variables");
348 }
349 if (*baseType != *fContext.fFloat4x4_Type) {
350 fErrors.error(decls.fOffset, "'marker' is only permitted on float4x4 variables");
351 }
352 }
Brian Osmanb32d66b2020-04-30 17:12:03 -0400353 if (modifiers.fLayout.fFlags & Layout::kSRGBUnpremul_Flag) {
354 if (fKind != Program::kPipelineStage_Kind) {
355 fErrors.error(decls.fOffset, "'srgb_unpremul' is only permitted in runtime effects");
356 }
357 if (!(modifiers.fFlags & Modifiers::kUniform_Flag)) {
358 fErrors.error(decls.fOffset,
359 "'srgb_unpremul' is only permitted on 'uniform' variables");
360 }
361 auto validColorXformType = [](const Type& t) {
362 return t.kind() == Type::kVector_Kind && t.componentType().isFloat() &&
363 (t.columns() == 3 || t.columns() == 4);
364 };
365 if (!validColorXformType(*baseType) && !(baseType->kind() == Type::kArray_Kind &&
366 validColorXformType(baseType->componentType()))) {
367 fErrors.error(decls.fOffset,
368 "'srgb_unpremul' is only permitted on half3, half4, float3, or float4 "
369 "variables");
370 }
371 }
Brian Osman3c358422020-03-23 10:44:12 -0400372 if (modifiers.fFlags & Modifiers::kVarying_Flag) {
373 if (fKind != Program::kPipelineStage_Kind) {
374 fErrors.error(decls.fOffset, "'varying' is only permitted in runtime effects");
375 }
376 if (!baseType->isFloat() &&
377 !(baseType->kind() == Type::kVector_Kind && baseType->componentType().isFloat())) {
378 fErrors.error(decls.fOffset, "'varying' must be float scalar or vector");
379 }
380 }
Ethan Nicholas63d7ee32020-08-17 10:57:12 -0400381 int permitted = Modifiers::kConst_Flag;
382 if (storage == Variable::kGlobal_Storage) {
383 permitted |= Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag |
384 Modifiers::kFlat_Flag | Modifiers::kVarying_Flag |
385 Modifiers::kNoPerspective_Flag | Modifiers::kPLS_Flag |
386 Modifiers::kPLSIn_Flag | Modifiers::kPLSOut_Flag |
387 Modifiers::kRestrict_Flag | Modifiers::kVolatile_Flag |
388 Modifiers::kReadOnly_Flag | Modifiers::kWriteOnly_Flag |
389 Modifiers::kCoherent_Flag | Modifiers::kBuffer_Flag;
390 }
391 this->checkModifiers(decls.fOffset, modifiers, permitted);
John Stilesf621e232020-08-25 13:33:02 -0400392 for (; declarationsIter != decls.end(); ++declarationsIter) {
393 const ASTNode& varDecl = *declarationsIter;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400394 if (modifiers.fLayout.fLocation == 0 && modifiers.fLayout.fIndex == 0 &&
395 (modifiers.fFlags & Modifiers::kOut_Flag) && fKind == Program::kFragment_Kind &&
396 varDecl.getVarData().fName != "sk_FragColor") {
397 fErrors.error(varDecl.fOffset,
Ethan Nicholas6c942712018-03-16 09:45:11 -0400398 "out location=0, index=0 is reserved for sk_FragColor");
399 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400400 const ASTNode::VarData& varData = varDecl.getVarData();
ethannicholasd598f792016-07-25 10:08:54 -0700401 const Type* type = baseType;
ethannicholas14fe8cc2016-09-07 13:37:16 -0700402 std::vector<std::unique_ptr<Expression>> sizes;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400403 auto iter = varDecl.begin();
404 for (size_t i = 0; i < varData.fSizeCount; ++i, ++iter) {
405 const ASTNode& rawSize = *iter;
ethannicholas14fe8cc2016-09-07 13:37:16 -0700406 if (rawSize) {
Ethan Nicholasfc994162019-06-06 10:04:27 -0400407 auto size = this->coerce(this->convertExpression(rawSize), *fContext.fInt_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700408 if (!size) {
409 return nullptr;
410 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700411 String name(type->fName);
Ethan Nicholas50afc172017-02-16 14:49:57 -0500412 int64_t count;
ethannicholasb3058bd2016-07-01 08:22:01 -0700413 if (size->fKind == Expression::kIntLiteral_Kind) {
John Stiles81365af2020-08-18 09:24:00 -0400414 count = size->as<IntLiteral>().fValue;
ethannicholasb3058bd2016-07-01 08:22:01 -0700415 if (count <= 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700416 fErrors.error(size->fOffset, "array size must be positive");
Ethan Nicholas66d80062019-09-09 14:50:51 -0400417 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -0700418 }
419 name += "[" + to_string(count) + "]";
420 } else {
Ethan Nicholas66d80062019-09-09 14:50:51 -0400421 fErrors.error(size->fOffset, "array size must be specified");
422 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -0700423 }
John Stiles3ae071e2020-08-05 15:29:29 -0400424 type = fSymbolTable->takeOwnershipOfSymbol(
425 std::make_unique<Type>(name, Type::kArray_Kind, *type, (int)count));
ethannicholas14fe8cc2016-09-07 13:37:16 -0700426 sizes.push_back(std::move(size));
ethannicholasb3058bd2016-07-01 08:22:01 -0700427 } else {
John Stiles3ae071e2020-08-05 15:29:29 -0400428 type = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
429 type->name() + "[]", Type::kArray_Kind, *type, /*columns=*/-1));
ethannicholas14fe8cc2016-09-07 13:37:16 -0700430 sizes.push_back(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700431 }
432 }
John Stilesfbd050b2020-08-03 13:21:46 -0400433 auto var = std::make_unique<Variable>(varDecl.fOffset, modifiers, varData.fName, *type,
434 storage);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000435 if (var->fName == Compiler::RTADJUST_NAME) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400436 SkASSERT(!fRTAdjust);
437 SkASSERT(var->fType == *fContext.fFloat4_Type);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000438 fRTAdjust = var.get();
439 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700440 std::unique_ptr<Expression> value;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400441 if (iter != varDecl.end()) {
442 value = this->convertExpression(*iter);
ethannicholasb3058bd2016-07-01 08:22:01 -0700443 if (!value) {
444 return nullptr;
445 }
ethannicholasd598f792016-07-25 10:08:54 -0700446 value = this->coerce(std::move(value), *type);
Ethan Nicholas68dd2c12018-03-01 15:05:17 -0500447 if (!value) {
448 return nullptr;
449 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400450 var->fWriteCount = 1;
Ethan Nicholas8f6c2ab2018-01-17 13:51:52 -0500451 var->fInitialValue = value.get();
ethannicholasb3058bd2016-07-01 08:22:01 -0700452 }
John Stilesce591b72020-08-27 11:47:30 -0400453 const Symbol* symbol = (*fSymbolTable)[var->fName];
454 if (symbol && storage == Variable::kGlobal_Storage && var->fName == "sk_FragColor") {
455 // Already defined, ignore.
456 } else if (symbol && storage == Variable::kGlobal_Storage &&
457 symbol->fKind == Symbol::kVariable_Kind &&
458 symbol->as<Variable>().fModifiers.fLayout.fBuiltin >= 0) {
459 // Already defined, just update the modifiers.
460 symbol->as<Variable>().fModifiers = var->fModifiers;
ethannicholasf789b382016-08-03 12:43:36 -0700461 } else {
John Stilesce591b72020-08-27 11:47:30 -0400462 variables.emplace_back(std::make_unique<VarDeclaration>(var.get(), std::move(sizes),
463 std::move(value)));
Ethan Nicholasfc994162019-06-06 10:04:27 -0400464 StringFragment name = var->fName;
465 fSymbolTable->add(name, std::move(var));
ethannicholasf789b382016-08-03 12:43:36 -0700466 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700467 }
John Stilesfbd050b2020-08-03 13:21:46 -0400468 return std::make_unique<VarDeclarations>(decls.fOffset, baseType, std::move(variables));
ethannicholasb3058bd2016-07-01 08:22:01 -0700469}
470
Ethan Nicholasfc994162019-06-06 10:04:27 -0400471std::unique_ptr<ModifiersDeclaration> IRGenerator::convertModifiersDeclaration(const ASTNode& m) {
472 SkASSERT(m.fKind == ASTNode::Kind::kModifiers);
473 Modifiers modifiers = m.getModifiers();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400474 if (modifiers.fLayout.fInvocations != -1) {
Ethan Nicholasf06576b2019-04-03 15:45:25 -0400475 if (fKind != Program::kGeometry_Kind) {
476 fErrors.error(m.fOffset, "'invocations' is only legal in geometry shaders");
477 return nullptr;
478 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400479 fInvocations = modifiers.fLayout.fInvocations;
Chris Daltonf1b47bb2017-10-06 11:57:51 -0600480 if (fSettings->fCaps && !fSettings->fCaps->gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400481 modifiers.fLayout.fInvocations = -1;
John Stilesce591b72020-08-27 11:47:30 -0400482 const Variable& invocationId = (*fSymbolTable)["sk_InvocationID"]->as<Variable>();
483 invocationId.fModifiers.fFlags = 0;
484 invocationId.fModifiers.fLayout.fBuiltin = -1;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400485 if (modifiers.fLayout.description() == "") {
486 return nullptr;
487 }
488 }
489 }
490 if (modifiers.fLayout.fMaxVertices != -1 && fInvocations > 0 && fSettings->fCaps &&
Chris Daltonf1b47bb2017-10-06 11:57:51 -0600491 !fSettings->fCaps->gsInvocationsSupport()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400492 modifiers.fLayout.fMaxVertices *= fInvocations;
493 }
John Stilesfbd050b2020-08-03 13:21:46 -0400494 return std::make_unique<ModifiersDeclaration>(modifiers);
ethannicholas5961bc92016-10-12 06:39:56 -0700495}
496
Ethan Nicholasfc994162019-06-06 10:04:27 -0400497std::unique_ptr<Statement> IRGenerator::convertIf(const ASTNode& n) {
498 SkASSERT(n.fKind == ASTNode::Kind::kIf);
499 auto iter = n.begin();
500 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
ethannicholasd598f792016-07-25 10:08:54 -0700501 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -0700502 if (!test) {
503 return nullptr;
504 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400505 std::unique_ptr<Statement> ifTrue = this->convertStatement(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700506 if (!ifTrue) {
507 return nullptr;
508 }
509 std::unique_ptr<Statement> ifFalse;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400510 if (iter != n.end()) {
511 ifFalse = this->convertStatement(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700512 if (!ifFalse) {
513 return nullptr;
514 }
515 }
ethannicholas08a92112016-11-09 13:26:45 -0800516 if (test->fKind == Expression::kBoolLiteral_Kind) {
517 // static boolean value, fold down to a single branch
John Stiles403a3632020-08-20 12:11:48 -0400518 if (test->as<BoolLiteral>().fValue) {
ethannicholas08a92112016-11-09 13:26:45 -0800519 return ifTrue;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400520 } else if (ifFalse) {
ethannicholas08a92112016-11-09 13:26:45 -0800521 return ifFalse;
522 } else {
523 // False & no else clause. Not an error, so don't return null!
524 std::vector<std::unique_ptr<Statement>> empty;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400525 return std::unique_ptr<Statement>(new Block(n.fOffset, std::move(empty),
ethannicholas08a92112016-11-09 13:26:45 -0800526 fSymbolTable));
527 }
528 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400529 return std::unique_ptr<Statement>(new IfStatement(n.fOffset, n.getBool(), std::move(test),
ethannicholasb3058bd2016-07-01 08:22:01 -0700530 std::move(ifTrue), std::move(ifFalse)));
531}
532
Ethan Nicholasfc994162019-06-06 10:04:27 -0400533std::unique_ptr<Statement> IRGenerator::convertFor(const ASTNode& f) {
534 SkASSERT(f.fKind == ASTNode::Kind::kFor);
ethannicholas22f939e2016-10-13 13:25:34 -0700535 AutoLoopLevel level(this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700536 AutoSymbolTable table(this);
ethannicholas22f939e2016-10-13 13:25:34 -0700537 std::unique_ptr<Statement> initializer;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400538 auto iter = f.begin();
539 if (*iter) {
540 initializer = this->convertStatement(*iter);
ethannicholas22f939e2016-10-13 13:25:34 -0700541 if (!initializer) {
542 return nullptr;
543 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700544 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400545 ++iter;
ethannicholas22f939e2016-10-13 13:25:34 -0700546 std::unique_ptr<Expression> test;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400547 if (*iter) {
John Stilesd1c4dac2020-08-11 18:50:50 -0400548 AutoDisableInline disableInline(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400549 test = this->coerce(this->convertExpression(*iter), *fContext.fBool_Type);
ethannicholas22f939e2016-10-13 13:25:34 -0700550 if (!test) {
551 return nullptr;
552 }
Ethan Nicholas70728ef2020-05-28 07:09:00 -0400553
ethannicholasb3058bd2016-07-01 08:22:01 -0700554 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400555 ++iter;
ethannicholas22f939e2016-10-13 13:25:34 -0700556 std::unique_ptr<Expression> next;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400557 if (*iter) {
John Stilesd1c4dac2020-08-11 18:50:50 -0400558 AutoDisableInline disableInline(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400559 next = this->convertExpression(*iter);
ethannicholas22f939e2016-10-13 13:25:34 -0700560 if (!next) {
561 return nullptr;
562 }
563 this->checkValid(*next);
ethannicholasb3058bd2016-07-01 08:22:01 -0700564 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400565 ++iter;
566 std::unique_ptr<Statement> statement = this->convertStatement(*iter);
ethannicholasb3058bd2016-07-01 08:22:01 -0700567 if (!statement) {
568 return nullptr;
569 }
John Stilesd1c4dac2020-08-11 18:50:50 -0400570 return std::make_unique<ForStatement>(f.fOffset, std::move(initializer), std::move(test),
571 std::move(next), std::move(statement), fSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -0700572}
573
Ethan Nicholasfc994162019-06-06 10:04:27 -0400574std::unique_ptr<Statement> IRGenerator::convertWhile(const ASTNode& w) {
575 SkASSERT(w.fKind == ASTNode::Kind::kWhile);
ethannicholas22f939e2016-10-13 13:25:34 -0700576 AutoLoopLevel level(this);
John Stilesd1c4dac2020-08-11 18:50:50 -0400577 std::unique_ptr<Expression> test;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400578 auto iter = w.begin();
John Stilesd1c4dac2020-08-11 18:50:50 -0400579 {
580 AutoDisableInline disableInline(this);
581 test = this->coerce(this->convertExpression(*(iter++)), *fContext.fBool_Type);
582 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700583 if (!test) {
584 return nullptr;
585 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400586 std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -0700587 if (!statement) {
588 return nullptr;
589 }
John Stilesd1c4dac2020-08-11 18:50:50 -0400590 return std::make_unique<WhileStatement>(w.fOffset, std::move(test), std::move(statement));
ethannicholasb3058bd2016-07-01 08:22:01 -0700591}
592
Ethan Nicholasfc994162019-06-06 10:04:27 -0400593std::unique_ptr<Statement> IRGenerator::convertDo(const ASTNode& d) {
594 SkASSERT(d.fKind == ASTNode::Kind::kDo);
ethannicholas22f939e2016-10-13 13:25:34 -0700595 AutoLoopLevel level(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400596 auto iter = d.begin();
597 std::unique_ptr<Statement> statement = this->convertStatement(*(iter++));
598 if (!statement) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700599 return nullptr;
600 }
John Stilesd1c4dac2020-08-11 18:50:50 -0400601 std::unique_ptr<Expression> test;
602 {
603 AutoDisableInline disableInline(this);
604 test = this->coerce(this->convertExpression(*(iter++)), *fContext.fBool_Type);
605 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400606 if (!test) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700607 return nullptr;
608 }
John Stilesd1c4dac2020-08-11 18:50:50 -0400609 return std::make_unique<DoStatement>(d.fOffset, std::move(statement), std::move(test));
ethannicholasb3058bd2016-07-01 08:22:01 -0700610}
611
Ethan Nicholasfc994162019-06-06 10:04:27 -0400612std::unique_ptr<Statement> IRGenerator::convertSwitch(const ASTNode& s) {
613 SkASSERT(s.fKind == ASTNode::Kind::kSwitch);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500614 AutoSwitchLevel level(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400615 auto iter = s.begin();
616 std::unique_ptr<Expression> value = this->convertExpression(*(iter++));
Ethan Nicholasaf197692017-02-27 13:26:45 -0500617 if (!value) {
618 return nullptr;
619 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500620 if (value->fType != *fContext.fUInt_Type && value->fType.kind() != Type::kEnum_Kind) {
Ethan Nicholasaf197692017-02-27 13:26:45 -0500621 value = this->coerce(std::move(value), *fContext.fInt_Type);
622 if (!value) {
623 return nullptr;
624 }
625 }
626 AutoSymbolTable table(this);
627 std::unordered_set<int> caseValues;
628 std::vector<std::unique_ptr<SwitchCase>> cases;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400629 for (; iter != s.end(); ++iter) {
630 const ASTNode& c = *iter;
631 SkASSERT(c.fKind == ASTNode::Kind::kSwitchCase);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500632 std::unique_ptr<Expression> caseValue;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400633 auto childIter = c.begin();
634 if (*childIter) {
635 caseValue = this->convertExpression(*childIter);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500636 if (!caseValue) {
637 return nullptr;
638 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500639 caseValue = this->coerce(std::move(caseValue), value->fType);
640 if (!caseValue) {
641 return nullptr;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500642 }
Brian Osman3e3db6c2020-08-14 09:42:12 -0400643 int64_t v = 0;
644 if (!this->getConstantInt(*caseValue, &v)) {
645 fErrors.error(caseValue->fOffset, "case value must be a constant integer");
Ethan Nicholasaf197692017-02-27 13:26:45 -0500646 return nullptr;
647 }
Ethan Nicholasaf197692017-02-27 13:26:45 -0500648 if (caseValues.find(v) != caseValues.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700649 fErrors.error(caseValue->fOffset, "duplicate case value");
Ethan Nicholasaf197692017-02-27 13:26:45 -0500650 }
651 caseValues.insert(v);
652 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400653 ++childIter;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500654 std::vector<std::unique_ptr<Statement>> statements;
Ethan Nicholasfc994162019-06-06 10:04:27 -0400655 for (; childIter != c.end(); ++childIter) {
656 std::unique_ptr<Statement> converted = this->convertStatement(*childIter);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500657 if (!converted) {
658 return nullptr;
659 }
660 statements.push_back(std::move(converted));
661 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400662 cases.emplace_back(new SwitchCase(c.fOffset, std::move(caseValue),
Ethan Nicholasaf197692017-02-27 13:26:45 -0500663 std::move(statements)));
664 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400665 return std::unique_ptr<Statement>(new SwitchStatement(s.fOffset, s.getBool(),
Ethan Nicholasc432b0c2017-07-18 13:22:37 -0400666 std::move(value), std::move(cases),
667 fSymbolTable));
Ethan Nicholasaf197692017-02-27 13:26:45 -0500668}
669
Ethan Nicholasfc994162019-06-06 10:04:27 -0400670std::unique_ptr<Statement> IRGenerator::convertExpressionStatement(const ASTNode& s) {
671 std::unique_ptr<Expression> e = this->convertExpression(s);
ethannicholasb3058bd2016-07-01 08:22:01 -0700672 if (!e) {
673 return nullptr;
674 }
675 this->checkValid(*e);
676 return std::unique_ptr<Statement>(new ExpressionStatement(std::move(e)));
677}
678
Ethan Nicholasfc994162019-06-06 10:04:27 -0400679std::unique_ptr<Statement> IRGenerator::convertReturn(const ASTNode& r) {
680 SkASSERT(r.fKind == ASTNode::Kind::kReturn);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400681 SkASSERT(fCurrentFunction);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000682 // early returns from a vertex main function will bypass the sk_Position normalization, so
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400683 // 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 +0000684 // normalization before each return, but it will probably never actually be necessary.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400685 SkASSERT(Program::kVertex_Kind != fKind || !fRTAdjust || "main" != fCurrentFunction->fName);
Ethan Nicholasfc994162019-06-06 10:04:27 -0400686 if (r.begin() != r.end()) {
687 std::unique_ptr<Expression> result = this->convertExpression(*r.begin());
ethannicholasb3058bd2016-07-01 08:22:01 -0700688 if (!result) {
689 return nullptr;
690 }
ethannicholasd598f792016-07-25 10:08:54 -0700691 if (fCurrentFunction->fReturnType == *fContext.fVoid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700692 fErrors.error(result->fOffset, "may not return a value from a void function");
ethannicholasb3058bd2016-07-01 08:22:01 -0700693 } else {
694 result = this->coerce(std::move(result), fCurrentFunction->fReturnType);
695 if (!result) {
696 return nullptr;
697 }
698 }
699 return std::unique_ptr<Statement>(new ReturnStatement(std::move(result)));
700 } else {
ethannicholasd598f792016-07-25 10:08:54 -0700701 if (fCurrentFunction->fReturnType != *fContext.fVoid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700702 fErrors.error(r.fOffset, "expected function to return '" +
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500703 fCurrentFunction->fReturnType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -0700704 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700705 return std::unique_ptr<Statement>(new ReturnStatement(r.fOffset));
ethannicholasb3058bd2016-07-01 08:22:01 -0700706 }
707}
708
Ethan Nicholasfc994162019-06-06 10:04:27 -0400709std::unique_ptr<Statement> IRGenerator::convertBreak(const ASTNode& b) {
710 SkASSERT(b.fKind == ASTNode::Kind::kBreak);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500711 if (fLoopLevel > 0 || fSwitchLevel > 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700712 return std::unique_ptr<Statement>(new BreakStatement(b.fOffset));
ethannicholas22f939e2016-10-13 13:25:34 -0700713 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700714 fErrors.error(b.fOffset, "break statement must be inside a loop or switch");
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::convertContinue(const ASTNode& c) {
720 SkASSERT(c.fKind == ASTNode::Kind::kContinue);
ethannicholas22f939e2016-10-13 13:25:34 -0700721 if (fLoopLevel > 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700722 return std::unique_ptr<Statement>(new ContinueStatement(c.fOffset));
ethannicholas22f939e2016-10-13 13:25:34 -0700723 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700724 fErrors.error(c.fOffset, "continue statement must be inside a loop");
ethannicholas22f939e2016-10-13 13:25:34 -0700725 return nullptr;
726 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700727}
728
Ethan Nicholasfc994162019-06-06 10:04:27 -0400729std::unique_ptr<Statement> IRGenerator::convertDiscard(const ASTNode& d) {
730 SkASSERT(d.fKind == ASTNode::Kind::kDiscard);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700731 return std::unique_ptr<Statement>(new DiscardStatement(d.fOffset));
ethannicholasb3058bd2016-07-01 08:22:01 -0700732}
733
Ethan Nicholasaae47c82017-11-10 15:34:03 -0500734std::unique_ptr<Block> IRGenerator::applyInvocationIDWorkaround(std::unique_ptr<Block> main) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400735 Layout invokeLayout;
736 Modifiers invokeModifiers(invokeLayout, Modifiers::kHasSideEffects_Flag);
John Stilesb9af7232020-08-20 15:57:48 -0400737 const FunctionDeclaration* invokeDecl = fSymbolTable->add(
738 "_invoke", std::make_unique<FunctionDeclaration>(/*offset=*/-1,
739 invokeModifiers,
740 "_invoke",
741 std::vector<const Variable*>(),
742 *fContext.fVoid_Type,
743 /*builtin=*/false));
744 fProgramElements->push_back(std::make_unique<FunctionDefinition>(/*offset=*/-1,
745 *invokeDecl,
746 std::move(main)));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400747
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000748 std::vector<std::unique_ptr<VarDeclaration>> variables;
John Stilesb9af7232020-08-20 15:57:48 -0400749 const Variable* loopIdx = &(*fSymbolTable)["sk_InvocationID"]->as<Variable>();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700750 std::unique_ptr<Expression> test(new BinaryExpression(-1,
751 std::unique_ptr<Expression>(new VariableReference(-1, *loopIdx)),
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400752 Token::Kind::TK_LT,
John Stilesfbd050b2020-08-03 13:21:46 -0400753 std::make_unique<IntLiteral>(fContext, -1, fInvocations),
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400754 *fContext.fBool_Type));
755 std::unique_ptr<Expression> next(new PostfixExpression(
756 std::unique_ptr<Expression>(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700757 new VariableReference(-1,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400758 *loopIdx,
759 VariableReference::kReadWrite_RefKind)),
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400760 Token::Kind::TK_PLUSPLUS));
Ethan Nicholasfc994162019-06-06 10:04:27 -0400761 ASTNode endPrimitiveID(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier, "EndPrimitive");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400762 std::unique_ptr<Expression> endPrimitive = this->convertExpression(endPrimitiveID);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400763 SkASSERT(endPrimitive);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400764
765 std::vector<std::unique_ptr<Statement>> loopBody;
766 std::vector<std::unique_ptr<Expression>> invokeArgs;
767 loopBody.push_back(std::unique_ptr<Statement>(new ExpressionStatement(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700768 this->call(-1,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400769 *invokeDecl,
770 std::vector<std::unique_ptr<Expression>>()))));
771 loopBody.push_back(std::unique_ptr<Statement>(new ExpressionStatement(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700772 this->call(-1,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400773 std::move(endPrimitive),
774 std::vector<std::unique_ptr<Expression>>()))));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700775 std::unique_ptr<Expression> assignment(new BinaryExpression(-1,
Ethan Nicholas4fadce42020-07-30 13:29:30 -0400776 std::unique_ptr<Expression>(new VariableReference(-1, *loopIdx,
777 VariableReference::kWrite_RefKind)),
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400778 Token::Kind::TK_EQ,
John Stilesfbd050b2020-08-03 13:21:46 -0400779 std::make_unique<IntLiteral>(fContext, -1, 0),
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400780 *fContext.fInt_Type));
781 std::unique_ptr<Statement> initializer(new ExpressionStatement(std::move(assignment)));
782 std::unique_ptr<Statement> loop = std::unique_ptr<Statement>(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700783 new ForStatement(-1,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400784 std::move(initializer),
785 std::move(test),
786 std::move(next),
John Stilesfbd050b2020-08-03 13:21:46 -0400787 std::make_unique<Block>(-1, std::move(loopBody)),
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400788 fSymbolTable));
789 std::vector<std::unique_ptr<Statement>> children;
790 children.push_back(std::move(loop));
John Stilesfbd050b2020-08-03 13:21:46 -0400791 return std::make_unique<Block>(-1, std::move(children));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400792}
793
Robert Phillipsfe8da172018-01-24 14:52:02 +0000794std::unique_ptr<Statement> IRGenerator::getNormalizeSkPositionCode() {
Ethan Nicholasb809efb2018-04-12 14:39:21 -0400795 // sk_Position = float4(sk_Position.xy * rtAdjust.xz + sk_Position.ww * rtAdjust.yw,
Robert Phillipsfe8da172018-01-24 14:52:02 +0000796 // 0,
797 // sk_Position.w);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400798 SkASSERT(fSkPerVertex && fRTAdjust);
Robert Phillipsfe8da172018-01-24 14:52:02 +0000799 #define REF(var) std::unique_ptr<Expression>(\
800 new VariableReference(-1, *var, VariableReference::kRead_RefKind))
Ethan Nicholas4fadce42020-07-30 13:29:30 -0400801 #define WREF(var) std::unique_ptr<Expression>(\
802 new VariableReference(-1, *var, VariableReference::kWrite_RefKind))
Robert Phillipsfe8da172018-01-24 14:52:02 +0000803 #define FIELD(var, idx) std::unique_ptr<Expression>(\
804 new FieldAccess(REF(var), idx, FieldAccess::kAnonymousInterfaceBlock_OwnerKind))
Ethan Nicholas4fadce42020-07-30 13:29:30 -0400805 #define POS std::unique_ptr<Expression>(new FieldAccess(WREF(fSkPerVertex), 0, \
Robert Phillipsfe8da172018-01-24 14:52:02 +0000806 FieldAccess::kAnonymousInterfaceBlock_OwnerKind))
807 #define ADJUST (fRTAdjustInterfaceBlock ? \
808 FIELD(fRTAdjustInterfaceBlock, fRTAdjustFieldIndex) : \
809 REF(fRTAdjust))
Ethan Nicholasb809efb2018-04-12 14:39:21 -0400810 #define SWIZZLE(expr, ...) std::unique_ptr<Expression>(new Swizzle(fContext, expr, \
811 { __VA_ARGS__ }))
812 #define OP(left, op, right) std::unique_ptr<Expression>( \
813 new BinaryExpression(-1, left, op, right, \
814 *fContext.fFloat2_Type))
Robert Phillipsfe8da172018-01-24 14:52:02 +0000815 std::vector<std::unique_ptr<Expression>> children;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400816 children.push_back(OP(OP(SWIZZLE(POS, 0, 1), Token::Kind::TK_STAR, SWIZZLE(ADJUST, 0, 2)),
817 Token::Kind::TK_PLUS,
818 OP(SWIZZLE(POS, 3, 3), Token::Kind::TK_STAR, SWIZZLE(ADJUST, 1, 3))));
Robert Phillipsfe8da172018-01-24 14:52:02 +0000819 children.push_back(std::unique_ptr<Expression>(new FloatLiteral(fContext, -1, 0.0)));
820 children.push_back(SWIZZLE(POS, 3));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400821 std::unique_ptr<Expression> result = OP(POS, Token::Kind::TK_EQ,
Robert Phillipsfe8da172018-01-24 14:52:02 +0000822 std::unique_ptr<Expression>(new Constructor(-1,
823 *fContext.fFloat4_Type,
824 std::move(children))));
825 return std::unique_ptr<Statement>(new ExpressionStatement(std::move(result)));
826}
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();
880 const Type* returnType = this->convertType(*(iter++));
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);
ethannicholasd598f792016-07-25 10:08:54 -0700902 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(
918 std::make_unique<Type>(std::move(name), Type::kArray_Kind, *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 }
Ethan Nicholasfc994162019-06-06 10:04:27 -0400927 StringFragment name = pd.fName;
John Stiles3ae071e2020-08-05 15:29:29 -0400928 const Variable* var = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Variable>(
929 param.fOffset, pd.fModifiers, name, *type, Variable::kParameter_Storage));
ethannicholasd598f792016-07-25 10:08:54 -0700930 parameters.push_back(var);
ethannicholasb3058bd2016-07-01 08:22:01 -0700931 }
932
Brian Osman767f4442020-08-13 16:59:48 -0400933 auto paramIsCoords = [&](int idx) {
934 return parameters[idx]->fType == *fContext.fFloat2_Type &&
935 parameters[idx]->fModifiers.fFlags == 0;
936 };
Brian Osman767f4442020-08-13 16:59:48 -0400937
John Stilesb9af7232020-08-20 15:57:48 -0400938 if (funcData.fName == "main") {
Ethan Nicholas0d997662019-04-08 09:46:01 -0400939 switch (fKind) {
940 case Program::kPipelineStage_Kind: {
Brian Osman767f4442020-08-13 16:59:48 -0400941 // half4 main() -or- half4 main(float2)
942 bool valid = (*returnType == *fContext.fHalf4_Type) &&
943 ((parameters.size() == 0) ||
944 (parameters.size() == 1 && paramIsCoords(0)));
945 if (!valid) {
946 fErrors.error(f.fOffset, "pipeline stage 'main' must be declared "
947 "half4 main() or half4 main(float2)");
948 return;
949 }
950 break;
Brian Osman44820a92020-08-26 09:27:39 -0400951 }
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400952 case Program::kFragmentProcessor_Kind: {
Brian Osman44820a92020-08-26 09:27:39 -0400953 bool valid = (parameters.size() == 0) ||
954 (parameters.size() == 1 && paramIsCoords(0));
Michael Ludwigfc2fdf02020-06-29 17:20:13 -0400955 if (!valid) {
956 fErrors.error(f.fOffset, ".fp 'main' must be declared main() or main(float2)");
957 return;
958 }
959 break;
960 }
Ethan Nicholas746035a2019-04-23 13:31:09 -0400961 case Program::kGeneric_Kind:
Ethan Nicholas0d997662019-04-08 09:46:01 -0400962 break;
Ethan Nicholas0d997662019-04-08 09:46:01 -0400963 default:
964 if (parameters.size()) {
965 fErrors.error(f.fOffset, "shader 'main' must have zero parameters");
966 }
Ethan Nicholas00543112018-07-31 09:44:36 -0400967 }
968 }
969
ethannicholasb3058bd2016-07-01 08:22:01 -0700970 // find existing declaration
ethannicholasd598f792016-07-25 10:08:54 -0700971 const FunctionDeclaration* decl = nullptr;
John Stilesb9af7232020-08-20 15:57:48 -0400972 const Symbol* entry = (*fSymbolTable)[funcData.fName];
ethannicholasb3058bd2016-07-01 08:22:01 -0700973 if (entry) {
ethannicholasd598f792016-07-25 10:08:54 -0700974 std::vector<const FunctionDeclaration*> functions;
ethannicholasb3058bd2016-07-01 08:22:01 -0700975 switch (entry->fKind) {
976 case Symbol::kUnresolvedFunction_Kind:
John Stiles17c5b702020-08-18 10:40:03 -0400977 functions = entry->as<UnresolvedFunction>().fFunctions;
ethannicholasb3058bd2016-07-01 08:22:01 -0700978 break;
979 case Symbol::kFunctionDeclaration_Kind:
John Stiles17c5b702020-08-18 10:40:03 -0400980 functions.push_back(&entry->as<FunctionDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -0700981 break;
982 default:
John Stilesb9af7232020-08-20 15:57:48 -0400983 fErrors.error(f.fOffset, "symbol '" + funcData.fName + "' was already defined");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400984 return;
ethannicholasb3058bd2016-07-01 08:22:01 -0700985 }
John Stilesb9af7232020-08-20 15:57:48 -0400986 for (const FunctionDeclaration* other : functions) {
987 SkASSERT(other->fName == funcData.fName);
ethannicholasb3058bd2016-07-01 08:22:01 -0700988 if (parameters.size() == other->fParameters.size()) {
989 bool match = true;
990 for (size_t i = 0; i < parameters.size(); i++) {
991 if (parameters[i]->fType != other->fParameters[i]->fType) {
992 match = false;
993 break;
994 }
995 }
996 if (match) {
ethannicholasd598f792016-07-25 10:08:54 -0700997 if (*returnType != other->fReturnType) {
John Stilesb9af7232020-08-20 15:57:48 -0400998 FunctionDeclaration newDecl(f.fOffset, funcData.fModifiers, funcData.fName,
999 parameters, *returnType, fIsBuiltinCode);
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001000 fErrors.error(f.fOffset, "functions '" + newDecl.description() +
1001 "' and '" + other->description() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001002 "' differ only in return type");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001003 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001004 }
1005 decl = other;
1006 for (size_t i = 0; i < parameters.size(); i++) {
1007 if (parameters[i]->fModifiers != other->fParameters[i]->fModifiers) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001008 fErrors.error(f.fOffset, "modifiers on parameter " +
1009 to_string((uint64_t) i + 1) +
John Stilesb9af7232020-08-20 15:57:48 -04001010 " differ between declaration and definition");
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001011 return;
ethannicholasb3058bd2016-07-01 08:22:01 -07001012 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001013 }
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001014 if (other->fDefinition && !other->fBuiltin) {
John Stilesb9af7232020-08-20 15:57:48 -04001015 fErrors.error(f.fOffset, "duplicate definition of " + other->description());
ethannicholasb3058bd2016-07-01 08:22:01 -07001016 }
1017 break;
1018 }
1019 }
1020 }
1021 }
1022 if (!decl) {
John Stilesb9af7232020-08-20 15:57:48 -04001023 // Conservatively assume all user-defined functions have side effects.
1024 Modifiers declModifiers = funcData.fModifiers;
1025 if (!fIsBuiltinCode) {
1026 declModifiers.fFlags |= Modifiers::kHasSideEffects_Flag;
1027 }
1028
1029 // Create a new declaration.
1030 decl = fSymbolTable->add(funcData.fName,
John Stiles311dd9d2020-08-13 17:09:29 -04001031 std::make_unique<FunctionDeclaration>(f.fOffset,
John Stilesb9af7232020-08-20 15:57:48 -04001032 declModifiers,
1033 funcData.fName,
John Stiles311dd9d2020-08-13 17:09:29 -04001034 parameters,
1035 *returnType,
1036 fIsBuiltinCode));
ethannicholasb3058bd2016-07-01 08:22:01 -07001037 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001038 if (iter != f.end()) {
1039 // compile body
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001040 SkASSERT(!fCurrentFunction);
ethannicholasd598f792016-07-25 10:08:54 -07001041 fCurrentFunction = decl;
ethannicholasd598f792016-07-25 10:08:54 -07001042 std::shared_ptr<SymbolTable> old = fSymbolTable;
1043 AutoSymbolTable table(this);
Brian Osman44820a92020-08-26 09:27:39 -04001044 if (funcData.fName == "main" && (fKind == Program::kPipelineStage_Kind ||
1045 fKind == Program::kFragmentProcessor_Kind)) {
Brian Osman767f4442020-08-13 16:59:48 -04001046 if (parameters.size() == 1) {
1047 SkASSERT(paramIsCoords(0));
1048 parameters[0]->fModifiers.fLayout.fBuiltin = SK_MAIN_COORDS_BUILTIN;
1049 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001050 }
ethannicholasd598f792016-07-25 10:08:54 -07001051 for (size_t i = 0; i < parameters.size(); i++) {
1052 fSymbolTable->addWithoutOwnership(parameters[i]->fName, decl->fParameters[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -07001053 }
John Stilesb9af7232020-08-20 15:57:48 -04001054 bool needInvocationIDWorkaround = fInvocations != -1 && funcData.fName == "main" &&
Chris Daltonf1b47bb2017-10-06 11:57:51 -06001055 fSettings->fCaps &&
1056 !fSettings->fCaps->gsInvocationsSupport();
Ethan Nicholasfc994162019-06-06 10:04:27 -04001057 std::unique_ptr<Block> body = this->convertBlock(*iter);
ethannicholasd598f792016-07-25 10:08:54 -07001058 fCurrentFunction = nullptr;
1059 if (!body) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001060 return;
1061 }
1062 if (needInvocationIDWorkaround) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001063 body = this->applyInvocationIDWorkaround(std::move(body));
ethannicholasd598f792016-07-25 10:08:54 -07001064 }
John Stilesb9af7232020-08-20 15:57:48 -04001065 if (Program::kVertex_Kind == fKind && funcData.fName == "main" && fRTAdjust) {
Robert Phillipsfe8da172018-01-24 14:52:02 +00001066 body->fStatements.insert(body->fStatements.end(), this->getNormalizeSkPositionCode());
1067 }
John Stilesb8e010c2020-08-11 18:05:39 -04001068 auto result = std::make_unique<FunctionDefinition>(f.fOffset, *decl, std::move(body),
1069 std::move(fReferencedIntrinsics));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001070 decl->fDefinition = result.get();
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001071 result->fSource = &f;
1072 fProgramElements->push_back(std::move(result));
ethannicholasb3058bd2016-07-01 08:22:01 -07001073 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001074}
1075
Ethan Nicholasfc994162019-06-06 10:04:27 -04001076std::unique_ptr<InterfaceBlock> IRGenerator::convertInterfaceBlock(const ASTNode& intf) {
1077 SkASSERT(intf.fKind == ASTNode::Kind::kInterfaceBlock);
1078 ASTNode::InterfaceBlockData id = intf.getInterfaceBlockData();
ethannicholasb3058bd2016-07-01 08:22:01 -07001079 std::shared_ptr<SymbolTable> old = fSymbolTable;
Ethan Nicholas68dd2c12018-03-01 15:05:17 -05001080 this->pushSymbolTable();
1081 std::shared_ptr<SymbolTable> symbols = fSymbolTable;
ethannicholasb3058bd2016-07-01 08:22:01 -07001082 std::vector<Type::Field> fields;
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001083 bool haveRuntimeArray = false;
Robert Phillipsfe8da172018-01-24 14:52:02 +00001084 bool foundRTAdjust = false;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001085 auto iter = intf.begin();
1086 for (size_t i = 0; i < id.fDeclarationCount; ++i) {
ethannicholas14fe8cc2016-09-07 13:37:16 -07001087 std::unique_ptr<VarDeclarations> decl = this->convertVarDeclarations(
Ethan Nicholasfc994162019-06-06 10:04:27 -04001088 *(iter++),
Ethan Nicholasa7ceb502019-01-11 10:31:48 -05001089 Variable::kInterfaceBlock_Storage);
ethannicholas7effa7a2016-10-14 09:56:33 -07001090 if (!decl) {
1091 return nullptr;
1092 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001093 for (const auto& stmt : decl->fVars) {
John Stiles403a3632020-08-20 12:11:48 -04001094 VarDeclaration& vd = stmt->as<VarDeclaration>();
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001095 if (haveRuntimeArray) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001096 fErrors.error(decl->fOffset,
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001097 "only the last entry in an interface block may be a runtime-sized "
1098 "array");
1099 }
Robert Phillipsfe8da172018-01-24 14:52:02 +00001100 if (vd.fVar == fRTAdjust) {
1101 foundRTAdjust = true;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001102 SkASSERT(vd.fVar->fType == *fContext.fFloat4_Type);
Robert Phillipsfe8da172018-01-24 14:52:02 +00001103 fRTAdjustFieldIndex = fields.size();
1104 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001105 fields.push_back(Type::Field(vd.fVar->fModifiers, vd.fVar->fName,
1106 &vd.fVar->fType));
1107 if (vd.fValue) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001108 fErrors.error(decl->fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -07001109 "initializers are not permitted on interface block fields");
1110 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001111 if (vd.fVar->fType.kind() == Type::kArray_Kind &&
1112 vd.fVar->fType.columns() == -1) {
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04001113 haveRuntimeArray = true;
1114 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001115 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001116 }
Ethan Nicholas68dd2c12018-03-01 15:05:17 -05001117 this->popSymbolTable();
John Stiles3ae071e2020-08-05 15:29:29 -04001118 const Type* type =
1119 old->takeOwnershipOfSymbol(std::make_unique<Type>(intf.fOffset, id.fTypeName, fields));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001120 std::vector<std::unique_ptr<Expression>> sizes;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001121 for (size_t i = 0; i < id.fSizeCount; ++i) {
1122 const ASTNode& size = *(iter++);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001123 if (size) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001124 std::unique_ptr<Expression> converted = this->convertExpression(size);
Ethan Nicholas50afc172017-02-16 14:49:57 -05001125 if (!converted) {
1126 return nullptr;
1127 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001128 String name = type->fName;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001129 int64_t count;
1130 if (converted->fKind == Expression::kIntLiteral_Kind) {
John Stiles81365af2020-08-18 09:24:00 -04001131 count = converted->as<IntLiteral>().fValue;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001132 if (count <= 0) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001133 fErrors.error(converted->fOffset, "array size must be positive");
Ethan Nicholas66d80062019-09-09 14:50:51 -04001134 return nullptr;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001135 }
1136 name += "[" + to_string(count) + "]";
1137 } else {
Ethan Nicholas66d80062019-09-09 14:50:51 -04001138 fErrors.error(intf.fOffset, "array size must be specified");
1139 return nullptr;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001140 }
John Stiles3ae071e2020-08-05 15:29:29 -04001141 type = symbols->takeOwnershipOfSymbol(
1142 std::make_unique<Type>(name, Type::kArray_Kind, *type, (int)count));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001143 sizes.push_back(std::move(converted));
1144 } else {
Ethan Nicholas66d80062019-09-09 14:50:51 -04001145 fErrors.error(intf.fOffset, "array size must be specified");
1146 return nullptr;
Ethan Nicholas50afc172017-02-16 14:49:57 -05001147 }
1148 }
John Stiles3ae071e2020-08-05 15:29:29 -04001149 const Variable* var = old->takeOwnershipOfSymbol(
1150 std::make_unique<Variable>(intf.fOffset,
1151 id.fModifiers,
1152 id.fInstanceName.fLength ? id.fInstanceName : id.fTypeName,
1153 *type,
1154 Variable::kGlobal_Storage));
Robert Phillipsfe8da172018-01-24 14:52:02 +00001155 if (foundRTAdjust) {
1156 fRTAdjustInterfaceBlock = var;
1157 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001158 if (id.fInstanceName.fLength) {
1159 old->addWithoutOwnership(id.fInstanceName, var);
ethannicholasb3058bd2016-07-01 08:22:01 -07001160 } else {
1161 for (size_t i = 0; i < fields.size(); i++) {
John Stilesfbd050b2020-08-03 13:21:46 -04001162 old->add(fields[i].fName, std::make_unique<Field>(intf.fOffset, *var, (int)i));
ethannicholasb3058bd2016-07-01 08:22:01 -07001163 }
1164 }
John Stilesfbd050b2020-08-03 13:21:46 -04001165 return std::make_unique<InterfaceBlock>(intf.fOffset,
1166 var,
1167 id.fTypeName,
1168 id.fInstanceName,
1169 std::move(sizes),
1170 symbols);
ethannicholasb3058bd2016-07-01 08:22:01 -07001171}
1172
Brian Osman3e3db6c2020-08-14 09:42:12 -04001173bool IRGenerator::getConstantInt(const Expression& value, int64_t* out) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001174 switch (value.fKind) {
1175 case Expression::kIntLiteral_Kind:
Brian Osman3e3db6c2020-08-14 09:42:12 -04001176 *out = static_cast<const IntLiteral&>(value).fValue;
1177 return true;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001178 case Expression::kVariableReference_Kind: {
Brian Osman3e3db6c2020-08-14 09:42:12 -04001179 const Variable& var = static_cast<const VariableReference&>(value).fVariable;
1180 return (var.fModifiers.fFlags & Modifiers::kConst_Flag) &&
1181 var.fInitialValue &&
1182 this->getConstantInt(*var.fInitialValue, out);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001183 }
1184 default:
Brian Osman3e3db6c2020-08-14 09:42:12 -04001185 return false;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001186 }
1187}
1188
Ethan Nicholasfc994162019-06-06 10:04:27 -04001189void IRGenerator::convertEnum(const ASTNode& e) {
1190 SkASSERT(e.fKind == ASTNode::Kind::kEnum);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001191 int64_t currentValue = 0;
1192 Layout layout;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001193 ASTNode enumType(e.fNodes, e.fOffset, ASTNode::Kind::kType,
1194 ASTNode::TypeData(e.getString(), false, false));
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001195 const Type* type = this->convertType(enumType);
1196 Modifiers modifiers(layout, Modifiers::kConst_Flag);
Brian Osman3e3db6c2020-08-14 09:42:12 -04001197 AutoSymbolTable table(this);
Ethan Nicholasfc994162019-06-06 10:04:27 -04001198 for (auto iter = e.begin(); iter != e.end(); ++iter) {
1199 const ASTNode& child = *iter;
1200 SkASSERT(child.fKind == ASTNode::Kind::kEnumCase);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001201 std::unique_ptr<Expression> value;
Ethan Nicholasfc994162019-06-06 10:04:27 -04001202 if (child.begin() != child.end()) {
1203 value = this->convertExpression(*child.begin());
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001204 if (!value) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001205 return;
1206 }
Brian Osman3e3db6c2020-08-14 09:42:12 -04001207 if (!this->getConstantInt(*value, &currentValue)) {
1208 fErrors.error(value->fOffset, "enum value must be a constant integer");
1209 return;
1210 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001211 }
1212 value = std::unique_ptr<Expression>(new IntLiteral(fContext, e.fOffset, currentValue));
1213 ++currentValue;
Brian Osman3e3db6c2020-08-14 09:42:12 -04001214 fSymbolTable->add(child.getString(),
1215 std::make_unique<Variable>(e.fOffset, modifiers, child.getString(), *type,
1216 Variable::kGlobal_Storage, value.get()));
1217 fSymbolTable->takeOwnershipOfIRNode(std::move(value));
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001218 }
Brian Osman3e3db6c2020-08-14 09:42:12 -04001219 fProgramElements->push_back(std::unique_ptr<ProgramElement>(
1220 new Enum(e.fOffset, e.getString(), fSymbolTable, fIsBuiltinCode)));
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001221}
1222
Ethan Nicholasfc994162019-06-06 10:04:27 -04001223const Type* IRGenerator::convertType(const ASTNode& type) {
1224 ASTNode::TypeData td = type.getTypeData();
1225 const Symbol* result = (*fSymbolTable)[td.fName];
ethannicholasb3058bd2016-07-01 08:22:01 -07001226 if (result && result->fKind == Symbol::kType_Kind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001227 if (td.fIsNullable) {
John Stiles17c5b702020-08-18 10:40:03 -04001228 if (result->as<Type>() == *fContext.fFragmentProcessor_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001229 if (type.begin() != type.end()) {
1230 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be used in "
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001231 "an array");
1232 }
John Stiles3ae071e2020-08-05 15:29:29 -04001233 result = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
John Stiles17c5b702020-08-18 10:40:03 -04001234 String(result->fName) + "?", Type::kNullable_Kind, result->as<Type>()));
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001235 } else {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001236 fErrors.error(type.fOffset, "type '" + td.fName + "' may not be nullable");
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001237 }
1238 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001239 for (const auto& size : type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001240 String name(result->fName);
1241 name += "[";
Ethan Nicholasfc994162019-06-06 10:04:27 -04001242 if (size) {
1243 name += to_string(size.getInt());
Ethan Nicholas50afc172017-02-16 14:49:57 -05001244 }
1245 name += "]";
John Stiles3ae071e2020-08-05 15:29:29 -04001246 result = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
John Stiles17c5b702020-08-18 10:40:03 -04001247 name, Type::kArray_Kind, result->as<Type>(), size ? size.getInt() : 0));
Ethan Nicholas50afc172017-02-16 14:49:57 -05001248 }
John Stiles17c5b702020-08-18 10:40:03 -04001249 return &result->as<Type>();
ethannicholasb3058bd2016-07-01 08:22:01 -07001250 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001251 fErrors.error(type.fOffset, "unknown type '" + td.fName + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001252 return nullptr;
1253}
1254
Ethan Nicholasfc994162019-06-06 10:04:27 -04001255std::unique_ptr<Expression> IRGenerator::convertExpression(const ASTNode& expr) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001256 switch (expr.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001257 case ASTNode::Kind::kBinary:
1258 return this->convertBinaryExpression(expr);
1259 case ASTNode::Kind::kBool:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001260 return std::unique_ptr<Expression>(new BoolLiteral(fContext, expr.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04001261 expr.getBool()));
1262 case ASTNode::Kind::kCall:
1263 return this->convertCallExpression(expr);
1264 case ASTNode::Kind::kField:
1265 return this->convertFieldExpression(expr);
1266 case ASTNode::Kind::kFloat:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001267 return std::unique_ptr<Expression>(new FloatLiteral(fContext, expr.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04001268 expr.getFloat()));
1269 case ASTNode::Kind::kIdentifier:
1270 return this->convertIdentifier(expr);
1271 case ASTNode::Kind::kIndex:
1272 return this->convertIndexExpression(expr);
1273 case ASTNode::Kind::kInt:
1274 return std::unique_ptr<Expression>(new IntLiteral(fContext, expr.fOffset,
1275 expr.getInt()));
1276 case ASTNode::Kind::kNull:
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001277 return std::unique_ptr<Expression>(new NullLiteral(fContext, expr.fOffset));
Ethan Nicholasfc994162019-06-06 10:04:27 -04001278 case ASTNode::Kind::kPostfix:
1279 return this->convertPostfixExpression(expr);
1280 case ASTNode::Kind::kPrefix:
1281 return this->convertPrefixExpression(expr);
1282 case ASTNode::Kind::kTernary:
1283 return this->convertTernaryExpression(expr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001284 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001285#ifdef SK_DEBUG
Ethan Nicholasfc994162019-06-06 10:04:27 -04001286 ABORT("unsupported expression: %s\n", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001287#endif
1288 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001289 }
1290}
1291
Ethan Nicholasfc994162019-06-06 10:04:27 -04001292std::unique_ptr<Expression> IRGenerator::convertIdentifier(const ASTNode& identifier) {
1293 SkASSERT(identifier.fKind == ASTNode::Kind::kIdentifier);
1294 const Symbol* result = (*fSymbolTable)[identifier.getString()];
ethannicholasb3058bd2016-07-01 08:22:01 -07001295 if (!result) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001296 fErrors.error(identifier.fOffset, "unknown identifier '" + identifier.getString() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001297 return nullptr;
1298 }
1299 switch (result->fKind) {
1300 case Symbol::kFunctionDeclaration_Kind: {
ethannicholasd598f792016-07-25 10:08:54 -07001301 std::vector<const FunctionDeclaration*> f = {
John Stiles17c5b702020-08-18 10:40:03 -04001302 &result->as<FunctionDeclaration>()
ethannicholasb3058bd2016-07-01 08:22:01 -07001303 };
John Stilesfbd050b2020-08-03 13:21:46 -04001304 return std::make_unique<FunctionReference>(fContext, identifier.fOffset, f);
ethannicholasb3058bd2016-07-01 08:22:01 -07001305 }
1306 case Symbol::kUnresolvedFunction_Kind: {
John Stiles17c5b702020-08-18 10:40:03 -04001307 const UnresolvedFunction* f = &result->as<UnresolvedFunction>();
John Stilesfbd050b2020-08-03 13:21:46 -04001308 return std::make_unique<FunctionReference>(fContext, identifier.fOffset, f->fFunctions);
ethannicholasb3058bd2016-07-01 08:22:01 -07001309 }
1310 case Symbol::kVariable_Kind: {
John Stiles17c5b702020-08-18 10:40:03 -04001311 const Variable* var = &result->as<Variable>();
Ethan Nicholascd700e92018-08-24 16:43:57 -04001312 switch (var->fModifiers.fLayout.fBuiltin) {
1313 case SK_WIDTH_BUILTIN:
1314 fInputs.fRTWidth = true;
1315 break;
1316 case SK_HEIGHT_BUILTIN:
Greg Daniele6ab9982018-08-22 13:56:32 +00001317 fInputs.fRTHeight = true;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001318 break;
1319#ifndef SKSL_STANDALONE
1320 case SK_FRAGCOORD_BUILTIN:
Brian Osman9f313b62019-10-02 12:03:11 -04001321 fInputs.fFlipY = true;
1322 if (fSettings->fFlipY &&
1323 (!fSettings->fCaps ||
1324 !fSettings->fCaps->fragCoordConventionsExtensionString())) {
1325 fInputs.fRTHeight = true;
Ethan Nicholascd700e92018-08-24 16:43:57 -04001326 }
Greg Daniele6ab9982018-08-22 13:56:32 +00001327#endif
Ethan Nicholascd700e92018-08-24 16:43:57 -04001328 }
Ethan Nicholas33c59ed2019-08-13 10:21:38 -04001329 if (fKind == Program::kFragmentProcessor_Kind &&
1330 (var->fModifiers.fFlags & Modifiers::kIn_Flag) &&
1331 !(var->fModifiers.fFlags & Modifiers::kUniform_Flag) &&
1332 !var->fModifiers.fLayout.fKey &&
1333 var->fModifiers.fLayout.fBuiltin == -1 &&
1334 var->fType.nonnullable() != *fContext.fFragmentProcessor_Type &&
1335 var->fType.kind() != Type::kSampler_Kind) {
1336 bool valid = false;
1337 for (const auto& decl : fFile->root()) {
1338 if (decl.fKind == ASTNode::Kind::kSection) {
1339 ASTNode::SectionData section = decl.getSectionData();
1340 if (section.fName == "setData") {
1341 valid = true;
1342 break;
1343 }
1344 }
1345 }
1346 if (!valid) {
1347 fErrors.error(identifier.fOffset, "'in' variable must be either 'uniform' or "
1348 "'layout(key)', or there must be a custom "
1349 "@setData function");
1350 }
1351 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001352 // default to kRead_RefKind; this will be corrected later if the variable is written to
John Stilesfbd050b2020-08-03 13:21:46 -04001353 return std::make_unique<VariableReference>(identifier.fOffset,
1354 *var,
1355 VariableReference::kRead_RefKind);
ethannicholasb3058bd2016-07-01 08:22:01 -07001356 }
1357 case Symbol::kField_Kind: {
John Stiles17c5b702020-08-18 10:40:03 -04001358 const Field* field = &result->as<Field>();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001359 VariableReference* base = new VariableReference(identifier.fOffset, field->fOwner,
Ethan Nicholas86a43402017-01-19 13:32:00 -05001360 VariableReference::kRead_RefKind);
ethannicholasf789b382016-08-03 12:43:36 -07001361 return std::unique_ptr<Expression>(new FieldAccess(
1362 std::unique_ptr<Expression>(base),
1363 field->fFieldIndex,
1364 FieldAccess::kAnonymousInterfaceBlock_OwnerKind));
ethannicholasb3058bd2016-07-01 08:22:01 -07001365 }
1366 case Symbol::kType_Kind: {
John Stiles17c5b702020-08-18 10:40:03 -04001367 const Type* t = &result->as<Type>();
John Stilesfbd050b2020-08-03 13:21:46 -04001368 return std::make_unique<TypeReference>(fContext, identifier.fOffset, *t);
ethannicholasb3058bd2016-07-01 08:22:01 -07001369 }
Ethan Nicholas91164d12019-05-15 15:29:54 -04001370 case Symbol::kExternal_Kind: {
John Stiles17c5b702020-08-18 10:40:03 -04001371 const ExternalValue* r = &result->as<ExternalValue>();
John Stilesfbd050b2020-08-03 13:21:46 -04001372 return std::make_unique<ExternalValueReference>(identifier.fOffset, r);
Ethan Nicholas91164d12019-05-15 15:29:54 -04001373 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001374 default:
1375 ABORT("unsupported symbol type %d\n", result->fKind);
1376 }
Ethan Nicholasc0709392017-06-27 11:20:22 -04001377}
1378
Ethan Nicholasfc994162019-06-06 10:04:27 -04001379std::unique_ptr<Section> IRGenerator::convertSection(const ASTNode& s) {
1380 ASTNode::SectionData section = s.getSectionData();
John Stilesfbd050b2020-08-03 13:21:46 -04001381 return std::make_unique<Section>(s.fOffset, section.fName, section.fArgument,
1382 section.fText);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001383}
1384
1385
Ethan Nicholas11d53972016-11-28 11:23:23 -05001386std::unique_ptr<Expression> IRGenerator::coerce(std::unique_ptr<Expression> expr,
ethannicholasd598f792016-07-25 10:08:54 -07001387 const Type& type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001388 if (!expr) {
1389 return nullptr;
1390 }
ethannicholasd598f792016-07-25 10:08:54 -07001391 if (expr->fType == type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001392 return expr;
1393 }
1394 this->checkValid(*expr);
ethannicholasd598f792016-07-25 10:08:54 -07001395 if (expr->fType == *fContext.fInvalid_Type) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001396 return nullptr;
1397 }
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001398 if (expr->coercionCost(type) == INT_MAX) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001399 fErrors.error(expr->fOffset, "expected '" + type.displayName() + "', but found '" +
1400 expr->fType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001401 return nullptr;
1402 }
ethannicholasd598f792016-07-25 10:08:54 -07001403 if (type.kind() == Type::kScalar_Kind) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001404 std::vector<std::unique_ptr<Expression>> args;
1405 args.push_back(std::move(expr));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001406 std::unique_ptr<Expression> ctor;
1407 if (type == *fContext.fFloatLiteral_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001408 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
1409 "float"));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001410 } else if (type == *fContext.fIntLiteral_Type) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001411 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
1412 "int"));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001413 } else {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001414 ctor = this->convertIdentifier(ASTNode(&fFile->fNodes, -1, ASTNode::Kind::kIdentifier,
1415 type.fName));
Ethan Nicholase1f55022019-02-05 17:17:40 -05001416 }
1417 if (!ctor) {
1418 printf("error, null identifier: %s\n", String(type.fName).c_str());
1419 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001420 SkASSERT(ctor);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001421 return this->call(-1, std::move(ctor), std::move(args));
ethannicholasb3058bd2016-07-01 08:22:01 -07001422 }
Ethan Nicholasee1c8a72019-02-22 10:50:47 -05001423 if (expr->fKind == Expression::kNullLiteral_Kind) {
1424 SkASSERT(type.kind() == Type::kNullable_Kind);
1425 return std::unique_ptr<Expression>(new NullLiteral(expr->fOffset, type));
1426 }
ethannicholas5961bc92016-10-12 06:39:56 -07001427 std::vector<std::unique_ptr<Expression>> args;
1428 args.push_back(std::move(expr));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001429 return std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
ethannicholasb3058bd2016-07-01 08:22:01 -07001430}
1431
ethannicholasf789b382016-08-03 12:43:36 -07001432static bool is_matrix_multiply(const Type& left, const Type& right) {
1433 if (left.kind() == Type::kMatrix_Kind) {
1434 return right.kind() == Type::kMatrix_Kind || right.kind() == Type::kVector_Kind;
1435 }
1436 return left.kind() == Type::kVector_Kind && right.kind() == Type::kMatrix_Kind;
1437}
ethannicholasea4567c2016-10-17 11:24:37 -07001438
ethannicholasb3058bd2016-07-01 08:22:01 -07001439/**
1440 * Determines the operand and result types of a binary expression. Returns true if the expression is
1441 * legal, false otherwise. If false, the values of the out parameters are undefined.
1442 */
Ethan Nicholas11d53972016-11-28 11:23:23 -05001443static bool determine_binary_type(const Context& context,
1444 Token::Kind op,
1445 const Type& left,
1446 const Type& right,
ethannicholasd598f792016-07-25 10:08:54 -07001447 const Type** outLeftType,
1448 const Type** outRightType,
1449 const Type** outResultType,
ethannicholasb3058bd2016-07-01 08:22:01 -07001450 bool tryFlipped) {
1451 bool isLogical;
ethannicholasea4567c2016-10-17 11:24:37 -07001452 bool validMatrixOrVectorOp;
ethannicholasb3058bd2016-07-01 08:22:01 -07001453 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001454 case Token::Kind::TK_EQ:
ethannicholasea4567c2016-10-17 11:24:37 -07001455 *outLeftType = &left;
1456 *outRightType = &left;
1457 *outResultType = &left;
1458 return right.canCoerceTo(left);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001459 case Token::Kind::TK_EQEQ: // fall through
1460 case Token::Kind::TK_NEQ:
Ethan Nicholas23463002018-03-28 15:16:15 -04001461 if (right.canCoerceTo(left)) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001462 *outLeftType = &left;
Ethan Nicholas23463002018-03-28 15:16:15 -04001463 *outRightType = &left;
1464 *outResultType = context.fBool_Type.get();
1465 return true;
1466 } if (left.canCoerceTo(right)) {
1467 *outLeftType = &right;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001468 *outRightType = &right;
1469 *outResultType = context.fBool_Type.get();
1470 return true;
1471 }
Ethan Nicholas23463002018-03-28 15:16:15 -04001472 return false;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001473 case Token::Kind::TK_LT: // fall through
1474 case Token::Kind::TK_GT: // fall through
1475 case Token::Kind::TK_LTEQ: // fall through
1476 case Token::Kind::TK_GTEQ:
ethannicholasb3058bd2016-07-01 08:22:01 -07001477 isLogical = true;
ethannicholasea4567c2016-10-17 11:24:37 -07001478 validMatrixOrVectorOp = false;
ethannicholasb3058bd2016-07-01 08:22:01 -07001479 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001480 case Token::Kind::TK_LOGICALOR: // fall through
1481 case Token::Kind::TK_LOGICALAND: // fall through
1482 case Token::Kind::TK_LOGICALXOR: // fall through
1483 case Token::Kind::TK_LOGICALOREQ: // fall through
1484 case Token::Kind::TK_LOGICALANDEQ: // fall through
1485 case Token::Kind::TK_LOGICALXOREQ:
ethannicholasd598f792016-07-25 10:08:54 -07001486 *outLeftType = context.fBool_Type.get();
1487 *outRightType = context.fBool_Type.get();
1488 *outResultType = context.fBool_Type.get();
Ethan Nicholas11d53972016-11-28 11:23:23 -05001489 return left.canCoerceTo(*context.fBool_Type) &&
ethannicholasd598f792016-07-25 10:08:54 -07001490 right.canCoerceTo(*context.fBool_Type);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001491 case Token::Kind::TK_STAREQ:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001492 if (left.kind() == Type::kScalar_Kind) {
1493 *outLeftType = &left;
1494 *outRightType = &left;
1495 *outResultType = &left;
1496 return right.canCoerceTo(left);
1497 }
John Stiles30212b72020-06-11 17:55:07 -04001498 [[fallthrough]];
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001499 case Token::Kind::TK_STAR:
ethannicholasf789b382016-08-03 12:43:36 -07001500 if (is_matrix_multiply(left, right)) {
1501 // determine final component type
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001502 if (determine_binary_type(context, Token::Kind::TK_STAR, left.componentType(),
ethannicholasf789b382016-08-03 12:43:36 -07001503 right.componentType(), outLeftType, outRightType,
1504 outResultType, false)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001505 *outLeftType = &(*outResultType)->toCompound(context, left.columns(),
Brian Salomon23356442018-11-30 15:33:19 -05001506 left.rows());
Ethan Nicholas11d53972016-11-28 11:23:23 -05001507 *outRightType = &(*outResultType)->toCompound(context, right.columns(),
Brian Salomon23356442018-11-30 15:33:19 -05001508 right.rows());
ethannicholasf789b382016-08-03 12:43:36 -07001509 int leftColumns = left.columns();
1510 int leftRows = left.rows();
1511 int rightColumns;
1512 int rightRows;
1513 if (right.kind() == Type::kVector_Kind) {
1514 // matrix * vector treats the vector as a column vector, so we need to
1515 // transpose it
1516 rightColumns = right.rows();
1517 rightRows = right.columns();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001518 SkASSERT(rightColumns == 1);
ethannicholasf789b382016-08-03 12:43:36 -07001519 } else {
1520 rightColumns = right.columns();
1521 rightRows = right.rows();
1522 }
1523 if (rightColumns > 1) {
1524 *outResultType = &(*outResultType)->toCompound(context, rightColumns,
1525 leftRows);
1526 } else {
1527 // result was a column vector, transpose it back to a row
1528 *outResultType = &(*outResultType)->toCompound(context, leftRows,
1529 rightColumns);
1530 }
1531 return leftColumns == rightRows;
1532 } else {
1533 return false;
1534 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001535 }
ethannicholasea4567c2016-10-17 11:24:37 -07001536 isLogical = false;
1537 validMatrixOrVectorOp = true;
1538 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001539 case Token::Kind::TK_PLUSEQ:
1540 case Token::Kind::TK_MINUSEQ:
1541 case Token::Kind::TK_SLASHEQ:
1542 case Token::Kind::TK_PERCENTEQ:
1543 case Token::Kind::TK_SHLEQ:
1544 case Token::Kind::TK_SHREQ:
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001545 if (left.kind() == Type::kScalar_Kind) {
1546 *outLeftType = &left;
1547 *outRightType = &left;
1548 *outResultType = &left;
1549 return right.canCoerceTo(left);
1550 }
John Stiles30212b72020-06-11 17:55:07 -04001551 [[fallthrough]];
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001552 case Token::Kind::TK_PLUS: // fall through
1553 case Token::Kind::TK_MINUS: // fall through
1554 case Token::Kind::TK_SLASH: // fall through
ethannicholasea4567c2016-10-17 11:24:37 -07001555 isLogical = false;
1556 validMatrixOrVectorOp = true;
1557 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001558 case Token::Kind::TK_COMMA:
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001559 *outLeftType = &left;
1560 *outRightType = &right;
1561 *outResultType = &right;
1562 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001563 default:
1564 isLogical = false;
ethannicholasea4567c2016-10-17 11:24:37 -07001565 validMatrixOrVectorOp = false;
ethannicholasb3058bd2016-07-01 08:22:01 -07001566 }
ethannicholasea4567c2016-10-17 11:24:37 -07001567 bool isVectorOrMatrix = left.kind() == Type::kVector_Kind || left.kind() == Type::kMatrix_Kind;
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001568 if (left.kind() == Type::kScalar_Kind && right.kind() == Type::kScalar_Kind &&
1569 right.canCoerceTo(left)) {
1570 if (left.priority() > right.priority()) {
1571 *outLeftType = &left;
1572 *outRightType = &left;
1573 } else {
1574 *outLeftType = &right;
1575 *outRightType = &right;
1576 }
1577 if (isLogical) {
1578 *outResultType = context.fBool_Type.get();
1579 } else {
1580 *outResultType = &left;
1581 }
1582 return true;
1583 }
1584 if (right.canCoerceTo(left) && isVectorOrMatrix && validMatrixOrVectorOp) {
ethannicholasd598f792016-07-25 10:08:54 -07001585 *outLeftType = &left;
1586 *outRightType = &left;
ethannicholasb3058bd2016-07-01 08:22:01 -07001587 if (isLogical) {
ethannicholasd598f792016-07-25 10:08:54 -07001588 *outResultType = context.fBool_Type.get();
ethannicholasb3058bd2016-07-01 08:22:01 -07001589 } else {
ethannicholasd598f792016-07-25 10:08:54 -07001590 *outResultType = &left;
ethannicholasb3058bd2016-07-01 08:22:01 -07001591 }
1592 return true;
1593 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001594 if ((left.kind() == Type::kVector_Kind || left.kind() == Type::kMatrix_Kind) &&
ethannicholasd598f792016-07-25 10:08:54 -07001595 (right.kind() == Type::kScalar_Kind)) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001596 if (determine_binary_type(context, op, left.componentType(), right, outLeftType,
ethannicholasd598f792016-07-25 10:08:54 -07001597 outRightType, outResultType, false)) {
1598 *outLeftType = &(*outLeftType)->toCompound(context, left.columns(), left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001599 if (!isLogical) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001600 *outResultType = &(*outResultType)->toCompound(context, left.columns(),
ethannicholasd598f792016-07-25 10:08:54 -07001601 left.rows());
ethannicholasb3058bd2016-07-01 08:22:01 -07001602 }
1603 return true;
1604 }
1605 return false;
1606 }
1607 if (tryFlipped) {
Ethan Nicholas11d53972016-11-28 11:23:23 -05001608 return determine_binary_type(context, op, right, left, outRightType, outLeftType,
ethannicholasd598f792016-07-25 10:08:54 -07001609 outResultType, false);
ethannicholasb3058bd2016-07-01 08:22:01 -07001610 }
1611 return false;
1612}
1613
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001614static std::unique_ptr<Expression> short_circuit_boolean(const Context& context,
1615 const Expression& left,
1616 Token::Kind op,
1617 const Expression& right) {
1618 SkASSERT(left.fKind == Expression::kBoolLiteral_Kind);
John Stiles403a3632020-08-20 12:11:48 -04001619 bool leftVal = left.as<BoolLiteral>().fValue;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001620 if (op == Token::Kind::TK_LOGICALAND) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001621 // (true && expr) -> (expr) and (false && expr) -> (false)
1622 return leftVal ? right.clone()
1623 : std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, false));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001624 } else if (op == Token::Kind::TK_LOGICALOR) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001625 // (true || expr) -> (true) and (false || expr) -> (expr)
1626 return leftVal ? std::unique_ptr<Expression>(new BoolLiteral(context, left.fOffset, true))
1627 : right.clone();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001628 } else if (op == Token::Kind::TK_LOGICALXOR) {
Noah Lavine334d0ba2019-12-18 23:03:49 -05001629 // (true ^^ expr) -> !(expr) and (false ^^ expr) -> (expr)
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001630 return leftVal ? std::unique_ptr<Expression>(new PrefixExpression(
1631 Token::Kind::TK_LOGICALNOT,
1632 right.clone()))
Noah Lavine334d0ba2019-12-18 23:03:49 -05001633 : right.clone();
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001634 } else {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001635 return nullptr;
1636 }
1637}
1638
ethannicholas08a92112016-11-09 13:26:45 -08001639std::unique_ptr<Expression> IRGenerator::constantFold(const Expression& left,
1640 Token::Kind op,
Ethan Nicholas86a43402017-01-19 13:32:00 -05001641 const Expression& right) const {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001642 // If the left side is a constant boolean literal, the right side does not need to be constant
1643 // for short circuit optimizations to allow the constant to be folded.
Brian Osmanb6b95732020-06-30 11:44:27 -04001644 if (left.fKind == Expression::kBoolLiteral_Kind && !right.isCompileTimeConstant()) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001645 return short_circuit_boolean(fContext, left, op, right);
Brian Osmanb6b95732020-06-30 11:44:27 -04001646 } else if (right.fKind == Expression::kBoolLiteral_Kind && !left.isCompileTimeConstant()) {
Michael Ludwig7b429ae2018-09-06 17:01:38 -04001647 // There aren't side effects in SKSL within expressions, so (left OP right) is equivalent to
1648 // (right OP left) for short-circuit optimizations
1649 return short_circuit_boolean(fContext, right, op, left);
1650 }
1651
1652 // Other than the short-circuit cases above, constant folding requires both sides to be constant
Brian Osmanb6b95732020-06-30 11:44:27 -04001653 if (!left.isCompileTimeConstant() || !right.isCompileTimeConstant()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001654 return nullptr;
1655 }
ethannicholas08a92112016-11-09 13:26:45 -08001656 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
1657 // precision to calculate the results and hope the result makes sense. The plan is to move the
1658 // Skia caps into SkSL, so we have access to all of them including the precisions of the various
1659 // types, which will let us be more intelligent about this.
Ethan Nicholas11d53972016-11-28 11:23:23 -05001660 if (left.fKind == Expression::kBoolLiteral_Kind &&
ethannicholas08a92112016-11-09 13:26:45 -08001661 right.fKind == Expression::kBoolLiteral_Kind) {
John Stiles403a3632020-08-20 12:11:48 -04001662 bool leftVal = left.as<BoolLiteral>().fValue;
1663 bool rightVal = right.as<BoolLiteral>().fValue;
ethannicholas08a92112016-11-09 13:26:45 -08001664 bool result;
1665 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001666 case Token::Kind::TK_LOGICALAND: result = leftVal && rightVal; break;
1667 case Token::Kind::TK_LOGICALOR: result = leftVal || rightVal; break;
1668 case Token::Kind::TK_LOGICALXOR: result = leftVal ^ rightVal; break;
ethannicholas08a92112016-11-09 13:26:45 -08001669 default: return nullptr;
1670 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001671 return std::unique_ptr<Expression>(new BoolLiteral(fContext, left.fOffset, result));
ethannicholas08a92112016-11-09 13:26:45 -08001672 }
John Stilesfbd050b2020-08-03 13:21:46 -04001673 #define RESULT(t, op) std::make_unique<t ## Literal>(fContext, left.fOffset, \
1674 leftVal op rightVal)
1675 #define URESULT(t, op) std::make_unique<t ## Literal>(fContext, left.fOffset, \
1676 (uint32_t) leftVal op \
1677 (uint32_t) rightVal)
ethannicholas08a92112016-11-09 13:26:45 -08001678 if (left.fKind == Expression::kIntLiteral_Kind && right.fKind == Expression::kIntLiteral_Kind) {
John Stiles81365af2020-08-18 09:24:00 -04001679 int64_t leftVal = left.as<IntLiteral>().fValue;
1680 int64_t rightVal = right.as<IntLiteral>().fValue;
ethannicholas08a92112016-11-09 13:26:45 -08001681 switch (op) {
Ethan Nicholas66869e92020-04-30 09:27:54 -04001682 case Token::Kind::TK_PLUS: return URESULT(Int, +);
1683 case Token::Kind::TK_MINUS: return URESULT(Int, -);
1684 case Token::Kind::TK_STAR: return URESULT(Int, *);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001685 case Token::Kind::TK_SLASH:
Ethan Nicholas66869e92020-04-30 09:27:54 -04001686 if (leftVal == std::numeric_limits<int64_t>::min() && rightVal == -1) {
1687 fErrors.error(right.fOffset, "arithmetic overflow");
1688 return nullptr;
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001689 }
Ethan Nicholas66869e92020-04-30 09:27:54 -04001690 if (!rightVal) {
1691 fErrors.error(right.fOffset, "division by zero");
1692 return nullptr;
1693 }
1694 return RESULT(Int, /);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001695 case Token::Kind::TK_PERCENT:
Ethan Nicholas66869e92020-04-30 09:27:54 -04001696 if (leftVal == std::numeric_limits<int64_t>::min() && rightVal == -1) {
1697 fErrors.error(right.fOffset, "arithmetic overflow");
1698 return nullptr;
Ethan Nicholas2503ab62017-01-05 10:44:25 -05001699 }
Ethan Nicholas66869e92020-04-30 09:27:54 -04001700 if (!rightVal) {
1701 fErrors.error(right.fOffset, "division by zero");
1702 return nullptr;
1703 }
1704 return RESULT(Int, %);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001705 case Token::Kind::TK_BITWISEAND: return RESULT(Int, &);
1706 case Token::Kind::TK_BITWISEOR: return RESULT(Int, |);
1707 case Token::Kind::TK_BITWISEXOR: return RESULT(Int, ^);
1708 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
1709 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
1710 case Token::Kind::TK_GT: return RESULT(Bool, >);
1711 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
1712 case Token::Kind::TK_LT: return RESULT(Bool, <);
1713 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
1714 case Token::Kind::TK_SHL:
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001715 if (rightVal >= 0 && rightVal <= 31) {
Ethan Nicholase4489002020-04-29 14:00:14 -04001716 return URESULT(Int, <<);
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001717 }
1718 fErrors.error(right.fOffset, "shift value out of range");
1719 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001720 case Token::Kind::TK_SHR:
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001721 if (rightVal >= 0 && rightVal <= 31) {
Ethan Nicholase4489002020-04-29 14:00:14 -04001722 return URESULT(Int, >>);
Ethan Nicholasfeba68a2019-06-10 09:56:29 -04001723 }
1724 fErrors.error(right.fOffset, "shift value out of range");
1725 return nullptr;
1726
1727 default:
1728 return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001729 }
1730 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05001731 if (left.fKind == Expression::kFloatLiteral_Kind &&
ethannicholas08a92112016-11-09 13:26:45 -08001732 right.fKind == Expression::kFloatLiteral_Kind) {
John Stiles81365af2020-08-18 09:24:00 -04001733 double leftVal = left.as<FloatLiteral>().fValue;
1734 double rightVal = right.as<FloatLiteral>().fValue;
ethannicholas08a92112016-11-09 13:26:45 -08001735 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001736 case Token::Kind::TK_PLUS: return RESULT(Float, +);
1737 case Token::Kind::TK_MINUS: return RESULT(Float, -);
1738 case Token::Kind::TK_STAR: return RESULT(Float, *);
1739 case Token::Kind::TK_SLASH:
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001740 if (rightVal) {
1741 return RESULT(Float, /);
1742 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001743 fErrors.error(right.fOffset, "division by zero");
Ethan Nicholas9a5610e2017-01-03 15:16:29 -05001744 return nullptr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001745 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
1746 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
1747 case Token::Kind::TK_GT: return RESULT(Bool, >);
1748 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
1749 case Token::Kind::TK_LT: return RESULT(Bool, <);
1750 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
1751 default: return nullptr;
ethannicholas08a92112016-11-09 13:26:45 -08001752 }
1753 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05001754 if (left.fType.kind() == Type::kVector_Kind && left.fType.componentType().isFloat() &&
Ethan Nicholascb670962017-04-20 19:31:52 -04001755 left.fType == right.fType) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001756 std::vector<std::unique_ptr<Expression>> args;
Ethan Nicholas4cf5fd92019-06-10 16:15:56 -04001757 #define RETURN_VEC_COMPONENTWISE_RESULT(op) \
1758 for (int i = 0; i < left.fType.columns(); i++) { \
1759 float value = left.getFVecComponent(i) op \
1760 right.getFVecComponent(i); \
1761 args.emplace_back(new FloatLiteral(fContext, -1, value)); \
1762 } \
1763 return std::unique_ptr<Expression>(new Constructor(-1, left.fType, \
Brian Salomon23356442018-11-30 15:33:19 -05001764 std::move(args)))
Ethan Nicholascb670962017-04-20 19:31:52 -04001765 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001766 case Token::Kind::TK_EQEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001767 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001768 left.compareConstant(fContext, right)));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001769 case Token::Kind::TK_NEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001770 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001771 !left.compareConstant(fContext, right)));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001772 case Token::Kind::TK_PLUS: RETURN_VEC_COMPONENTWISE_RESULT(+);
1773 case Token::Kind::TK_MINUS: RETURN_VEC_COMPONENTWISE_RESULT(-);
1774 case Token::Kind::TK_STAR: RETURN_VEC_COMPONENTWISE_RESULT(*);
1775 case Token::Kind::TK_SLASH:
Ethan Nicholas4cf5fd92019-06-10 16:15:56 -04001776 for (int i = 0; i < left.fType.columns(); i++) {
1777 SKSL_FLOAT rvalue = right.getFVecComponent(i);
1778 if (rvalue == 0.0) {
1779 fErrors.error(right.fOffset, "division by zero");
1780 return nullptr;
1781 }
1782 float value = left.getFVecComponent(i) / rvalue;
1783 args.emplace_back(new FloatLiteral(fContext, -1, value));
1784 }
1785 return std::unique_ptr<Expression>(new Constructor(-1, left.fType,
1786 std::move(args)));
Ethan Nicholascb670962017-04-20 19:31:52 -04001787 default: return nullptr;
1788 }
1789 }
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001790 if (left.fType.kind() == Type::kMatrix_Kind &&
1791 right.fType.kind() == Type::kMatrix_Kind &&
1792 left.fKind == right.fKind) {
1793 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001794 case Token::Kind::TK_EQEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001795 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001796 left.compareConstant(fContext, right)));
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001797 case Token::Kind::TK_NEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001798 return std::unique_ptr<Expression>(new BoolLiteral(fContext, -1,
Ethan Nicholas3deaeb22017-04-25 14:42:11 -04001799 !left.compareConstant(fContext, right)));
1800 default:
1801 return nullptr;
1802 }
1803 }
ethannicholas08a92112016-11-09 13:26:45 -08001804 #undef RESULT
1805 return nullptr;
1806}
1807
Ethan Nicholasfc994162019-06-06 10:04:27 -04001808std::unique_ptr<Expression> IRGenerator::convertBinaryExpression(const ASTNode& expression) {
1809 SkASSERT(expression.fKind == ASTNode::Kind::kBinary);
1810 auto iter = expression.begin();
1811 std::unique_ptr<Expression> left = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07001812 if (!left) {
1813 return nullptr;
1814 }
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001815 Token::Kind op = expression.getToken().fKind;
John Stilesd1c4dac2020-08-11 18:50:50 -04001816 std::unique_ptr<Expression> right;
1817 {
1818 // Can't inline the right side of a short-circuiting boolean, because our inlining
1819 // approach runs things out of order.
1820 AutoDisableInline disableInline(this, /*canInline=*/(op != Token::Kind::TK_LOGICALAND &&
1821 op != Token::Kind::TK_LOGICALOR));
1822 right = this->convertExpression(*(iter++));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001823 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001824 if (!right) {
1825 return nullptr;
1826 }
ethannicholasd598f792016-07-25 10:08:54 -07001827 const Type* leftType;
1828 const Type* rightType;
1829 const Type* resultType;
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04001830 const Type* rawLeftType;
1831 if (left->fKind == Expression::kIntLiteral_Kind && right->fType.isInteger()) {
1832 rawLeftType = &right->fType;
1833 } else {
1834 rawLeftType = &left->fType;
1835 }
1836 const Type* rawRightType;
1837 if (right->fKind == Expression::kIntLiteral_Kind && left->fType.isInteger()) {
1838 rawRightType = &left->fType;
1839 } else {
1840 rawRightType = &right->fType;
1841 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001842 if (!determine_binary_type(fContext, op, *rawLeftType, *rawRightType, &leftType, &rightType,
1843 &resultType, !Compiler::IsAssignment(op))) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001844 fErrors.error(expression.fOffset, String("type mismatch: '") +
Ethan Nicholasfc994162019-06-06 10:04:27 -04001845 Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001846 "' cannot operate on '" + left->fType.displayName() +
1847 "', '" + right->fType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001848 return nullptr;
1849 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001850 if (Compiler::IsAssignment(op)) {
Ethan Nicholas4fadce42020-07-30 13:29:30 -04001851 if (!this->setRefKind(*left, op != Token::Kind::TK_EQ
1852 ? VariableReference::kReadWrite_RefKind
1853 : VariableReference::kWrite_RefKind)) {
1854 return nullptr;
1855 }
ethannicholasea4567c2016-10-17 11:24:37 -07001856 }
1857 left = this->coerce(std::move(left), *leftType);
1858 right = this->coerce(std::move(right), *rightType);
1859 if (!left || !right) {
1860 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001861 }
John Stilesa008b0f2020-08-16 08:48:02 -04001862 std::unique_ptr<Expression> result = this->constantFold(*left, op, *right);
ethannicholas08a92112016-11-09 13:26:45 -08001863 if (!result) {
John Stilesd1c4dac2020-08-11 18:50:50 -04001864 result = std::make_unique<BinaryExpression>(expression.fOffset, std::move(left), op,
1865 std::move(right), *resultType);
ethannicholas08a92112016-11-09 13:26:45 -08001866 }
1867 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07001868}
1869
Ethan Nicholasfc994162019-06-06 10:04:27 -04001870std::unique_ptr<Expression> IRGenerator::convertTernaryExpression(const ASTNode& node) {
1871 SkASSERT(node.fKind == ASTNode::Kind::kTernary);
1872 auto iter = node.begin();
1873 std::unique_ptr<Expression> test = this->coerce(this->convertExpression(*(iter++)),
ethannicholasd598f792016-07-25 10:08:54 -07001874 *fContext.fBool_Type);
ethannicholasb3058bd2016-07-01 08:22:01 -07001875 if (!test) {
1876 return nullptr;
1877 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001878 std::unique_ptr<Expression> ifTrue = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07001879 if (!ifTrue) {
1880 return nullptr;
1881 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001882 std::unique_ptr<Expression> ifFalse = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07001883 if (!ifFalse) {
1884 return nullptr;
1885 }
ethannicholasd598f792016-07-25 10:08:54 -07001886 const Type* trueType;
1887 const Type* falseType;
1888 const Type* resultType;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001889 if (!determine_binary_type(fContext, Token::Kind::TK_EQEQ, ifTrue->fType, ifFalse->fType,
1890 &trueType, &falseType, &resultType, true) || trueType != falseType) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04001891 fErrors.error(node.fOffset, "ternary operator result mismatch: '" +
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001892 ifTrue->fType.displayName() + "', '" +
1893 ifFalse->fType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07001894 return nullptr;
1895 }
Brian Osman82329002020-07-21 09:39:27 -04001896 if (trueType->nonnullable() == *fContext.fFragmentProcessor_Type) {
1897 fErrors.error(node.fOffset,
1898 "ternary expression of type '" + trueType->displayName() + "' not allowed");
1899 return nullptr;
1900 }
ethannicholasd598f792016-07-25 10:08:54 -07001901 ifTrue = this->coerce(std::move(ifTrue), *trueType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05001902 if (!ifTrue) {
1903 return nullptr;
1904 }
ethannicholasd598f792016-07-25 10:08:54 -07001905 ifFalse = this->coerce(std::move(ifFalse), *falseType);
Ethan Nicholas2be687a2017-01-03 16:44:39 -05001906 if (!ifFalse) {
1907 return nullptr;
1908 }
ethannicholas08a92112016-11-09 13:26:45 -08001909 if (test->fKind == Expression::kBoolLiteral_Kind) {
1910 // static boolean test, just return one of the branches
John Stiles403a3632020-08-20 12:11:48 -04001911 if (test->as<BoolLiteral>().fValue) {
ethannicholas08a92112016-11-09 13:26:45 -08001912 return ifTrue;
1913 } else {
1914 return ifFalse;
1915 }
1916 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04001917 return std::unique_ptr<Expression>(new TernaryExpression(node.fOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -07001918 std::move(test),
Ethan Nicholas11d53972016-11-28 11:23:23 -05001919 std::move(ifTrue),
ethannicholasb3058bd2016-07-01 08:22:01 -07001920 std::move(ifFalse)));
1921}
1922
John Stilesddefaee2020-08-11 15:13:26 -04001923std::unique_ptr<Expression> IRGenerator::inlineExpression(
1924 int offset,
1925 std::unordered_map<const Variable*, const Variable*>* varMap,
1926 const Expression& expression) {
John Stiles4914cbc2020-08-13 18:00:55 -04001927 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001928 if (e) {
1929 return this->inlineExpression(offset, varMap, *e);
1930 }
John Stiles4914cbc2020-08-13 18:00:55 -04001931 return nullptr;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001932 };
1933 switch (expression.fKind) {
1934 case Expression::kBinary_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04001935 const BinaryExpression& b = expression.as<BinaryExpression>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001936 return std::unique_ptr<Expression>(new BinaryExpression(offset,
1937 expr(b.fLeft),
1938 b.fOperator,
1939 expr(b.fRight),
1940 b.fType));
1941 }
1942 case Expression::kBoolLiteral_Kind:
1943 case Expression::kIntLiteral_Kind:
1944 case Expression::kFloatLiteral_Kind:
1945 case Expression::kNullLiteral_Kind:
1946 return expression.clone();
1947 case Expression::kConstructor_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04001948 const Constructor& c = expression.as<Constructor>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001949 std::vector<std::unique_ptr<Expression>> args;
1950 for (const auto& arg : c.fArguments) {
1951 args.push_back(expr(arg));
1952 }
1953 return std::unique_ptr<Expression>(new Constructor(offset, c.fType, std::move(args)));
1954 }
1955 case Expression::kExternalFunctionCall_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04001956 const ExternalFunctionCall& e = expression.as<ExternalFunctionCall>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001957 std::vector<std::unique_ptr<Expression>> args;
1958 for (const auto& arg : e.fArguments) {
1959 args.push_back(expr(arg));
1960 }
1961 return std::unique_ptr<Expression>(new ExternalFunctionCall(offset, e.fType,
1962 e.fFunction,
1963 std::move(args)));
1964 }
1965 case Expression::kExternalValue_Kind:
1966 return expression.clone();
1967 case Expression::kFieldAccess_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04001968 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001969 return std::unique_ptr<Expression>(new FieldAccess(expr(f.fBase), f.fFieldIndex,
1970 f.fOwnerKind));
1971 }
1972 case Expression::kFunctionCall_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04001973 const FunctionCall& c = expression.as<FunctionCall>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001974 std::vector<std::unique_ptr<Expression>> args;
1975 for (const auto& arg : c.fArguments) {
1976 args.push_back(expr(arg));
1977 }
1978 return std::unique_ptr<Expression>(new FunctionCall(offset, c.fType, c.fFunction,
1979 std::move(args)));
1980 }
1981 case Expression::kIndex_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04001982 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001983 return std::unique_ptr<Expression>(new IndexExpression(fContext, expr(idx.fBase),
1984 expr(idx.fIndex)));
1985 }
1986 case Expression::kPrefix_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04001987 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001988 return std::unique_ptr<Expression>(new PrefixExpression(p.fOperator, expr(p.fOperand)));
1989 }
1990 case Expression::kPostfix_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04001991 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001992 return std::unique_ptr<Expression>(new PostfixExpression(expr(p.fOperand),
1993 p.fOperator));
1994 }
1995 case Expression::kSetting_Kind:
1996 return expression.clone();
1997 case Expression::kSwizzle_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04001998 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001999 return std::unique_ptr<Expression>(new Swizzle(fContext, expr(s.fBase), s.fComponents));
2000 }
2001 case Expression::kTernary_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04002002 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002003 return std::unique_ptr<Expression>(new TernaryExpression(offset, expr(t.fTest),
2004 expr(t.fIfTrue),
2005 expr(t.fIfFalse)));
2006 }
2007 case Expression::kVariableReference_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04002008 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002009 auto found = varMap->find(&v.fVariable);
2010 if (found != varMap->end()) {
2011 return std::unique_ptr<Expression>(new VariableReference(offset,
2012 *found->second,
2013 v.fRefKind));
2014 }
2015 return v.clone();
2016 }
2017 default:
2018 SkASSERT(false);
2019 return nullptr;
2020 }
2021}
2022
John Stiles36374402020-08-13 12:16:44 -04002023static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002024 if (src->kind() == Type::kArray_Kind) {
John Stiles3ae071e2020-08-05 15:29:29 -04002025 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(*src));
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002026 }
2027 return src;
2028}
2029
John Stilesddefaee2020-08-11 15:13:26 -04002030std::unique_ptr<Statement> IRGenerator::inlineStatement(
2031 int offset,
2032 std::unordered_map<const Variable*, const Variable*>* varMap,
John Stilesea9ab822020-08-31 09:55:04 -04002033 SymbolTable* symbolTableForStatement,
John Stilesddefaee2020-08-11 15:13:26 -04002034 const Variable* returnVar,
2035 bool haveEarlyReturns,
2036 const Statement& statement) {
John Stiles4914cbc2020-08-13 18:00:55 -04002037 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002038 if (s) {
John Stilesea9ab822020-08-31 09:55:04 -04002039 return this->inlineStatement(offset, varMap, symbolTableForStatement, returnVar,
2040 haveEarlyReturns, *s);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002041 }
John Stiles4914cbc2020-08-13 18:00:55 -04002042 return nullptr;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002043 };
2044 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
2045 std::vector<std::unique_ptr<Statement>> result;
2046 for (const auto& s : ss) {
2047 result.push_back(stmt(s));
2048 }
2049 return result;
2050 };
John Stiles4914cbc2020-08-13 18:00:55 -04002051 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002052 if (e) {
2053 return this->inlineExpression(offset, varMap, *e);
2054 }
John Stiles4914cbc2020-08-13 18:00:55 -04002055 return nullptr;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002056 };
2057 switch (statement.fKind) {
2058 case Statement::kBlock_Kind: {
John Stiles26f98502020-08-18 09:30:51 -04002059 const Block& b = statement.as<Block>();
John Stilesfbd050b2020-08-03 13:21:46 -04002060 return std::make_unique<Block>(offset, stmts(b.fStatements), b.fSymbols, b.fIsScope);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002061 }
2062
2063 case Statement::kBreak_Kind:
2064 case Statement::kContinue_Kind:
2065 case Statement::kDiscard_Kind:
2066 return statement.clone();
2067
2068 case Statement::kDo_Kind: {
John Stiles26f98502020-08-18 09:30:51 -04002069 const DoStatement& d = statement.as<DoStatement>();
John Stilesfbd050b2020-08-03 13:21:46 -04002070 return std::make_unique<DoStatement>(offset, stmt(d.fStatement), expr(d.fTest));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002071 }
2072 case Statement::kExpression_Kind: {
John Stiles26f98502020-08-18 09:30:51 -04002073 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stilesfbd050b2020-08-03 13:21:46 -04002074 return std::make_unique<ExpressionStatement>(expr(e.fExpression));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002075 }
2076 case Statement::kFor_Kind: {
John Stiles26f98502020-08-18 09:30:51 -04002077 const ForStatement& f = statement.as<ForStatement>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002078 // need to ensure initializer is evaluated first so that we've already remapped its
2079 // declarations by the time we evaluate test & next
2080 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
John Stilesfbd050b2020-08-03 13:21:46 -04002081 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
2082 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002083 }
2084 case Statement::kIf_Kind: {
John Stiles26f98502020-08-18 09:30:51 -04002085 const IfStatement& i = statement.as<IfStatement>();
John Stilesfbd050b2020-08-03 13:21:46 -04002086 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
2087 stmt(i.fIfTrue), stmt(i.fIfFalse));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002088 }
2089 case Statement::kNop_Kind:
2090 return statement.clone();
2091 case Statement::kReturn_Kind: {
John Stiles26f98502020-08-18 09:30:51 -04002092 const ReturnStatement& r = statement.as<ReturnStatement>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002093 if (r.fExpression) {
John Stiles48bdf6d2020-08-13 18:02:22 -04002094 auto assignment = std::make_unique<ExpressionStatement>(
John Stilesfbd050b2020-08-03 13:21:46 -04002095 std::make_unique<BinaryExpression>(
2096 offset,
2097 std::make_unique<VariableReference>(offset, *returnVar,
2098 VariableReference::kWrite_RefKind),
2099 Token::Kind::TK_EQ,
2100 expr(r.fExpression),
2101 returnVar->fType));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002102 if (haveEarlyReturns) {
2103 std::vector<std::unique_ptr<Statement>> block;
2104 block.push_back(std::move(assignment));
2105 block.emplace_back(new BreakStatement(offset));
John Stiles48bdf6d2020-08-13 18:02:22 -04002106 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
2107 /*isScope=*/true);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002108 } else {
John Stiles48bdf6d2020-08-13 18:02:22 -04002109 return std::move(assignment);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002110 }
2111 } else {
2112 if (haveEarlyReturns) {
John Stilesfbd050b2020-08-03 13:21:46 -04002113 return std::make_unique<BreakStatement>(offset);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002114 } else {
John Stilesfbd050b2020-08-03 13:21:46 -04002115 return std::make_unique<Nop>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002116 }
2117 }
2118 }
2119 case Statement::kSwitch_Kind: {
John Stiles26f98502020-08-18 09:30:51 -04002120 const SwitchStatement& ss = statement.as<SwitchStatement>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002121 std::vector<std::unique_ptr<SwitchCase>> cases;
2122 for (const auto& sc : ss.fCases) {
2123 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
2124 stmts(sc->fStatements)));
2125 }
John Stilesfbd050b2020-08-03 13:21:46 -04002126 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
2127 std::move(cases), ss.fSymbols);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002128 }
2129 case Statement::kVarDeclaration_Kind: {
John Stiles26f98502020-08-18 09:30:51 -04002130 const VarDeclaration& decl = statement.as<VarDeclaration>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002131 std::vector<std::unique_ptr<Expression>> sizes;
2132 for (const auto& size : decl.fSizes) {
2133 sizes.push_back(expr(size));
2134 }
2135 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
2136 const Variable* old = decl.fVar;
Ethan Nicholase8ad02c2020-06-03 16:58:20 -04002137 // need to copy the var name in case the originating function is discarded and we lose
2138 // its symbols
2139 std::unique_ptr<String> name(new String(old->fName));
John Stilesea9ab822020-08-31 09:55:04 -04002140 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
2141 const Type* typePtr = copy_if_needed(&old->fType, *symbolTableForStatement);
2142 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
John Stiles3ae071e2020-08-05 15:29:29 -04002143 std::make_unique<Variable>(offset,
2144 old->fModifiers,
2145 namePtr->c_str(),
2146 *typePtr,
2147 old->fStorage,
2148 initialValue.get()));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002149 (*varMap)[old] = clone;
John Stilesfbd050b2020-08-03 13:21:46 -04002150 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
2151 std::move(initialValue));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002152 }
2153 case Statement::kVarDeclarations_Kind: {
John Stiles26f98502020-08-18 09:30:51 -04002154 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002155 std::vector<std::unique_ptr<VarDeclaration>> vars;
2156 for (const auto& var : decls.fVars) {
John Stiles26f98502020-08-18 09:30:51 -04002157 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002158 }
John Stilesea9ab822020-08-31 09:55:04 -04002159 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002160 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
John Stilesfbd050b2020-08-03 13:21:46 -04002161 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002162 }
2163 case Statement::kWhile_Kind: {
John Stiles26f98502020-08-18 09:30:51 -04002164 const WhileStatement& w = statement.as<WhileStatement>();
John Stilesfbd050b2020-08-03 13:21:46 -04002165 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002166 }
2167 default:
2168 SkASSERT(false);
2169 return nullptr;
2170 }
2171}
2172
John Stiles318ad4b2020-08-27 10:58:36 -04002173static int count_all_returns(const FunctionDefinition& funcDef) {
John Stilesf1bc8282020-08-27 15:01:44 -04002174 class CountAllReturns : public ProgramVisitor {
2175 public:
2176 CountAllReturns(const FunctionDefinition& funcDef) {
2177 this->visitProgramElement(funcDef);
2178 }
2179
2180 bool visitStatement(const Statement& stmt) override {
2181 switch (stmt.fKind) {
2182 case Statement::kReturn_Kind:
2183 ++fNumReturns;
2184 [[fallthrough]];
2185
2186 default:
2187 return this->INHERITED::visitStatement(stmt);
2188 }
2189 }
2190
2191 int fNumReturns = 0;
2192 using INHERITED = ProgramVisitor;
2193 };
2194
John Stilesee58da92020-08-27 15:02:05 -04002195 return CountAllReturns{funcDef}.fNumReturns;
John Stiles318ad4b2020-08-27 10:58:36 -04002196}
2197
2198static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
John Stilesf1bc8282020-08-27 15:01:44 -04002199 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
2200 public:
2201 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
2202 this->visitProgramElement(funcDef);
2203 }
2204
2205 bool visitStatement(const Statement& stmt) override {
2206 switch (stmt.fKind) {
2207 case Statement::kBlock_Kind: {
2208 // Check only the last statement of a block.
2209 const auto& blockStmts = stmt.as<Block>().fStatements;
2210 return (blockStmts.size() > 0) ? this->visitStatement(*blockStmts.back())
2211 : false;
2212 }
2213 case Statement::kSwitch_Kind:
2214 case Statement::kWhile_Kind:
2215 case Statement::kDo_Kind:
2216 case Statement::kFor_Kind:
2217 // Don't introspect switches or loop structures at all.
2218 return false;
2219
2220 case Statement::kReturn_Kind:
2221 ++fNumReturns;
2222 [[fallthrough]];
2223
2224 default:
2225 return this->INHERITED::visitStatement(stmt);
2226 }
2227 }
2228
2229 int fNumReturns = 0;
2230 using INHERITED = ProgramVisitor;
2231 };
2232
John Stilesee58da92020-08-27 15:02:05 -04002233 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
John Stiles318ad4b2020-08-27 10:58:36 -04002234}
2235
2236static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
John Stilesf1bc8282020-08-27 15:01:44 -04002237 class CountReturnsInBreakableConstructs : public ProgramVisitor {
2238 public:
2239 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
2240 this->visitProgramElement(funcDef);
2241 }
2242
2243 bool visitStatement(const Statement& stmt) override {
2244 switch (stmt.fKind) {
2245 case Statement::kSwitch_Kind:
2246 case Statement::kWhile_Kind:
2247 case Statement::kDo_Kind:
2248 case Statement::kFor_Kind: {
2249 ++fInsideBreakableConstruct;
2250 bool result = this->INHERITED::visitStatement(stmt);
2251 --fInsideBreakableConstruct;
2252 return result;
2253 }
2254
2255 case Statement::kReturn_Kind:
2256 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
2257 [[fallthrough]];
2258
2259 default:
2260 return this->INHERITED::visitStatement(stmt);
2261 }
2262 }
2263
2264 int fNumReturns = 0;
2265 int fInsideBreakableConstruct = 0;
2266 using INHERITED = ProgramVisitor;
2267 };
2268
John Stilesee58da92020-08-27 15:02:05 -04002269 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
John Stiles318ad4b2020-08-27 10:58:36 -04002270}
2271
2272static bool has_early_return(const FunctionDefinition& funcDef) {
2273 int returnCount = count_all_returns(funcDef);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002274 if (returnCount == 0) {
2275 return false;
2276 }
John Stiles20641112020-08-25 17:20:33 -04002277
John Stiles318ad4b2020-08-27 10:58:36 -04002278 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
2279 return returnCount > returnsAtEndOfControlFlow;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002280}
2281
John Stilesea9ab822020-08-31 09:55:04 -04002282std::unique_ptr<Expression> IRGenerator::inlineCall(std::unique_ptr<FunctionCall> call,
2283 SymbolTable* symbolTableForCall) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002284 // Inlining is more complicated here than in a typical compiler, because we have to have a
2285 // high-level IR and can't just drop statements into the middle of an expression or even use
2286 // gotos.
2287 //
2288 // Since we can't insert statements into an expression, we run the inline function as extra
2289 // statements before the statement we're currently processing, relying on a lack of execution
2290 // order guarantees. Since we can't use gotos (which are normally used to replace return
2291 // statements), we wrap the whole function in a loop and use break statements to jump to the
2292 // end.
John Stilesea9ab822020-08-31 09:55:04 -04002293 SkASSERT(call);
2294 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
2295
2296 int offset = call->fOffset;
2297 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
2298 const FunctionDefinition& function = *call->fFunction.fDefinition;
Brian Osmanb5f0f522020-07-23 13:28:14 -04002299
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002300 // Use unique variable names based on the function signature. Otherwise there are situations in
2301 // which an inlined function is later inlined into another function, and we end up with
2302 // duplicate names like 'inlineResult0' because the counter was reset. (skbug.com/10526)
2303 String raw = function.fDeclaration.description();
2304 String inlineSalt;
2305 for (size_t i = 0; i < raw.length(); ++i) {
2306 char c = raw[i];
2307 if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
2308 c == '_') {
2309 inlineSalt += c;
2310 }
Brian Osmanb5f0f522020-07-23 13:28:14 -04002311 }
2312
John Stiles09dac442020-08-28 10:01:14 -04002313 auto makeInlineVar = [&](const String& name, const Type& type, Modifiers modifiers,
2314 std::unique_ptr<Expression>* initialValue) -> const Variable* {
2315 // Add our new variable's name to the symbol table.
John Stilesea9ab822020-08-31 09:55:04 -04002316 const String* namePtr =
2317 symbolTableForCall->takeOwnershipOfString(std::make_unique<String>(name));
John Stiles09dac442020-08-28 10:01:14 -04002318 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
2319
2320 // Add our new variable to the symbol table.
2321 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
2322 Variable::kLocal_Storage, initialValue->get());
John Stilesea9ab822020-08-31 09:55:04 -04002323 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
John Stiles09dac442020-08-28 10:01:14 -04002324
2325 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
2326 // initial value).
2327 std::vector<std::unique_ptr<VarDeclaration>> variables;
2328 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
2329 variables.push_back(std::make_unique<VarDeclaration>(
2330 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
2331 (*initialValue)->clone()));
2332 } else {
2333 variables.push_back(std::make_unique<VarDeclaration>(
2334 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
2335 std::move(*initialValue)));
2336 }
2337
2338 // Add the new variable-declaration statement to our block of extra statements.
2339 fExtraStatements.push_back(std::make_unique<VarDeclarationsStatement>(
2340 std::make_unique<VarDeclarations>(offset, &type, std::move(variables))));
2341
2342 return variableSymbol;
2343 };
2344
2345 // Create a variable to hold the result in the extra statements (excepting void).
John Stiles311dd9d2020-08-13 17:09:29 -04002346 const Variable* resultVar = nullptr;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002347 if (function.fDeclaration.fReturnType != *fContext.fVoid_Type) {
Michael Ludwig9861b7c2020-06-23 18:37:17 -04002348 int varIndex = fInlineVarCounter++;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002349
John Stiles09dac442020-08-28 10:01:14 -04002350 std::unique_ptr<Expression> noInitialValue;
2351 resultVar = makeInlineVar(String::printf("_inlineResult%s%d", inlineSalt.c_str(), varIndex),
2352 function.fDeclaration.fReturnType, Modifiers{}, &noInitialValue);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002353 }
John Stiles09dac442020-08-28 10:01:14 -04002354
2355 // Create variables in the extra statements to hold the arguments, and assign the arguments to
2356 // them.
John Stilesddefaee2020-08-11 15:13:26 -04002357 std::unordered_map<const Variable*, const Variable*> varMap;
Michael Ludwig9861b7c2020-06-23 18:37:17 -04002358 int argIndex = fInlineVarCounter++;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002359 for (int i = 0; i < (int) arguments.size(); ++i) {
John Stiles09dac442020-08-28 10:01:14 -04002360 const Variable* param = function.fDeclaration.fParameters[i];
2361
Ethan Nicholas765d2fe2020-08-26 08:29:55 -04002362 if (arguments[i]->fKind == Expression::kVariableReference_Kind) {
John Stiles09dac442020-08-28 10:01:14 -04002363 // The argument is just a variable, so we only need to copy it if it's an out parameter
2364 // or it's written to within the function.
Ethan Nicholas765d2fe2020-08-26 08:29:55 -04002365 if ((param->fModifiers.fFlags & Modifiers::kOut_Flag) ||
2366 !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
John Stiles09dac442020-08-28 10:01:14 -04002367 varMap[param] = &arguments[i]->as<VariableReference>().fVariable;
Ethan Nicholas765d2fe2020-08-26 08:29:55 -04002368 continue;
2369 }
2370 }
John Stiles09dac442020-08-28 10:01:14 -04002371
2372 varMap[param] = makeInlineVar(
2373 String::printf("_inlineArg%s%d_%d", inlineSalt.c_str(), argIndex, i),
2374 arguments[i]->fType, param->fModifiers, &arguments[i]);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002375 }
John Stiles09dac442020-08-28 10:01:14 -04002376
John Stiles403a3632020-08-20 12:11:48 -04002377 const Block& body = function.fBody->as<Block>();
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002378 bool hasEarlyReturn = has_early_return(function);
John Stiles09dac442020-08-28 10:01:14 -04002379 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
2380 inlineBlock->fStatements.reserve(body.fStatements.size());
2381 for (const std::unique_ptr<Statement>& stmt : body.fStatements) {
John Stilesea9ab822020-08-31 09:55:04 -04002382 inlineBlock->fStatements.push_back(this->inlineStatement(
2383 offset, &varMap, symbolTableForCall, resultVar, hasEarlyReturn, *stmt));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002384 }
2385 if (hasEarlyReturn) {
2386 // Since we output to backends that don't have a goto statement (which would normally be
2387 // used to perform an early return), we fake it by wrapping the function in a
2388 // do { } while (false); and then use break statements to jump to the end in order to
2389 // emulate a goto.
John Stiles09dac442020-08-28 10:01:14 -04002390 fExtraStatements.push_back(std::make_unique<DoStatement>(
2391 /*offset=*/-1,
2392 std::move(inlineBlock),
2393 std::make_unique<BoolLiteral>(fContext, offset, /*value=*/false)));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002394 } else {
2395 // No early returns, so we can just dump the code in. We need to use a block so we don't get
2396 // name conflicts with locals.
John Stiles09dac442020-08-28 10:01:14 -04002397 fExtraStatements.push_back(std::move(inlineBlock));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002398 }
John Stiles09dac442020-08-28 10:01:14 -04002399
2400 // Copy the values of `out` parameters into their destinations.
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002401 for (size_t i = 0; i < arguments.size(); ++i) {
2402 const Variable* p = function.fDeclaration.fParameters[i];
2403 if (p->fModifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholas765d2fe2020-08-26 08:29:55 -04002404 SkASSERT(varMap.find(p) != varMap.end());
2405 if (arguments[i]->fKind == Expression::kVariableReference_Kind &&
2406 &arguments[i]->as<VariableReference>().fVariable == varMap[p]) {
2407 // we didn't create a temporary for this parameter, so there's nothing to copy back
2408 // out
2409 continue;
2410 }
John Stiles09dac442020-08-28 10:01:14 -04002411 auto varRef = std::make_unique<VariableReference>(offset, *varMap[p]);
2412 fExtraStatements.push_back(std::make_unique<ExpressionStatement>(
2413 std::make_unique<BinaryExpression>(offset,
2414 arguments[i]->clone(),
2415 Token::Kind::TK_EQ,
2416 std::move(varRef),
2417 arguments[i]->fType)));
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002418 }
2419 }
John Stiles09dac442020-08-28 10:01:14 -04002420
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002421 if (function.fDeclaration.fReturnType != *fContext.fVoid_Type) {
John Stiles09dac442020-08-28 10:01:14 -04002422 // Return a reference to the result variable as our replacement expression.
2423 return std::make_unique<VariableReference>(offset, *resultVar);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002424 } else {
John Stiles09dac442020-08-28 10:01:14 -04002425 // It's a void function, so it doesn't actually result in anything, but we have to return
2426 // something non-null as a standin.
2427 return std::make_unique<BoolLiteral>(fContext, /*offset=*/-1, /*value=*/false);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002428 }
2429}
2430
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002431void IRGenerator::copyIntrinsicIfNeeded(const FunctionDeclaration& function) {
2432 auto found = fIntrinsics->find(function.description());
John Stiles810c8cf2020-08-26 19:46:27 -04002433 if (found != fIntrinsics->end() && !found->second.fAlreadyIncluded) {
2434 found->second.fAlreadyIncluded = true;
2435 FunctionDefinition& original = found->second.fIntrinsic->as<FunctionDefinition>();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002436 for (const FunctionDeclaration* f : original.fReferencedIntrinsics) {
2437 this->copyIntrinsicIfNeeded(*f);
2438 }
2439 fProgramElements->push_back(original.clone());
2440 }
2441}
2442
John Stilesea9ab822020-08-31 09:55:04 -04002443bool IRGenerator::isSafeToInline(const FunctionCall& functionCall, int inlineThreshold) {
John Stiles8c91c932020-08-13 14:35:35 -04002444 if (!fCanInline) {
2445 // Inlining has been explicitly disabled by the IR generator.
2446 return false;
2447 }
John Stilesea9ab822020-08-31 09:55:04 -04002448 if (functionCall.fFunction.fDefinition == nullptr) {
2449 // Can't inline something if we don't actually have its definition.
John Stiles8c91c932020-08-13 14:35:35 -04002450 return false;
2451 }
John Stilesea9ab822020-08-31 09:55:04 -04002452 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
2453 if (inlineThreshold < INT_MAX) {
2454 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
2455 Analysis::NodeCount(functionDef) >= inlineThreshold) {
2456 // The function exceeds our maximum inline size and is not flagged 'inline'.
2457 return false;
2458 }
2459 }
John Stiles8c91c932020-08-13 14:35:35 -04002460 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
2461 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
2462 // can't inline functions that have an early return.
John Stiles318ad4b2020-08-27 10:58:36 -04002463 bool hasEarlyReturn = has_early_return(functionDef);
2464
2465 // If we didn't detect an early return, there shouldn't be any returns in breakable
2466 // constructs either.
2467 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
2468 return !hasEarlyReturn;
John Stiles8c91c932020-08-13 14:35:35 -04002469 }
2470 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
2471 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
John Stiles318ad4b2020-08-27 10:58:36 -04002472 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
2473
2474 // If we detected returns in breakable constructs, we should also detect an early return.
2475 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
2476 return !hasReturnInBreakableConstruct;
John Stiles8c91c932020-08-13 14:35:35 -04002477}
2478
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002479std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05002480 const FunctionDeclaration& function,
ethannicholasd598f792016-07-25 10:08:54 -07002481 std::vector<std::unique_ptr<Expression>> arguments) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05002482 if (function.fBuiltin) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -04002483 if (function.fDefinition) {
2484 fReferencedIntrinsics.insert(&function);
2485 }
2486 if (!fIsBuiltinCode) {
2487 this->copyIntrinsicIfNeeded(function);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05002488 }
2489 }
ethannicholasd598f792016-07-25 10:08:54 -07002490 if (function.fParameters.size() != arguments.size()) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002491 String msg = "call to '" + function.fName + "' expected " +
Ethan Nicholas11d53972016-11-28 11:23:23 -05002492 to_string((uint64_t) function.fParameters.size()) +
ethannicholasb3058bd2016-07-01 08:22:01 -07002493 " argument";
ethannicholasd598f792016-07-25 10:08:54 -07002494 if (function.fParameters.size() != 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002495 msg += "s";
2496 }
ethannicholas5961bc92016-10-12 06:39:56 -07002497 msg += ", but found " + to_string((uint64_t) arguments.size());
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002498 fErrors.error(offset, msg);
ethannicholasb3058bd2016-07-01 08:22:01 -07002499 return nullptr;
2500 }
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002501 if (fKind == Program::kPipelineStage_Kind && !function.fDefinition && !function.fBuiltin) {
Brian Osman5f6b41e2020-03-09 11:53:24 -04002502 String msg = "call to undefined function '" + function.fName + "'";
2503 fErrors.error(offset, msg);
2504 return nullptr;
2505 }
ethannicholas471e8942016-10-28 09:02:46 -07002506 std::vector<const Type*> types;
2507 const Type* returnType;
2508 if (!function.determineFinalTypes(arguments, &types, &returnType)) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002509 String msg = "no match for " + function.fName + "(";
2510 String separator;
ethannicholas471e8942016-10-28 09:02:46 -07002511 for (size_t i = 0; i < arguments.size(); i++) {
2512 msg += separator;
2513 separator = ", ";
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002514 msg += arguments[i]->fType.displayName();
ethannicholas471e8942016-10-28 09:02:46 -07002515 }
2516 msg += ")";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002517 fErrors.error(offset, msg);
ethannicholas471e8942016-10-28 09:02:46 -07002518 return nullptr;
2519 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002520 for (size_t i = 0; i < arguments.size(); i++) {
ethannicholas471e8942016-10-28 09:02:46 -07002521 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
ethannicholasea4567c2016-10-17 11:24:37 -07002522 if (!arguments[i]) {
2523 return nullptr;
2524 }
ethannicholasd598f792016-07-25 10:08:54 -07002525 if (arguments[i] && (function.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag)) {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -04002526 this->setRefKind(*arguments[i],
2527 function.fParameters[i]->fModifiers.fFlags & Modifiers::kIn_Flag ?
2528 VariableReference::kReadWrite_RefKind :
2529 VariableReference::kPointer_RefKind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002530 }
2531 }
John Stilesea9ab822020-08-31 09:55:04 -04002532
2533 auto funcCall = std::make_unique<FunctionCall>(offset, *returnType, function,
2534 std::move(arguments));
2535 if (this->isSafeToInline(*funcCall, fSettings->fInlineThreshold)) {
2536 return this->inlineCall(std::move(funcCall), fSymbolTable.get());
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002537 }
John Stiles8c91c932020-08-13 14:35:35 -04002538
John Stilesea9ab822020-08-31 09:55:04 -04002539 return std::move(funcCall);
ethannicholasb3058bd2016-07-01 08:22:01 -07002540}
2541
2542/**
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002543 * Determines the cost of coercing the arguments of a function to the required types. Cost has no
2544 * particular meaning other than "lower costs are preferred". Returns INT_MAX if the call is not
2545 * valid.
ethannicholasb3058bd2016-07-01 08:22:01 -07002546 */
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002547int IRGenerator::callCost(const FunctionDeclaration& function,
2548 const std::vector<std::unique_ptr<Expression>>& arguments) {
ethannicholasd598f792016-07-25 10:08:54 -07002549 if (function.fParameters.size() != arguments.size()) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002550 return INT_MAX;
ethannicholasb3058bd2016-07-01 08:22:01 -07002551 }
2552 int total = 0;
ethannicholas471e8942016-10-28 09:02:46 -07002553 std::vector<const Type*> types;
2554 const Type* ignored;
2555 if (!function.determineFinalTypes(arguments, &types, &ignored)) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002556 return INT_MAX;
ethannicholas471e8942016-10-28 09:02:46 -07002557 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002558 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002559 int cost = arguments[i]->coercionCost(*types[i]);
2560 if (cost != INT_MAX) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002561 total += cost;
2562 } else {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002563 return INT_MAX;
ethannicholasb3058bd2016-07-01 08:22:01 -07002564 }
2565 }
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002566 return total;
ethannicholasb3058bd2016-07-01 08:22:01 -07002567}
2568
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002569std::unique_ptr<Expression> IRGenerator::call(int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05002570 std::unique_ptr<Expression> functionValue,
ethannicholasb3058bd2016-07-01 08:22:01 -07002571 std::vector<std::unique_ptr<Expression>> arguments) {
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002572 switch (functionValue->fKind) {
2573 case Expression::kTypeReference_Kind:
2574 return this->convertConstructor(offset,
John Stiles403a3632020-08-20 12:11:48 -04002575 functionValue->as<TypeReference>().fValue,
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002576 std::move(arguments));
2577 case Expression::kExternalValue_Kind: {
John Stiles17c5b702020-08-18 10:40:03 -04002578 const ExternalValue* v = functionValue->as<ExternalValueReference>().fValue;
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002579 if (!v->canCall()) {
2580 fErrors.error(offset, "this external value is not a function");
2581 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002582 }
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002583 int count = v->callParameterCount();
2584 if (count != (int) arguments.size()) {
2585 fErrors.error(offset, "external function expected " + to_string(count) +
2586 " arguments, but found " + to_string((int) arguments.size()));
2587 return nullptr;
2588 }
2589 static constexpr int PARAMETER_MAX = 16;
2590 SkASSERT(count < PARAMETER_MAX);
2591 const Type* types[PARAMETER_MAX];
2592 v->getCallParameterTypes(types);
2593 for (int i = 0; i < count; ++i) {
2594 arguments[i] = this->coerce(std::move(arguments[i]), *types[i]);
2595 if (!arguments[i]) {
2596 return nullptr;
2597 }
2598 }
2599 return std::unique_ptr<Expression>(new ExternalFunctionCall(offset, v->callReturnType(),
2600 v, std::move(arguments)));
ethannicholasb3058bd2016-07-01 08:22:01 -07002601 }
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002602 case Expression::kFunctionReference_Kind: {
John Stilesce591b72020-08-27 11:47:30 -04002603 const FunctionReference& ref = functionValue->as<FunctionReference>();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002604 int bestCost = INT_MAX;
2605 const FunctionDeclaration* best = nullptr;
John Stilesce591b72020-08-27 11:47:30 -04002606 if (ref.fFunctions.size() > 1) {
2607 for (const auto& f : ref.fFunctions) {
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002608 int cost = this->callCost(*f, arguments);
2609 if (cost < bestCost) {
2610 bestCost = cost;
2611 best = f;
2612 }
2613 }
2614 if (best) {
2615 return this->call(offset, *best, std::move(arguments));
2616 }
John Stilesce591b72020-08-27 11:47:30 -04002617 String msg = "no match for " + ref.fFunctions[0]->fName + "(";
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002618 String separator;
2619 for (size_t i = 0; i < arguments.size(); i++) {
2620 msg += separator;
2621 separator = ", ";
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002622 msg += arguments[i]->fType.displayName();
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002623 }
2624 msg += ")";
2625 fErrors.error(offset, msg);
2626 return nullptr;
2627 }
John Stilesce591b72020-08-27 11:47:30 -04002628 return this->call(offset, *ref.fFunctions[0], std::move(arguments));
ethannicholasb3058bd2016-07-01 08:22:01 -07002629 }
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002630 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002631 fErrors.error(offset, "not a function");
Ethan Nicholas9e6a3932019-05-17 16:31:21 -04002632 return nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07002633 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002634}
2635
Ethan Nicholas84645e32017-02-09 13:57:14 -05002636std::unique_ptr<Expression> IRGenerator::convertNumberConstructor(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002637 int offset,
Ethan Nicholas11d53972016-11-28 11:23:23 -05002638 const Type& type,
ethannicholasb3058bd2016-07-01 08:22:01 -07002639 std::vector<std::unique_ptr<Expression>> args) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04002640 SkASSERT(type.isNumber());
Ethan Nicholas84645e32017-02-09 13:57:14 -05002641 if (args.size() != 1) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002642 fErrors.error(offset, "invalid arguments to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002643 "' constructor, (expected exactly 1 argument, but found " +
2644 to_string((uint64_t) args.size()) + ")");
ethannicholasb3058bd2016-07-01 08:22:01 -07002645 return nullptr;
2646 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -04002647 if (type == args[0]->fType) {
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002648 return std::move(args[0]);
2649 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -04002650 if (type.isFloat() && args.size() == 1 && args[0]->fKind == Expression::kFloatLiteral_Kind) {
John Stiles81365af2020-08-18 09:24:00 -04002651 double value = args[0]->as<FloatLiteral>().fValue;
Ethan Nicholas00543112018-07-31 09:44:36 -04002652 return std::unique_ptr<Expression>(new FloatLiteral(offset, value, &type));
Ethan Nicholasdcba08e2017-08-02 10:52:54 -04002653 }
2654 if (type.isFloat() && args.size() == 1 && args[0]->fKind == Expression::kIntLiteral_Kind) {
John Stiles81365af2020-08-18 09:24:00 -04002655 int64_t value = args[0]->as<IntLiteral>().fValue;
Ethan Nicholas00543112018-07-31 09:44:36 -04002656 return std::unique_ptr<Expression>(new FloatLiteral(offset, (double) value, &type));
ethannicholasb3058bd2016-07-01 08:22:01 -07002657 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05002658 if (args[0]->fKind == Expression::kIntLiteral_Kind && (type == *fContext.fInt_Type ||
2659 type == *fContext.fUInt_Type)) {
Ethan Nicholas00543112018-07-31 09:44:36 -04002660 return std::unique_ptr<Expression>(new IntLiteral(offset,
John Stiles81365af2020-08-18 09:24:00 -04002661 args[0]->as<IntLiteral>().fValue,
Ethan Nicholas84645e32017-02-09 13:57:14 -05002662 &type));
ethannicholasb3058bd2016-07-01 08:22:01 -07002663 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05002664 if (args[0]->fType == *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002665 std::unique_ptr<IntLiteral> zero(new IntLiteral(fContext, offset, 0));
2666 std::unique_ptr<IntLiteral> one(new IntLiteral(fContext, offset, 1));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002667 return std::unique_ptr<Expression>(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002668 new TernaryExpression(offset, std::move(args[0]),
Ethan Nicholas84645e32017-02-09 13:57:14 -05002669 this->coerce(std::move(one), type),
2670 this->coerce(std::move(zero),
2671 type)));
2672 }
2673 if (!args[0]->fType.isNumber()) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002674 fErrors.error(offset, "invalid argument to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002675 "' constructor (expected a number or bool, but found '" +
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002676 args[0]->fType.displayName() + "')");
Ethan Nicholas84645e32017-02-09 13:57:14 -05002677 return nullptr;
2678 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002679 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002680}
2681
John Stiles36374402020-08-13 12:16:44 -04002682static int component_count(const Type& type) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002683 switch (type.kind()) {
2684 case Type::kVector_Kind:
2685 return type.columns();
2686 case Type::kMatrix_Kind:
2687 return type.columns() * type.rows();
2688 default:
2689 return 1;
2690 }
2691}
2692
2693std::unique_ptr<Expression> IRGenerator::convertCompoundConstructor(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002694 int offset,
Ethan Nicholas84645e32017-02-09 13:57:14 -05002695 const Type& type,
2696 std::vector<std::unique_ptr<Expression>> args) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04002697 SkASSERT(type.kind() == Type::kVector_Kind || type.kind() == Type::kMatrix_Kind);
Ethan Nicholas84645e32017-02-09 13:57:14 -05002698 if (type.kind() == Type::kMatrix_Kind && args.size() == 1 &&
2699 args[0]->fType.kind() == Type::kMatrix_Kind) {
2700 // matrix from matrix is always legal
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002701 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002702 }
2703 int actual = 0;
2704 int expected = type.rows() * type.columns();
2705 if (args.size() != 1 || expected != component_count(args[0]->fType) ||
2706 type.componentType().isNumber() != args[0]->fType.componentType().isNumber()) {
ethannicholas5961bc92016-10-12 06:39:56 -07002707 for (size_t i = 0; i < args.size(); i++) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002708 if (args[i]->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002709 if (type.componentType().isNumber() !=
2710 args[i]->fType.componentType().isNumber()) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002711 fErrors.error(offset, "'" + args[i]->fType.displayName() + "' is not a valid "
2712 "parameter to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002713 "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002714 return nullptr;
2715 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05002716 actual += args[i]->fType.columns();
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002717 } else if (args[i]->fType.kind() == Type::kScalar_Kind) {
2718 actual += 1;
2719 if (type.kind() != Type::kScalar_Kind) {
2720 args[i] = this->coerce(std::move(args[i]), type.componentType());
2721 if (!args[i]) {
2722 return nullptr;
2723 }
2724 }
2725 } else {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002726 fErrors.error(offset, "'" + args[i]->fType.displayName() + "' is not a valid "
2727 "parameter to '" + type.displayName() + "' constructor");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002728 return nullptr;
2729 }
2730 }
Ethan Nicholas84645e32017-02-09 13:57:14 -05002731 if (actual != 1 && actual != expected) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002732 fErrors.error(offset, "invalid arguments to '" + type.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002733 "' constructor (expected " + to_string(expected) +
2734 " scalars, but found " + to_string(actual) + ")");
Ethan Nicholas49a36ba2017-02-09 17:04:23 +00002735 return nullptr;
2736 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002737 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002738 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
ethannicholasb3058bd2016-07-01 08:22:01 -07002739}
2740
Ethan Nicholas84645e32017-02-09 13:57:14 -05002741std::unique_ptr<Expression> IRGenerator::convertConstructor(
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002742 int offset,
Ethan Nicholas84645e32017-02-09 13:57:14 -05002743 const Type& type,
2744 std::vector<std::unique_ptr<Expression>> args) {
2745 // FIXME: add support for structs
Brian Osman82329002020-07-21 09:39:27 -04002746 if (args.size() == 1 && args[0]->fType == type &&
2747 type.nonnullable() != *fContext.fFragmentProcessor_Type) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05002748 // argument is already the right type, just return it
2749 return std::move(args[0]);
2750 }
Brian Osman82329002020-07-21 09:39:27 -04002751 Type::Kind kind = type.kind();
Ethan Nicholas84645e32017-02-09 13:57:14 -05002752 if (type.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002753 return this->convertNumberConstructor(offset, type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002754 } else if (kind == Type::kArray_Kind) {
2755 const Type& base = type.componentType();
2756 for (size_t i = 0; i < args.size(); i++) {
2757 args[i] = this->coerce(std::move(args[i]), base);
2758 if (!args[i]) {
2759 return nullptr;
2760 }
2761 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002762 return std::unique_ptr<Expression>(new Constructor(offset, type, std::move(args)));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002763 } else if (kind == Type::kVector_Kind || kind == Type::kMatrix_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002764 return this->convertCompoundConstructor(offset, type, std::move(args));
Ethan Nicholas84645e32017-02-09 13:57:14 -05002765 } else {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002766 fErrors.error(offset, "cannot construct '" + type.displayName() + "'");
Ethan Nicholas84645e32017-02-09 13:57:14 -05002767 return nullptr;
2768 }
2769}
2770
Ethan Nicholasfc994162019-06-06 10:04:27 -04002771std::unique_ptr<Expression> IRGenerator::convertPrefixExpression(const ASTNode& expression) {
2772 SkASSERT(expression.fKind == ASTNode::Kind::kPrefix);
2773 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
ethannicholasb3058bd2016-07-01 08:22:01 -07002774 if (!base) {
2775 return nullptr;
2776 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002777 switch (expression.getToken().fKind) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002778 case Token::Kind::TK_PLUS:
Ethan Nicholase1f55022019-02-05 17:17:40 -05002779 if (!base->fType.isNumber() && base->fType.kind() != Type::kVector_Kind &&
2780 base->fType != *fContext.fFloatLiteral_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002781 fErrors.error(expression.fOffset,
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002782 "'+' cannot operate on '" + base->fType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002783 return nullptr;
2784 }
2785 return base;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002786 case Token::Kind::TK_MINUS:
ethannicholasb3058bd2016-07-01 08:22:01 -07002787 if (base->fKind == Expression::kIntLiteral_Kind) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002788 return std::unique_ptr<Expression>(new IntLiteral(fContext, base->fOffset,
John Stiles81365af2020-08-18 09:24:00 -04002789 -base->as<IntLiteral>().fValue));
ethannicholasb3058bd2016-07-01 08:22:01 -07002790 }
2791 if (base->fKind == Expression::kFloatLiteral_Kind) {
John Stiles81365af2020-08-18 09:24:00 -04002792 double value = -base->as<FloatLiteral>().fValue;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002793 return std::unique_ptr<Expression>(new FloatLiteral(fContext, base->fOffset,
ethannicholasd598f792016-07-25 10:08:54 -07002794 value));
ethannicholasb3058bd2016-07-01 08:22:01 -07002795 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05002796 if (!base->fType.isNumber() && base->fType.kind() != Type::kVector_Kind) {
2797 fErrors.error(expression.fOffset,
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002798 "'-' cannot operate on '" + base->fType.displayName() + "'");
Ethan Nicholase1f55022019-02-05 17:17:40 -05002799 return nullptr;
2800 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002801 return std::unique_ptr<Expression>(new PrefixExpression(Token::Kind::TK_MINUS,
2802 std::move(base)));
2803 case Token::Kind::TK_PLUSPLUS:
ethannicholasd598f792016-07-25 10:08:54 -07002804 if (!base->fType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002805 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002806 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002807 "' cannot operate on '" + base->fType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002808 return nullptr;
2809 }
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -04002810 this->setRefKind(*base, VariableReference::kReadWrite_RefKind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002811 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002812 case Token::Kind::TK_MINUSMINUS:
ethannicholasd598f792016-07-25 10:08:54 -07002813 if (!base->fType.isNumber()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002814 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002815 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002816 "' cannot operate on '" + base->fType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002817 return nullptr;
2818 }
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -04002819 this->setRefKind(*base, VariableReference::kReadWrite_RefKind);
ethannicholasb3058bd2016-07-01 08:22:01 -07002820 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002821 case Token::Kind::TK_LOGICALNOT:
ethannicholasd598f792016-07-25 10:08:54 -07002822 if (base->fType != *fContext.fBool_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002823 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002824 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002825 "' cannot operate on '" + base->fType.displayName() + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002826 return nullptr;
2827 }
ethannicholas08a92112016-11-09 13:26:45 -08002828 if (base->fKind == Expression::kBoolLiteral_Kind) {
John Stiles403a3632020-08-20 12:11:48 -04002829 return std::unique_ptr<Expression>(
2830 new BoolLiteral(fContext, base->fOffset, !base->as<BoolLiteral>().fValue));
ethannicholas08a92112016-11-09 13:26:45 -08002831 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002832 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002833 case Token::Kind::TK_BITWISENOT:
Brian Osman73fb39c2019-09-24 16:22:55 -04002834 if (base->fType != *fContext.fInt_Type && base->fType != *fContext.fUInt_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002835 fErrors.error(expression.fOffset,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002836 String("'") + Compiler::OperatorName(expression.getToken().fKind) +
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002837 "' cannot operate on '" + base->fType.displayName() + "'");
ethannicholas5961bc92016-10-12 06:39:56 -07002838 return nullptr;
2839 }
2840 break;
Ethan Nicholas11d53972016-11-28 11:23:23 -05002841 default:
ethannicholasb3058bd2016-07-01 08:22:01 -07002842 ABORT("unsupported prefix operator\n");
2843 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04002844 return std::unique_ptr<Expression>(new PrefixExpression(expression.getToken().fKind,
ethannicholasb3058bd2016-07-01 08:22:01 -07002845 std::move(base)));
2846}
2847
2848std::unique_ptr<Expression> IRGenerator::convertIndex(std::unique_ptr<Expression> base,
Ethan Nicholasfc994162019-06-06 10:04:27 -04002849 const ASTNode& index) {
Ethan Nicholas50afc172017-02-16 14:49:57 -05002850 if (base->fKind == Expression::kTypeReference_Kind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04002851 if (index.fKind == ASTNode::Kind::kInt) {
John Stiles403a3632020-08-20 12:11:48 -04002852 const Type& oldType = base->as<TypeReference>().fValue;
Ethan Nicholasfc994162019-06-06 10:04:27 -04002853 SKSL_INT size = index.getInt();
John Stiles3ae071e2020-08-05 15:29:29 -04002854 const Type* newType = fSymbolTable->takeOwnershipOfSymbol(
2855 std::make_unique<Type>(oldType.name() + "[" + to_string(size) + "]",
2856 Type::kArray_Kind, oldType, size));
2857 return std::make_unique<TypeReference>(fContext, base->fOffset, *newType);
Ethan Nicholas50afc172017-02-16 14:49:57 -05002858
2859 } else {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002860 fErrors.error(base->fOffset, "array size must be a constant");
Ethan Nicholas50afc172017-02-16 14:49:57 -05002861 return nullptr;
2862 }
2863 }
ethannicholas5961bc92016-10-12 06:39:56 -07002864 if (base->fType.kind() != Type::kArray_Kind && base->fType.kind() != Type::kMatrix_Kind &&
2865 base->fType.kind() != Type::kVector_Kind) {
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002866 fErrors.error(base->fOffset, "expected array, but found '" + base->fType.displayName() +
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002867 "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002868 return nullptr;
2869 }
2870 std::unique_ptr<Expression> converted = this->convertExpression(index);
2871 if (!converted) {
2872 return nullptr;
2873 }
ethannicholas5961bc92016-10-12 06:39:56 -07002874 if (converted->fType != *fContext.fUInt_Type) {
2875 converted = this->coerce(std::move(converted), *fContext.fInt_Type);
2876 if (!converted) {
2877 return nullptr;
2878 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002879 }
Ethan Nicholas11d53972016-11-28 11:23:23 -05002880 return std::unique_ptr<Expression>(new IndexExpression(fContext, std::move(base),
ethannicholasd598f792016-07-25 10:08:54 -07002881 std::move(converted)));
ethannicholasb3058bd2016-07-01 08:22:01 -07002882}
2883
2884std::unique_ptr<Expression> IRGenerator::convertField(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002885 StringFragment field) {
Ethan Nicholas91164d12019-05-15 15:29:54 -04002886 if (base->fKind == Expression::kExternalValue_Kind) {
John Stiles17c5b702020-08-18 10:40:03 -04002887 const ExternalValue& ev = *base->as<ExternalValueReference>().fValue;
Ethan Nicholas91164d12019-05-15 15:29:54 -04002888 ExternalValue* result = ev.getChild(String(field).c_str());
2889 if (!result) {
2890 fErrors.error(base->fOffset, "external value does not have a child named '" + field +
2891 "'");
2892 return nullptr;
2893 }
2894 return std::unique_ptr<Expression>(new ExternalValueReference(base->fOffset, result));
2895 }
ethannicholasd598f792016-07-25 10:08:54 -07002896 auto fields = base->fType.fields();
ethannicholasb3058bd2016-07-01 08:22:01 -07002897 for (size_t i = 0; i < fields.size(); i++) {
2898 if (fields[i].fName == field) {
2899 return std::unique_ptr<Expression>(new FieldAccess(std::move(base), (int) i));
2900 }
2901 }
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002902 fErrors.error(base->fOffset, "type '" + base->fType.displayName() + "' does not have a "
Brian Osmanb08cc022020-04-02 11:38:40 -04002903 "field named '" + field + "");
ethannicholasb3058bd2016-07-01 08:22:01 -07002904 return nullptr;
2905}
2906
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002907// counts the number of chunks of contiguous 'x's in a swizzle, e.g. xxx1 has one and x0xx has two
John Stiles36374402020-08-13 12:16:44 -04002908static int count_contiguous_swizzle_chunks(const std::vector<int>& components) {
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002909 int chunkCount = 0;
2910 for (size_t i = 0; i < components.size(); ++i) {
2911 SkASSERT(components[i] <= 0);
2912 if (components[i] == 0) {
2913 ++chunkCount;
2914 while (i + 1 < components.size() && components[i + 1] == 0) {
2915 ++i;
2916 }
2917 }
2918 }
2919 return chunkCount;
2920}
2921
ethannicholasb3058bd2016-07-01 08:22:01 -07002922std::unique_ptr<Expression> IRGenerator::convertSwizzle(std::unique_ptr<Expression> base,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002923 StringFragment fields) {
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002924 if (base->fType.kind() != Type::kVector_Kind && !base->fType.isNumber()) {
2925 fErrors.error(base->fOffset, "cannot swizzle value of type '" + base->fType.displayName() +
2926 "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002927 return nullptr;
2928 }
2929 std::vector<int> swizzleComponents;
Brian Osmanb65dc4a2020-08-14 11:27:28 -04002930 size_t numLiteralFields = 0;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002931 for (size_t i = 0; i < fields.fLength; i++) {
Ethan Nicholas9e1138d2016-11-21 10:39:35 -05002932 switch (fields[i]) {
Ethan Nicholasac285b12019-02-12 16:05:18 -05002933 case '0':
Ethan Nicholasac285b12019-02-12 16:05:18 -05002934 swizzleComponents.push_back(SKSL_SWIZZLE_0);
Brian Osmanb65dc4a2020-08-14 11:27:28 -04002935 numLiteralFields++;
Ethan Nicholasac285b12019-02-12 16:05:18 -05002936 break;
2937 case '1':
Ethan Nicholasac285b12019-02-12 16:05:18 -05002938 swizzleComponents.push_back(SKSL_SWIZZLE_1);
Brian Osmanb65dc4a2020-08-14 11:27:28 -04002939 numLiteralFields++;
Ethan Nicholasac285b12019-02-12 16:05:18 -05002940 break;
Ethan Nicholase455f652019-09-13 12:52:55 -04002941 case 'x':
2942 case 'r':
Ethan Nicholas11d53972016-11-28 11:23:23 -05002943 case 's':
Ethan Nicholase455f652019-09-13 12:52:55 -04002944 case 'L':
ethannicholasb3058bd2016-07-01 08:22:01 -07002945 swizzleComponents.push_back(0);
2946 break;
Ethan Nicholase455f652019-09-13 12:52:55 -04002947 case 'y':
2948 case 'g':
ethannicholasb3058bd2016-07-01 08:22:01 -07002949 case 't':
Ethan Nicholase455f652019-09-13 12:52:55 -04002950 case 'T':
ethannicholasd598f792016-07-25 10:08:54 -07002951 if (base->fType.columns() >= 2) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002952 swizzleComponents.push_back(1);
2953 break;
2954 }
John Stiles30212b72020-06-11 17:55:07 -04002955 [[fallthrough]];
Ethan Nicholase455f652019-09-13 12:52:55 -04002956 case 'z':
2957 case 'b':
Ethan Nicholas11d53972016-11-28 11:23:23 -05002958 case 'p':
Ethan Nicholase455f652019-09-13 12:52:55 -04002959 case 'R':
ethannicholasd598f792016-07-25 10:08:54 -07002960 if (base->fType.columns() >= 3) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002961 swizzleComponents.push_back(2);
2962 break;
2963 }
John Stiles30212b72020-06-11 17:55:07 -04002964 [[fallthrough]];
Ethan Nicholase455f652019-09-13 12:52:55 -04002965 case 'w':
2966 case 'a':
ethannicholasb3058bd2016-07-01 08:22:01 -07002967 case 'q':
Ethan Nicholase455f652019-09-13 12:52:55 -04002968 case 'B':
ethannicholasd598f792016-07-25 10:08:54 -07002969 if (base->fType.columns() >= 4) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002970 swizzleComponents.push_back(3);
2971 break;
2972 }
John Stiles30212b72020-06-11 17:55:07 -04002973 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -07002974 default:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002975 fErrors.error(base->fOffset, String::printf("invalid swizzle component '%c'",
2976 fields[i]));
ethannicholasb3058bd2016-07-01 08:22:01 -07002977 return nullptr;
2978 }
2979 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04002980 SkASSERT(swizzleComponents.size() > 0);
ethannicholasb3058bd2016-07-01 08:22:01 -07002981 if (swizzleComponents.size() > 4) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002982 fErrors.error(base->fOffset, "too many components in swizzle mask '" + fields + "'");
ethannicholasb3058bd2016-07-01 08:22:01 -07002983 return nullptr;
2984 }
Brian Osmanb65dc4a2020-08-14 11:27:28 -04002985 if (numLiteralFields == swizzleComponents.size()) {
2986 fErrors.error(base->fOffset, "swizzle must refer to base expression");
2987 return nullptr;
2988 }
Ethan Nicholas7b9da252020-08-03 13:43:50 -04002989 if (base->fType.isNumber()) {
2990 // Swizzling a single scalar. Something like foo.x0x1 is equivalent to float4(foo, 0, foo,
2991 // 1)
2992 int offset = base->fOffset;
2993 std::unique_ptr<Expression> expr;
2994 switch (base->fKind) {
2995 case Expression::kVariableReference_Kind:
2996 case Expression::kFloatLiteral_Kind:
2997 case Expression::kIntLiteral_Kind:
2998 // the value being swizzled is just a constant or variable reference, so we can
2999 // safely re-use copies of it without reevaluation concerns
3000 expr = std::move(base);
3001 break;
3002 default:
3003 // It's a value we can't safely re-use multiple times. If it's all in one contiguous
3004 // chunk it's easy (e.g. foo.xxx0 can be turned into half4(half3(x), 0)), but
3005 // for multiple discontiguous chunks we'll need to copy it into a temporary value.
3006 int chunkCount = count_contiguous_swizzle_chunks(swizzleComponents);
3007 if (chunkCount <= 1) {
3008 // no copying needed, so we can just use the value directly
3009 expr = std::move(base);
3010 } else {
3011 // store the value in a temporary variable so we can re-use it
3012 int varIndex = fInlineVarCounter++;
3013 auto name = std::make_unique<String>();
3014 name->appendf("_tmpSwizzle%d", varIndex);
John Stiles3ae071e2020-08-05 15:29:29 -04003015 const String* namePtr = fSymbolTable->takeOwnershipOfString(std::move(name));
3016 const Variable* var = fSymbolTable->takeOwnershipOfSymbol(
3017 std::make_unique<Variable>(offset,
3018 Modifiers(),
3019 namePtr->c_str(),
3020 base->fType,
3021 Variable::kLocal_Storage,
3022 base.get()));
Ethan Nicholasd2dc2062020-08-03 16:05:04 -04003023 expr = std::make_unique<VariableReference>(offset, *var);
Ethan Nicholas7b9da252020-08-03 13:43:50 -04003024 std::vector<std::unique_ptr<VarDeclaration>> variables;
3025 variables.emplace_back(new VarDeclaration(var, {}, std::move(base)));
3026 fExtraStatements.emplace_back(new VarDeclarationsStatement(
3027 std::make_unique<VarDeclarations>(offset, &expr->fType,
3028 std::move(variables))));
3029 }
3030 }
3031 std::vector<std::unique_ptr<Expression>> args;
3032 for (size_t i = 0; i < swizzleComponents.size(); ++i) {
3033 switch (swizzleComponents[i]) {
3034 case 0: {
3035 args.push_back(expr->clone());
3036 int count = 1;
3037 while (i + 1 < swizzleComponents.size() && swizzleComponents[i + 1] == 0) {
3038 ++i;
3039 ++count;
3040 }
3041 if (count > 1) {
3042 std::vector<std::unique_ptr<Expression>> constructorArgs;
3043 constructorArgs.push_back(std::move(args.back()));
3044 args.pop_back();
3045 args.emplace_back(new Constructor(offset, expr->fType.toCompound(fContext,
3046 count,
3047 1),
3048 std::move(constructorArgs)));
3049 }
3050 break;
3051 }
3052 case SKSL_SWIZZLE_0:
3053 args.emplace_back(new IntLiteral(fContext, offset, 0));
3054 break;
3055 case SKSL_SWIZZLE_1:
3056 args.emplace_back(new IntLiteral(fContext, offset, 1));
3057 break;
3058 }
3059 }
3060 return std::unique_ptr<Expression>(new Constructor(offset,
3061 expr->fType.toCompound(
3062 fContext,
3063 swizzleComponents.size(),
3064 1),
3065 std::move(args)));
3066 }
ethannicholasd598f792016-07-25 10:08:54 -07003067 return std::unique_ptr<Expression>(new Swizzle(fContext, std::move(base), swizzleComponents));
ethannicholasb3058bd2016-07-01 08:22:01 -07003068}
3069
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07003070std::unique_ptr<Expression> IRGenerator::getCap(int offset, String name) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003071 auto found = fCapsMap.find(name);
3072 if (found == fCapsMap.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07003073 fErrors.error(offset, "unknown capability flag '" + name + "'");
Ethan Nicholas3605ace2016-11-21 15:59:48 -05003074 return nullptr;
3075 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04003076 String fullName = "sk_Caps." + name;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07003077 return std::unique_ptr<Expression>(new Setting(offset, fullName,
3078 found->second.literal(fContext, offset)));
Ethan Nicholas762466e2017-06-29 10:03:38 -04003079}
3080
Ethan Nicholasc18bb512020-07-28 14:46:53 -04003081std::unique_ptr<Expression> IRGenerator::findEnumRef(
3082 int offset,
3083 const Type& type,
3084 StringFragment field,
3085 std::vector<std::unique_ptr<ProgramElement>>& elements) {
3086 for (const auto& e : elements) {
John Stiles403a3632020-08-20 12:11:48 -04003087 if (e->fKind == ProgramElement::kEnum_Kind && type.name() == e->as<Enum>().fTypeName) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003088 std::shared_ptr<SymbolTable> old = fSymbolTable;
John Stiles403a3632020-08-20 12:11:48 -04003089 fSymbolTable = e->as<Enum>().fSymbols;
Ethan Nicholasc18bb512020-07-28 14:46:53 -04003090 std::unique_ptr<Expression> result = convertIdentifier(ASTNode(&fFile->fNodes, offset,
3091 ASTNode::Kind::kIdentifier,
3092 field));
3093 if (result) {
John Stiles403a3632020-08-20 12:11:48 -04003094 const Variable& v = result->as<VariableReference>().fVariable;
Ethan Nicholasc18bb512020-07-28 14:46:53 -04003095 SkASSERT(v.fInitialValue);
John Stilesfbd050b2020-08-03 13:21:46 -04003096 result = std::make_unique<IntLiteral>(
John Stiles81365af2020-08-18 09:24:00 -04003097 offset, v.fInitialValue->as<IntLiteral>().fValue, &type);
Ethan Nicholas9fdab9f2020-05-01 11:02:15 -04003098 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003099 fSymbolTable = old;
Ethan Nicholasc18bb512020-07-28 14:46:53 -04003100 return result;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003101 }
3102 }
Ethan Nicholasc18bb512020-07-28 14:46:53 -04003103 return nullptr;
3104}
3105
3106std::unique_ptr<Expression> IRGenerator::convertTypeField(int offset, const Type& type,
3107 StringFragment field) {
3108 std::unique_ptr<Expression> result = this->findEnumRef(offset, type, field, *fProgramElements);
3109 if (fInherited && !result) {
3110 result = this->findEnumRef(offset, type, field, *fInherited);
3111 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003112 if (!result) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05003113 auto found = fIntrinsics->find(type.fName);
3114 if (found != fIntrinsics->end()) {
John Stiles810c8cf2020-08-26 19:46:27 -04003115 SkASSERT(!found->second.fAlreadyIncluded);
3116 found->second.fAlreadyIncluded = true;
3117 fProgramElements->push_back(found->second.fIntrinsic->clone());
Ethan Nicholasdb80f692019-11-22 14:06:12 -05003118 return this->convertTypeField(offset, type, field);
3119 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003120 fErrors.error(offset, "type '" + type.fName + "' does not have a field named '" + field +
3121 "'");
3122 }
3123 return result;
3124}
3125
Ethan Nicholasfc994162019-06-06 10:04:27 -04003126std::unique_ptr<Expression> IRGenerator::convertIndexExpression(const ASTNode& index) {
3127 SkASSERT(index.fKind == ASTNode::Kind::kIndex);
3128 auto iter = index.begin();
3129 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
ethannicholasb3058bd2016-07-01 08:22:01 -07003130 if (!base) {
3131 return nullptr;
3132 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003133 if (iter != index.end()) {
3134 return this->convertIndex(std::move(base), *(iter++));
3135 } else if (base->fKind == Expression::kTypeReference_Kind) {
John Stiles403a3632020-08-20 12:11:48 -04003136 const Type& oldType = base->as<TypeReference>().fValue;
John Stiles3ae071e2020-08-05 15:29:29 -04003137 const Type* newType = fSymbolTable->takeOwnershipOfSymbol(std::make_unique<Type>(
3138 oldType.name() + "[]", Type::kArray_Kind, oldType, /*columns=*/-1));
Ethan Nicholasfc994162019-06-06 10:04:27 -04003139 return std::unique_ptr<Expression>(new TypeReference(fContext, base->fOffset,
3140 *newType));
ethannicholasb3058bd2016-07-01 08:22:01 -07003141 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003142 fErrors.error(index.fOffset, "'[]' must follow a type name");
3143 return nullptr;
3144}
3145
3146std::unique_ptr<Expression> IRGenerator::convertCallExpression(const ASTNode& callNode) {
3147 SkASSERT(callNode.fKind == ASTNode::Kind::kCall);
3148 auto iter = callNode.begin();
3149 std::unique_ptr<Expression> base = this->convertExpression(*(iter++));
3150 if (!base) {
3151 return nullptr;
3152 }
3153 std::vector<std::unique_ptr<Expression>> arguments;
3154 for (; iter != callNode.end(); ++iter) {
3155 std::unique_ptr<Expression> converted = this->convertExpression(*iter);
3156 if (!converted) {
3157 return nullptr;
3158 }
3159 arguments.push_back(std::move(converted));
3160 }
3161 return this->call(callNode.fOffset, std::move(base), std::move(arguments));
3162}
3163
3164std::unique_ptr<Expression> IRGenerator::convertFieldExpression(const ASTNode& fieldNode) {
3165 std::unique_ptr<Expression> base = this->convertExpression(*fieldNode.begin());
3166 if (!base) {
3167 return nullptr;
3168 }
3169 StringFragment field = fieldNode.getString();
3170 if (base->fType == *fContext.fSkCaps_Type) {
3171 return this->getCap(fieldNode.fOffset, field);
3172 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003173 if (base->fKind == Expression::kTypeReference_Kind) {
John Stiles403a3632020-08-20 12:11:48 -04003174 return this->convertTypeField(base->fOffset, base->as<TypeReference>().fValue,
Ethan Nicholasfc994162019-06-06 10:04:27 -04003175 field);
3176 }
3177 if (base->fKind == Expression::kExternalValue_Kind) {
3178 return this->convertField(std::move(base), field);
3179 }
3180 switch (base->fType.kind()) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04003181 case Type::kOther_Kind:
3182 case Type::kStruct_Kind:
3183 return this->convertField(std::move(base), field);
3184 default:
Ethan Nicholas7b9da252020-08-03 13:43:50 -04003185 return this->convertSwizzle(std::move(base), field);
Ethan Nicholasfc994162019-06-06 10:04:27 -04003186 }
3187}
3188
3189std::unique_ptr<Expression> IRGenerator::convertPostfixExpression(const ASTNode& expression) {
3190 std::unique_ptr<Expression> base = this->convertExpression(*expression.begin());
3191 if (!base) {
3192 return nullptr;
3193 }
3194 if (!base->fType.isNumber()) {
3195 fErrors.error(expression.fOffset,
3196 "'" + String(Compiler::OperatorName(expression.getToken().fKind)) +
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003197 "' cannot operate on '" + base->fType.displayName() + "'");
Ethan Nicholasfc994162019-06-06 10:04:27 -04003198 return nullptr;
3199 }
3200 this->setRefKind(*base, VariableReference::kReadWrite_RefKind);
3201 return std::unique_ptr<Expression>(new PostfixExpression(std::move(base),
3202 expression.getToken().fKind));
ethannicholasb3058bd2016-07-01 08:22:01 -07003203}
3204
3205void IRGenerator::checkValid(const Expression& expr) {
3206 switch (expr.fKind) {
3207 case Expression::kFunctionReference_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07003208 fErrors.error(expr.fOffset, "expected '(' to begin function call");
ethannicholasb3058bd2016-07-01 08:22:01 -07003209 break;
3210 case Expression::kTypeReference_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07003211 fErrors.error(expr.fOffset, "expected '(' to begin constructor invocation");
ethannicholasb3058bd2016-07-01 08:22:01 -07003212 break;
3213 default:
ethannicholasea4567c2016-10-17 11:24:37 -07003214 if (expr.fType == *fContext.fInvalid_Type) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07003215 fErrors.error(expr.fOffset, "invalid expression");
ethannicholasea4567c2016-10-17 11:24:37 -07003216 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003217 }
3218}
3219
Ethan Nicholascb0f4092019-04-19 11:26:50 -04003220bool IRGenerator::checkSwizzleWrite(const Swizzle& swizzle) {
ethannicholasb3058bd2016-07-01 08:22:01 -07003221 int bits = 0;
3222 for (int idx : swizzle.fComponents) {
Ethan Nicholascb0f4092019-04-19 11:26:50 -04003223 if (idx < 0) {
3224 fErrors.error(swizzle.fOffset, "cannot write to a swizzle mask containing a constant");
3225 return false;
3226 }
3227 SkASSERT(idx <= 3);
ethannicholasb3058bd2016-07-01 08:22:01 -07003228 int bit = 1 << idx;
3229 if (bits & bit) {
Ethan Nicholascb0f4092019-04-19 11:26:50 -04003230 fErrors.error(swizzle.fOffset,
3231 "cannot write to the same swizzle field more than once");
3232 return false;
ethannicholasb3058bd2016-07-01 08:22:01 -07003233 }
3234 bits |= bit;
3235 }
Ethan Nicholascb0f4092019-04-19 11:26:50 -04003236 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07003237}
3238
John Stiles403a3632020-08-20 12:11:48 -04003239bool IRGenerator::setRefKind(Expression& expr, VariableReference::RefKind kind) {
ethannicholasb3058bd2016-07-01 08:22:01 -07003240 switch (expr.fKind) {
3241 case Expression::kVariableReference_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04003242 const Variable& var = expr.as<VariableReference>().fVariable;
Brian Osman3c358422020-03-23 10:44:12 -04003243 if (var.fModifiers.fFlags &
3244 (Modifiers::kConst_Flag | Modifiers::kUniform_Flag | Modifiers::kVarying_Flag)) {
3245 fErrors.error(expr.fOffset, "cannot modify immutable variable '" + var.fName + "'");
Ethan Nicholas4fadce42020-07-30 13:29:30 -04003246 return false;
ethannicholasb3058bd2016-07-01 08:22:01 -07003247 }
John Stiles403a3632020-08-20 12:11:48 -04003248 expr.as<VariableReference>().setRefKind(kind);
Ethan Nicholas4fadce42020-07-30 13:29:30 -04003249 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07003250 }
3251 case Expression::kFieldAccess_Kind:
John Stiles403a3632020-08-20 12:11:48 -04003252 return this->setRefKind(*expr.as<FieldAccess>().fBase, kind);
Ethan Nicholascb0f4092019-04-19 11:26:50 -04003253 case Expression::kSwizzle_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04003254 const Swizzle& swizzle = expr.as<Swizzle>();
Ethan Nicholas4fadce42020-07-30 13:29:30 -04003255 return this->checkSwizzleWrite(swizzle) && this->setRefKind(*swizzle.fBase, kind);
Ethan Nicholascb0f4092019-04-19 11:26:50 -04003256 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003257 case Expression::kIndex_Kind:
John Stiles403a3632020-08-20 12:11:48 -04003258 return this->setRefKind(*expr.as<IndexExpression>().fBase, kind);
Ethan Nicholasa583b812018-01-18 13:32:11 -05003259 case Expression::kTernary_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04003260 const TernaryExpression& t = expr.as<TernaryExpression>();
Ethan Nicholas4fadce42020-07-30 13:29:30 -04003261 return this->setRefKind(*t.fIfTrue, kind) && this->setRefKind(*t.fIfFalse, kind);
Ethan Nicholasa583b812018-01-18 13:32:11 -05003262 }
Ethan Nicholas91164d12019-05-15 15:29:54 -04003263 case Expression::kExternalValue_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04003264 const ExternalValue& v = *expr.as<ExternalValueReference>().fValue;
Ethan Nicholas91164d12019-05-15 15:29:54 -04003265 if (!v.canWrite()) {
3266 fErrors.error(expr.fOffset,
3267 "cannot modify immutable external value '" + v.fName + "'");
Ethan Nicholas4fadce42020-07-30 13:29:30 -04003268 return false;
Ethan Nicholas91164d12019-05-15 15:29:54 -04003269 }
Ethan Nicholas4fadce42020-07-30 13:29:30 -04003270 return true;
Ethan Nicholas91164d12019-05-15 15:29:54 -04003271 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003272 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003273 fErrors.error(expr.fOffset, "cannot assign to this expression");
Ethan Nicholas4fadce42020-07-30 13:29:30 -04003274 return false;
ethannicholasb3058bd2016-07-01 08:22:01 -07003275 }
3276}
3277
Robert Phillipsfe8da172018-01-24 14:52:02 +00003278void IRGenerator::convertProgram(Program::Kind kind,
3279 const char* text,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07003280 size_t length,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003281 std::vector<std::unique_ptr<ProgramElement>>* out) {
Robert Phillipsfe8da172018-01-24 14:52:02 +00003282 fKind = kind;
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003283 fProgramElements = out;
Ethan Nicholasc18bb512020-07-28 14:46:53 -04003284 Parser parser(text, length, *fSymbolTable, fErrors);
Ethan Nicholasfc994162019-06-06 10:04:27 -04003285 fFile = parser.file();
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003286 if (fErrors.errorCount()) {
3287 return;
3288 }
Ethan Nicholasc18bb512020-07-28 14:46:53 -04003289 this->pushSymbolTable(); // this is popped by Compiler upon completion
Ethan Nicholasfc994162019-06-06 10:04:27 -04003290 SkASSERT(fFile);
3291 for (const auto& decl : fFile->root()) {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003292 switch (decl.fKind) {
Ethan Nicholasfc994162019-06-06 10:04:27 -04003293 case ASTNode::Kind::kVarDeclarations: {
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003294 std::unique_ptr<VarDeclarations> s = this->convertVarDeclarations(
Ethan Nicholasfc994162019-06-06 10:04:27 -04003295 decl,
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003296 Variable::kGlobal_Storage);
3297 if (s) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003298 fProgramElements->push_back(std::move(s));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003299 }
3300 break;
3301 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003302 case ASTNode::Kind::kEnum: {
3303 this->convertEnum(decl);
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003304 break;
3305 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003306 case ASTNode::Kind::kFunction: {
3307 this->convertFunction(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003308 break;
3309 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003310 case ASTNode::Kind::kModifiers: {
3311 std::unique_ptr<ModifiersDeclaration> f = this->convertModifiersDeclaration(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003312 if (f) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003313 fProgramElements->push_back(std::move(f));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003314 }
3315 break;
3316 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003317 case ASTNode::Kind::kInterfaceBlock: {
3318 std::unique_ptr<InterfaceBlock> i = this->convertInterfaceBlock(decl);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003319 if (i) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003320 fProgramElements->push_back(std::move(i));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003321 }
3322 break;
3323 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003324 case ASTNode::Kind::kExtension: {
3325 std::unique_ptr<Extension> e = this->convertExtension(decl.fOffset,
3326 decl.getString());
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003327 if (e) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003328 fProgramElements->push_back(std::move(e));
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003329 }
3330 break;
3331 }
Ethan Nicholasfc994162019-06-06 10:04:27 -04003332 case ASTNode::Kind::kSection: {
3333 std::unique_ptr<Section> s = this->convertSection(decl);
Ethan Nicholas762466e2017-06-29 10:03:38 -04003334 if (s) {
Ethan Nicholasaae47c82017-11-10 15:34:03 -05003335 fProgramElements->push_back(std::move(s));
Ethan Nicholas762466e2017-06-29 10:03:38 -04003336 }
3337 break;
3338 }
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003339 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003340#ifdef SK_DEBUG
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003341 ABORT("unsupported declaration: %s\n", decl.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003342#endif
3343 break;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04003344 }
3345 }
3346}
3347
3348
John Stilesa6841be2020-08-06 14:11:56 -04003349} // namespace SkSL