blob: 5ede14d44e9dcc6eab6593d0ad3fbbc461b0550d [file] [log] [blame]
John Stiles44e96be2020-08-31 13:16:04 -04001/*
2 * Copyright 2020 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/sksl/SkSLInliner.h"
9
10#include "limits.h"
11#include <memory>
12#include <unordered_set>
13
14#include "src/sksl/SkSLAnalysis.h"
15#include "src/sksl/ir/SkSLBinaryExpression.h"
16#include "src/sksl/ir/SkSLBoolLiteral.h"
17#include "src/sksl/ir/SkSLBreakStatement.h"
18#include "src/sksl/ir/SkSLConstructor.h"
19#include "src/sksl/ir/SkSLContinueStatement.h"
20#include "src/sksl/ir/SkSLDiscardStatement.h"
21#include "src/sksl/ir/SkSLDoStatement.h"
22#include "src/sksl/ir/SkSLEnum.h"
23#include "src/sksl/ir/SkSLExpressionStatement.h"
24#include "src/sksl/ir/SkSLExternalFunctionCall.h"
25#include "src/sksl/ir/SkSLExternalValueReference.h"
26#include "src/sksl/ir/SkSLField.h"
27#include "src/sksl/ir/SkSLFieldAccess.h"
28#include "src/sksl/ir/SkSLFloatLiteral.h"
29#include "src/sksl/ir/SkSLForStatement.h"
30#include "src/sksl/ir/SkSLFunctionCall.h"
31#include "src/sksl/ir/SkSLFunctionDeclaration.h"
32#include "src/sksl/ir/SkSLFunctionDefinition.h"
33#include "src/sksl/ir/SkSLFunctionReference.h"
34#include "src/sksl/ir/SkSLIfStatement.h"
35#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040036#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040037#include "src/sksl/ir/SkSLIntLiteral.h"
38#include "src/sksl/ir/SkSLInterfaceBlock.h"
39#include "src/sksl/ir/SkSLLayout.h"
40#include "src/sksl/ir/SkSLNop.h"
41#include "src/sksl/ir/SkSLNullLiteral.h"
42#include "src/sksl/ir/SkSLPostfixExpression.h"
43#include "src/sksl/ir/SkSLPrefixExpression.h"
44#include "src/sksl/ir/SkSLReturnStatement.h"
45#include "src/sksl/ir/SkSLSetting.h"
46#include "src/sksl/ir/SkSLSwitchCase.h"
47#include "src/sksl/ir/SkSLSwitchStatement.h"
48#include "src/sksl/ir/SkSLSwizzle.h"
49#include "src/sksl/ir/SkSLTernaryExpression.h"
50#include "src/sksl/ir/SkSLUnresolvedFunction.h"
51#include "src/sksl/ir/SkSLVarDeclarations.h"
52#include "src/sksl/ir/SkSLVarDeclarationsStatement.h"
53#include "src/sksl/ir/SkSLVariable.h"
54#include "src/sksl/ir/SkSLVariableReference.h"
55#include "src/sksl/ir/SkSLWhileStatement.h"
56
57namespace SkSL {
58namespace {
59
60static int count_all_returns(const FunctionDefinition& funcDef) {
61 class CountAllReturns : public ProgramVisitor {
62 public:
63 CountAllReturns(const FunctionDefinition& funcDef) {
64 this->visitProgramElement(funcDef);
65 }
66
67 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040068 switch (stmt.kind()) {
69 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040070 ++fNumReturns;
71 [[fallthrough]];
72
73 default:
John Stiles93442622020-09-11 12:11:27 -040074 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040075 }
76 }
77
78 int fNumReturns = 0;
79 using INHERITED = ProgramVisitor;
80 };
81
82 return CountAllReturns{funcDef}.fNumReturns;
83}
84
85static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
86 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
87 public:
88 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
89 this->visitProgramElement(funcDef);
90 }
91
92 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040093 switch (stmt.kind()) {
94 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040095 // Check only the last statement of a block.
96 const auto& blockStmts = stmt.as<Block>().fStatements;
97 return (blockStmts.size() > 0) ? this->visitStatement(*blockStmts.back())
98 : false;
99 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400100 case Statement::Kind::kSwitch:
101 case Statement::Kind::kWhile:
102 case Statement::Kind::kDo:
103 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -0400104 // Don't introspect switches or loop structures at all.
105 return false;
106
Ethan Nicholase6592142020-09-08 10:22:09 -0400107 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400108 ++fNumReturns;
109 [[fallthrough]];
110
111 default:
John Stiles93442622020-09-11 12:11:27 -0400112 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400113 }
114 }
115
116 int fNumReturns = 0;
117 using INHERITED = ProgramVisitor;
118 };
119
120 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
121}
122
123static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
124 class CountReturnsInBreakableConstructs : public ProgramVisitor {
125 public:
126 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
127 this->visitProgramElement(funcDef);
128 }
129
130 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400131 switch (stmt.kind()) {
132 case Statement::Kind::kSwitch:
133 case Statement::Kind::kWhile:
134 case Statement::Kind::kDo:
135 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400136 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400137 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400138 --fInsideBreakableConstruct;
139 return result;
140 }
141
Ethan Nicholase6592142020-09-08 10:22:09 -0400142 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400143 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
144 [[fallthrough]];
145
146 default:
John Stiles93442622020-09-11 12:11:27 -0400147 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400148 }
149 }
150
151 int fNumReturns = 0;
152 int fInsideBreakableConstruct = 0;
153 using INHERITED = ProgramVisitor;
154 };
155
156 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
157}
158
159static bool has_early_return(const FunctionDefinition& funcDef) {
160 int returnCount = count_all_returns(funcDef);
161 if (returnCount == 0) {
162 return false;
163 }
164
165 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
166 return returnCount > returnsAtEndOfControlFlow;
167}
168
John Stiles991b09d2020-09-10 13:33:40 -0400169static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
170 class ContainsRecursiveCall : public ProgramVisitor {
171 public:
172 bool visit(const FunctionDeclaration& funcDecl) {
173 fFuncDecl = &funcDecl;
174 return funcDecl.fDefinition ? this->visitProgramElement(*funcDecl.fDefinition)
175 : false;
176 }
177
178 bool visitExpression(const Expression& expr) override {
179 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().fFunction.matches(*fFuncDecl)) {
180 return true;
181 }
182 return INHERITED::visitExpression(expr);
183 }
184
185 bool visitStatement(const Statement& stmt) override {
186 if (stmt.is<InlineMarker>() && stmt.as<InlineMarker>().fFuncDecl->matches(*fFuncDecl)) {
187 return true;
188 }
189 return INHERITED::visitStatement(stmt);
190 }
191
192 const FunctionDeclaration* fFuncDecl;
193 using INHERITED = ProgramVisitor;
194 };
195
196 return ContainsRecursiveCall{}.visit(funcDecl);
197}
198
John Stiles915a38c2020-09-14 09:38:13 -0400199static void ensure_scoped_blocks(Block* inlinedBody, Statement* parentStmt) {
200 if (parentStmt && (parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
201 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
202 // Occasionally, IR generation can lead to Blocks containing multiple statements, but no
203 // scope. If this block is used as the statement for a do/for/if/while, this isn't actually
204 // possible to represent textually; a scope must be added for the generated code to match
205 // the intent. In the case of Blocks nested inside other Blocks, we add the scope to the
206 // outermost block if needed. Zero-statement blocks have similar issues--if we don't
207 // represent the Block textually somehow, we run the risk of accidentally absorbing the
208 // following statement into our loop--so we also add a scope to these.
209 for (Block* nestedBlock = inlinedBody;; ) {
210 if (nestedBlock->fIsScope) {
211 // We found an explicit scope; all is well.
212 return;
213 }
214 if (nestedBlock->fStatements.size() != 1) {
215 // We found a block with multiple (or zero) statements, but no scope? Let's add a
216 // scope to the outermost block.
217 inlinedBody->fIsScope = true;
218 return;
219 }
220 if (!nestedBlock->fStatements[0]->is<Block>()) {
221 // This block has exactly one thing inside, and it's not another block. No need to
222 // scope it.
223 return;
224 }
225 // We have to go deeper.
226 nestedBlock = &nestedBlock->fStatements[0]->as<Block>();
227 }
228 }
229}
230
John Stiles44e96be2020-08-31 13:16:04 -0400231static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400232 if (src->typeKind() == Type::TypeKind::kArray) {
John Stiles44e96be2020-08-31 13:16:04 -0400233 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(*src));
234 }
235 return src;
236}
237
John Stiles915a38c2020-09-14 09:38:13 -0400238static Statement* find_parent_statement(const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
239 SkASSERT(!stmtStack.empty());
240
241 // Walk the statement stack from back to front, ignoring the last element (which is the
242 // enclosing statement).
243 auto iter = stmtStack.rbegin();
244 ++iter;
245
246 // Anything counts as a parent statement other than a scopeless Block.
247 for (; iter != stmtStack.rend(); ++iter) {
248 Statement* stmt = (*iter)->get();
249 if (!stmt->is<Block>() || stmt->as<Block>().fIsScope) {
250 return stmt;
251 }
252 }
253
254 // There wasn't any parent statement to be found.
255 return nullptr;
256}
257
John Stiles44e96be2020-08-31 13:16:04 -0400258} // namespace
259
260void Inliner::reset(const Context& context, const Program::Settings& settings) {
261 fContext = &context;
262 fSettings = &settings;
263 fInlineVarCounter = 0;
264}
265
John Stilesc75abb82020-09-14 18:24:12 -0400266String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
267 // If the base name starts with an underscore, like "_coords", we can't append another
268 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
269 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
270 // putting in this special case.
271 const char* splitter = baseName.startsWith("_") ? "" : "_";
272
273 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
274 // we're not reusing an existing name. (Note that within a single compilation pass, this check
275 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
276 String uniqueName;
277 for (;;) {
278 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
279 StringFragment frag{uniqueName.data(), uniqueName.length()};
280 if ((*symbolTable)[frag] == nullptr) {
281 break;
282 }
283 }
284
285 return uniqueName;
286}
287
John Stiles44e96be2020-08-31 13:16:04 -0400288std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
289 VariableRewriteMap* varMap,
290 const Expression& expression) {
291 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
292 if (e) {
293 return this->inlineExpression(offset, varMap, *e);
294 }
295 return nullptr;
296 };
297 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
298 -> std::vector<std::unique_ptr<Expression>> {
299 std::vector<std::unique_ptr<Expression>> args;
300 args.reserve(originalArgs.size());
301 for (const std::unique_ptr<Expression>& arg : originalArgs) {
302 args.push_back(expr(arg));
303 }
304 return args;
305 };
306
Ethan Nicholase6592142020-09-08 10:22:09 -0400307 switch (expression.kind()) {
308 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400309 const BinaryExpression& b = expression.as<BinaryExpression>();
310 return std::make_unique<BinaryExpression>(offset,
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000311 expr(b.fLeft),
312 b.fOperator,
313 expr(b.fRight),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400314 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400315 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400316 case Expression::Kind::kBoolLiteral:
317 case Expression::Kind::kIntLiteral:
318 case Expression::Kind::kFloatLiteral:
319 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400320 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400321 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400322 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400323 return std::make_unique<Constructor>(offset, &constructor.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400324 argList(constructor.fArguments));
325 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400326 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400327 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400328 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400329 externalCall.fFunction,
330 argList(externalCall.fArguments));
331 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400332 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400333 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400334 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400335 const FieldAccess& f = expression.as<FieldAccess>();
336 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
337 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400338 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400339 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400340 return std::make_unique<FunctionCall>(offset, &funcCall.type(), funcCall.fFunction,
John Stiles44e96be2020-08-31 13:16:04 -0400341 argList(funcCall.fArguments));
342 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400343 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400344 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400345 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400346 const IndexExpression& idx = expression.as<IndexExpression>();
347 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
348 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400349 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400350 const PrefixExpression& p = expression.as<PrefixExpression>();
351 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
352 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400353 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400354 const PostfixExpression& p = expression.as<PostfixExpression>();
355 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
356 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400357 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400358 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400359 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400360 const Swizzle& s = expression.as<Swizzle>();
361 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
362 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400363 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400364 const TernaryExpression& t = expression.as<TernaryExpression>();
365 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
366 expr(t.fIfTrue), expr(t.fIfFalse));
367 }
Brian Osman83ba9302020-09-11 13:33:46 -0400368 case Expression::Kind::kTypeReference:
369 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400370 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400371 const VariableReference& v = expression.as<VariableReference>();
372 auto found = varMap->find(&v.fVariable);
373 if (found != varMap->end()) {
374 return std::make_unique<VariableReference>(offset, *found->second, v.fRefKind);
375 }
376 return v.clone();
377 }
378 default:
379 SkASSERT(false);
380 return nullptr;
381 }
382}
383
384std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
385 VariableRewriteMap* varMap,
386 SymbolTable* symbolTableForStatement,
387 const Variable* returnVar,
388 bool haveEarlyReturns,
389 const Statement& statement) {
390 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
391 if (s) {
392 return this->inlineStatement(offset, varMap, symbolTableForStatement, returnVar,
393 haveEarlyReturns, *s);
394 }
395 return nullptr;
396 };
397 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
398 std::vector<std::unique_ptr<Statement>> result;
399 for (const auto& s : ss) {
400 result.push_back(stmt(s));
401 }
402 return result;
403 };
404 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
405 if (e) {
406 return this->inlineExpression(offset, varMap, *e);
407 }
408 return nullptr;
409 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400410 switch (statement.kind()) {
411 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400412 const Block& b = statement.as<Block>();
413 return std::make_unique<Block>(offset, stmts(b.fStatements), b.fSymbols, b.fIsScope);
414 }
415
Ethan Nicholase6592142020-09-08 10:22:09 -0400416 case Statement::Kind::kBreak:
417 case Statement::Kind::kContinue:
418 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400419 return statement.clone();
420
Ethan Nicholase6592142020-09-08 10:22:09 -0400421 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400422 const DoStatement& d = statement.as<DoStatement>();
423 return std::make_unique<DoStatement>(offset, stmt(d.fStatement), expr(d.fTest));
424 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400425 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400426 const ExpressionStatement& e = statement.as<ExpressionStatement>();
427 return std::make_unique<ExpressionStatement>(expr(e.fExpression));
428 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400429 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400430 const ForStatement& f = statement.as<ForStatement>();
431 // need to ensure initializer is evaluated first so that we've already remapped its
432 // declarations by the time we evaluate test & next
433 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
434 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
435 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
436 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400437 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400438 const IfStatement& i = statement.as<IfStatement>();
439 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
440 stmt(i.fIfTrue), stmt(i.fIfFalse));
441 }
John Stiles98c1f822020-09-09 14:18:53 -0400442 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400443 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400444 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400445 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400446 const ReturnStatement& r = statement.as<ReturnStatement>();
447 if (r.fExpression) {
448 auto assignment = std::make_unique<ExpressionStatement>(
449 std::make_unique<BinaryExpression>(
450 offset,
451 std::make_unique<VariableReference>(offset, *returnVar,
452 VariableReference::kWrite_RefKind),
453 Token::Kind::TK_EQ,
454 expr(r.fExpression),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400455 &returnVar->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400456 if (haveEarlyReturns) {
457 std::vector<std::unique_ptr<Statement>> block;
458 block.push_back(std::move(assignment));
459 block.emplace_back(new BreakStatement(offset));
460 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
461 /*isScope=*/true);
462 } else {
463 return std::move(assignment);
464 }
465 } else {
466 if (haveEarlyReturns) {
467 return std::make_unique<BreakStatement>(offset);
468 } else {
469 return std::make_unique<Nop>();
470 }
471 }
472 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400473 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400474 const SwitchStatement& ss = statement.as<SwitchStatement>();
475 std::vector<std::unique_ptr<SwitchCase>> cases;
476 for (const auto& sc : ss.fCases) {
477 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
478 stmts(sc->fStatements)));
479 }
480 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
481 std::move(cases), ss.fSymbols);
482 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400483 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400484 const VarDeclaration& decl = statement.as<VarDeclaration>();
485 std::vector<std::unique_ptr<Expression>> sizes;
486 for (const auto& size : decl.fSizes) {
487 sizes.push_back(expr(size));
488 }
489 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
490 const Variable* old = decl.fVar;
John Stilesc75abb82020-09-14 18:24:12 -0400491 // We assign unique names to inlined variables--scopes hide most of the problems in this
492 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
493 // names are important.
494 auto name = std::make_unique<String>(
495 this->uniqueNameForInlineVar(String(old->fName), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400496 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas30d30222020-09-11 12:27:26 -0400497 const Type* typePtr = copy_if_needed(&old->type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400498 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
499 std::make_unique<Variable>(offset,
500 old->fModifiers,
501 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400502 typePtr,
John Stiles44e96be2020-08-31 13:16:04 -0400503 old->fStorage,
504 initialValue.get()));
505 (*varMap)[old] = clone;
506 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
507 std::move(initialValue));
508 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400509 case Statement::Kind::kVarDeclarations: {
John Stiles44e96be2020-08-31 13:16:04 -0400510 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
511 std::vector<std::unique_ptr<VarDeclaration>> vars;
512 for (const auto& var : decls.fVars) {
513 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
514 }
515 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
516 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
517 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
518 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400519 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400520 const WhileStatement& w = statement.as<WhileStatement>();
521 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
522 }
523 default:
524 SkASSERT(false);
525 return nullptr;
526 }
527}
528
John Stiles6eadf132020-09-08 10:16:10 -0400529Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles44e96be2020-08-31 13:16:04 -0400530 SymbolTable* symbolTableForCall) {
531 // Inlining is more complicated here than in a typical compiler, because we have to have a
532 // high-level IR and can't just drop statements into the middle of an expression or even use
533 // gotos.
534 //
535 // Since we can't insert statements into an expression, we run the inline function as extra
536 // statements before the statement we're currently processing, relying on a lack of execution
537 // order guarantees. Since we can't use gotos (which are normally used to replace return
538 // statements), we wrap the whole function in a loop and use break statements to jump to the
539 // end.
540 SkASSERT(fSettings);
541 SkASSERT(fContext);
542 SkASSERT(call);
543 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
544
John Stiles44e96be2020-08-31 13:16:04 -0400545 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
John Stiles6eadf132020-09-08 10:16:10 -0400546 const int offset = call->fOffset;
John Stiles44e96be2020-08-31 13:16:04 -0400547 const FunctionDefinition& function = *call->fFunction.fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400548 const bool hasEarlyReturn = has_early_return(function);
549
John Stiles44e96be2020-08-31 13:16:04 -0400550 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400551 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
552 std::vector<std::unique_ptr<Statement>>{},
553 /*symbols=*/nullptr,
554 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400555
John Stiles6eadf132020-09-08 10:16:10 -0400556 std::vector<std::unique_ptr<Statement>>& inlinedBody = inlinedCall.fInlinedBody->fStatements;
John Stiles98c1f822020-09-09 14:18:53 -0400557 inlinedBody.reserve(1 + // Inline marker
558 1 + // Result variable
559 arguments.size() + // Function arguments (passing in)
560 arguments.size() + // Function arguments (copy out-parameters back)
561 1); // Inlined code (either as a Block or do-while loop)
562
563 inlinedBody.push_back(std::make_unique<InlineMarker>(call->fFunction));
John Stiles44e96be2020-08-31 13:16:04 -0400564
John Stilesa003e812020-09-11 09:43:49 -0400565 auto makeInlineVar = [&](const String& baseName, const Type* type, Modifiers modifiers,
John Stiles44e96be2020-08-31 13:16:04 -0400566 std::unique_ptr<Expression>* initialValue) -> const Variable* {
John Stilesa003e812020-09-11 09:43:49 -0400567 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
568 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
569 // somewhere during compilation.
570 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400571 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400572 type = fContext->fFloat_Type.get();
573 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400574 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400575 type = fContext->fInt_Type.get();
576 }
577
John Stilesc75abb82020-09-14 18:24:12 -0400578 // Provide our new variable with a unique name, and add it to our symbol table.
579 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400580 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
581 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400582 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
583
584 // Add our new variable to the symbol table.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400585 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
John Stiles44e96be2020-08-31 13:16:04 -0400586 Variable::kLocal_Storage, initialValue->get());
587 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
588
589 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
590 // initial value).
591 std::vector<std::unique_ptr<VarDeclaration>> variables;
592 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
593 variables.push_back(std::make_unique<VarDeclaration>(
594 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
595 (*initialValue)->clone()));
596 } else {
597 variables.push_back(std::make_unique<VarDeclaration>(
598 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
599 std::move(*initialValue)));
600 }
601
602 // Add the new variable-declaration statement to our block of extra statements.
John Stiles39616ec2020-08-31 14:16:06 -0400603 inlinedBody.push_back(std::make_unique<VarDeclarationsStatement>(
John Stilesa003e812020-09-11 09:43:49 -0400604 std::make_unique<VarDeclarations>(offset, type, std::move(variables))));
John Stiles44e96be2020-08-31 13:16:04 -0400605
606 return variableSymbol;
607 };
608
609 // Create a variable to hold the result in the extra statements (excepting void).
610 const Variable* resultVar = nullptr;
611 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400612 std::unique_ptr<Expression> noInitialValue;
John Stilescf936f92020-08-31 17:18:45 -0400613 resultVar = makeInlineVar(String(function.fDeclaration.fName),
John Stilesa003e812020-09-11 09:43:49 -0400614 &function.fDeclaration.fReturnType, Modifiers{}, &noInitialValue);
John Stiles44e96be2020-08-31 13:16:04 -0400615 }
616
617 // Create variables in the extra statements to hold the arguments, and assign the arguments to
618 // them.
619 VariableRewriteMap varMap;
John Stiles44e96be2020-08-31 13:16:04 -0400620 for (int i = 0; i < (int) arguments.size(); ++i) {
621 const Variable* param = function.fDeclaration.fParameters[i];
622
John Stilesa003e812020-09-11 09:43:49 -0400623 if (arguments[i]->is<VariableReference>()) {
John Stiles44e96be2020-08-31 13:16:04 -0400624 // The argument is just a variable, so we only need to copy it if it's an out parameter
625 // or it's written to within the function.
626 if ((param->fModifiers.fFlags & Modifiers::kOut_Flag) ||
627 !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
628 varMap[param] = &arguments[i]->as<VariableReference>().fVariable;
629 continue;
630 }
631 }
632
Ethan Nicholas30d30222020-09-11 12:27:26 -0400633 varMap[param] = makeInlineVar(String(param->fName), &arguments[i]->type(),
634 param->fModifiers, &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400635 }
636
637 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400638 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
639 inlineBlock->fStatements.reserve(body.fStatements.size());
640 for (const std::unique_ptr<Statement>& stmt : body.fStatements) {
641 inlineBlock->fStatements.push_back(this->inlineStatement(
642 offset, &varMap, symbolTableForCall, resultVar, hasEarlyReturn, *stmt));
643 }
644 if (hasEarlyReturn) {
645 // Since we output to backends that don't have a goto statement (which would normally be
646 // used to perform an early return), we fake it by wrapping the function in a
647 // do { } while (false); and then use break statements to jump to the end in order to
648 // emulate a goto.
John Stiles39616ec2020-08-31 14:16:06 -0400649 inlinedBody.push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400650 /*offset=*/-1,
651 std::move(inlineBlock),
652 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
653 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400654 // No early returns, so we can just dump the code in. We still need to keep the block so we
655 // don't get name conflicts with locals.
John Stiles39616ec2020-08-31 14:16:06 -0400656 inlinedBody.push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400657 }
658
659 // Copy the values of `out` parameters into their destinations.
660 for (size_t i = 0; i < arguments.size(); ++i) {
661 const Variable* p = function.fDeclaration.fParameters[i];
662 if (p->fModifiers.fFlags & Modifiers::kOut_Flag) {
663 SkASSERT(varMap.find(p) != varMap.end());
Ethan Nicholase6592142020-09-08 10:22:09 -0400664 if (arguments[i]->kind() == Expression::Kind::kVariableReference &&
John Stiles44e96be2020-08-31 13:16:04 -0400665 &arguments[i]->as<VariableReference>().fVariable == varMap[p]) {
John Stiles6eadf132020-09-08 10:16:10 -0400666 // We didn't create a temporary for this parameter, so there's nothing to copy back
667 // out.
John Stiles44e96be2020-08-31 13:16:04 -0400668 continue;
669 }
670 auto varRef = std::make_unique<VariableReference>(offset, *varMap[p]);
John Stiles39616ec2020-08-31 14:16:06 -0400671 inlinedBody.push_back(std::make_unique<ExpressionStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400672 std::make_unique<BinaryExpression>(offset,
673 arguments[i]->clone(),
674 Token::Kind::TK_EQ,
675 std::move(varRef),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400676 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400677 }
678 }
679
680 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
681 // Return a reference to the result variable as our replacement expression.
682 inlinedCall.fReplacementExpr = std::make_unique<VariableReference>(offset, *resultVar);
683 } else {
684 // It's a void function, so it doesn't actually result in anything, but we have to return
685 // something non-null as a standin.
686 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
687 /*value=*/false);
688 }
689
John Stiles44e96be2020-08-31 13:16:04 -0400690 return inlinedCall;
691}
692
John Stiles93442622020-09-11 12:11:27 -0400693bool Inliner::isSafeToInline(const FunctionCall& functionCall, int inlineThreshold) {
John Stiles44e96be2020-08-31 13:16:04 -0400694 SkASSERT(fSettings);
695
696 if (functionCall.fFunction.fDefinition == nullptr) {
697 // Can't inline something if we don't actually have its definition.
698 return false;
699 }
700 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
701 if (inlineThreshold < INT_MAX) {
702 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
703 Analysis::NodeCount(functionDef) >= inlineThreshold) {
704 // The function exceeds our maximum inline size and is not flagged 'inline'.
705 return false;
706 }
707 }
John Stiles44e96be2020-08-31 13:16:04 -0400708 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
709 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
710 // can't inline functions that have an early return.
711 bool hasEarlyReturn = has_early_return(functionDef);
712
713 // If we didn't detect an early return, there shouldn't be any returns in breakable
714 // constructs either.
715 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
716 return !hasEarlyReturn;
717 }
718 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
719 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
720 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
721
722 // If we detected returns in breakable constructs, we should also detect an early return.
723 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
724 return !hasReturnInBreakableConstruct;
725}
726
John Stiles93442622020-09-11 12:11:27 -0400727bool Inliner::analyze(Program& program) {
728 // A candidate function for inlining, containing everything that `inlineCall` needs.
729 struct InlineCandidate {
John Stiles915a38c2020-09-14 09:38:13 -0400730 SymbolTable* fSymbols; // the SymbolTable of the candidate
731 Statement* fParentStmt; // the parent Statement of the enclosing stmt
732 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
733 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
John Stiles93442622020-09-11 12:11:27 -0400734 };
735
736 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
737 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
738 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
739 // `const T&`.
740 class InlineCandidateAnalyzer {
741 public:
742 // A list of all the inlining candidates we found during analysis.
743 std::vector<InlineCandidate> fInlineCandidates;
744 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower
745 // than the enclosing-statement stack.
746 std::vector<SymbolTable*> fSymbolTableStack;
747 // A stack of "enclosing" statements--these would be suitable for the inliner to use for
748 // adding new instructions. Not all statements are suitable (e.g. a for-loop's initializer).
749 // The inliner might replace a statement with a block containing the statement.
750 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
751
752 void visit(Program& program) {
753 fSymbolTableStack.push_back(program.fSymbols.get());
754
755 for (ProgramElement& pe : program) {
756 this->visitProgramElement(&pe);
757 }
758
759 fSymbolTableStack.pop_back();
760 }
761
762 void visitProgramElement(ProgramElement* pe) {
763 switch (pe->kind()) {
764 case ProgramElement::Kind::kFunction: {
765 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
766 this->visitStatement(&funcDef.fBody);
767 break;
768 }
769 default:
770 // The inliner can't operate outside of a function's scope.
771 break;
772 }
773 }
774
775 void visitStatement(std::unique_ptr<Statement>* stmt,
776 bool isViableAsEnclosingStatement = true) {
777 if (!*stmt) {
778 return;
779 }
780
781 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
782 size_t oldSymbolStackSize = fSymbolTableStack.size();
783
784 if (isViableAsEnclosingStatement) {
785 fEnclosingStmtStack.push_back(stmt);
786 }
787
788 switch ((*stmt)->kind()) {
789 case Statement::Kind::kBreak:
790 case Statement::Kind::kContinue:
791 case Statement::Kind::kDiscard:
792 case Statement::Kind::kInlineMarker:
793 case Statement::Kind::kNop:
794 break;
795
796 case Statement::Kind::kBlock: {
797 Block& block = (*stmt)->as<Block>();
798 if (block.fSymbols) {
799 fSymbolTableStack.push_back(block.fSymbols.get());
800 }
801
802 for (std::unique_ptr<Statement>& blockStmt : block.fStatements) {
803 this->visitStatement(&blockStmt);
804 }
805 break;
806 }
807 case Statement::Kind::kDo: {
808 DoStatement& doStmt = (*stmt)->as<DoStatement>();
809 // The loop body is a candidate for inlining.
810 this->visitStatement(&doStmt.fStatement);
811 // The inliner isn't smart enough to inline the test-expression for a do-while
812 // loop at this time. There are two limitations:
813 // - We would need to insert the inlined-body block at the very end of the do-
814 // statement's inner fStatement. We don't support that today, but it's doable.
815 // - We cannot inline the test expression if the loop uses `continue` anywhere;
816 // that would skip over the inlined block that evaluates the test expression.
817 // There isn't a good fix for this--any workaround would be more complex than
818 // the cost of a function call. However, loops that don't use `continue` would
819 // still be viable candidates for inlining.
820 break;
821 }
822 case Statement::Kind::kExpression: {
823 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
824 this->visitExpression(&expr.fExpression);
825 break;
826 }
827 case Statement::Kind::kFor: {
828 ForStatement& forStmt = (*stmt)->as<ForStatement>();
829 if (forStmt.fSymbols) {
830 fSymbolTableStack.push_back(forStmt.fSymbols.get());
831 }
832
833 // The initializer and loop body are candidates for inlining.
834 this->visitStatement(&forStmt.fInitializer,
835 /*isViableAsEnclosingStatement=*/false);
836 this->visitStatement(&forStmt.fStatement);
837
838 // The inliner isn't smart enough to inline the test- or increment-expressions
839 // of a for loop loop at this time. There are a handful of limitations:
840 // - We would need to insert the test-expression block at the very beginning of
841 // the for-loop's inner fStatement, and the increment-expression block at the
842 // very end. We don't support that today, but it's doable.
843 // - The for-loop's built-in test-expression would need to be dropped entirely,
844 // and the loop would be halted via a break statement at the end of the
845 // inlined test-expression. This is again something we don't support today,
846 // but it could be implemented.
847 // - We cannot inline the increment-expression if the loop uses `continue`
848 // anywhere; that would skip over the inlined block that evaluates the
849 // increment expression. There isn't a good fix for this--any workaround would
850 // be more complex than the cost of a function call. However, loops that don't
851 // use `continue` would still be viable candidates for increment-expression
852 // inlining.
853 break;
854 }
855 case Statement::Kind::kIf: {
856 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
857 this->visitExpression(&ifStmt.fTest);
858 this->visitStatement(&ifStmt.fIfTrue);
859 this->visitStatement(&ifStmt.fIfFalse);
860 break;
861 }
862 case Statement::Kind::kReturn: {
863 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
864 this->visitExpression(&returnStmt.fExpression);
865 break;
866 }
867 case Statement::Kind::kSwitch: {
868 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
869 if (switchStmt.fSymbols) {
870 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
871 }
872
873 this->visitExpression(&switchStmt.fValue);
874 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
875 // The switch-case's fValue cannot be a FunctionCall; skip it.
876 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
877 this->visitStatement(&caseBlock);
878 }
879 }
880 break;
881 }
882 case Statement::Kind::kVarDeclaration: {
883 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
884 // Don't need to scan the declaration's sizes; those are always IntLiterals.
885 this->visitExpression(&varDeclStmt.fValue);
886 break;
887 }
888 case Statement::Kind::kVarDeclarations: {
889 VarDeclarationsStatement& varDecls = (*stmt)->as<VarDeclarationsStatement>();
890 for (std::unique_ptr<Statement>& varDecl : varDecls.fDeclaration->fVars) {
891 this->visitStatement(&varDecl, /*isViableAsEnclosingStatement=*/false);
892 }
893 break;
894 }
895 case Statement::Kind::kWhile: {
896 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
897 // The loop body is a candidate for inlining.
898 this->visitStatement(&whileStmt.fStatement);
899 // The inliner isn't smart enough to inline the test-expression for a while
900 // loop at this time. There are two limitations:
901 // - We would need to insert the inlined-body block at the very beginning of the
902 // while loop's inner fStatement. We don't support that today, but it's
903 // doable.
904 // - The while-loop's built-in test-expression would need to be replaced with a
905 // `true` BoolLiteral, and the loop would be halted via a break statement at
906 // the end of the inlined test-expression. This is again something we don't
907 // support today, but it could be implemented.
908 break;
909 }
910 default:
911 SkUNREACHABLE;
912 }
913
914 // Pop our symbol and enclosing-statement stacks.
915 fSymbolTableStack.resize(oldSymbolStackSize);
916 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
917 }
918
919 void visitExpression(std::unique_ptr<Expression>* expr) {
920 if (!*expr) {
921 return;
922 }
923
924 switch ((*expr)->kind()) {
925 case Expression::Kind::kBoolLiteral:
926 case Expression::Kind::kDefined:
927 case Expression::Kind::kExternalValue:
928 case Expression::Kind::kFieldAccess:
929 case Expression::Kind::kFloatLiteral:
930 case Expression::Kind::kFunctionReference:
931 case Expression::Kind::kIntLiteral:
932 case Expression::Kind::kNullLiteral:
933 case Expression::Kind::kSetting:
934 case Expression::Kind::kTypeReference:
935 case Expression::Kind::kVariableReference:
936 // Nothing to scan here.
937 break;
938
939 case Expression::Kind::kBinary: {
940 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000941 this->visitExpression(&binaryExpr.fLeft);
John Stiles93442622020-09-11 12:11:27 -0400942
943 // Logical-and and logical-or binary expressions do not inline the right side,
944 // because that would invalidate short-circuiting. That is, when evaluating
945 // expressions like these:
946 // (false && x()) // always false
947 // (true || y()) // always true
948 // It is illegal for side-effects from x() or y() to occur. The simplest way to
949 // enforce that rule is to avoid inlining the right side entirely. However, it
950 // is safe for other types of binary expression to inline both sides.
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000951 bool shortCircuitable = (binaryExpr.fOperator == Token::Kind::TK_LOGICALAND ||
952 binaryExpr.fOperator == Token::Kind::TK_LOGICALOR);
John Stiles93442622020-09-11 12:11:27 -0400953 if (!shortCircuitable) {
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000954 this->visitExpression(&binaryExpr.fRight);
John Stiles93442622020-09-11 12:11:27 -0400955 }
956 break;
957 }
958 case Expression::Kind::kConstructor: {
959 Constructor& constructorExpr = (*expr)->as<Constructor>();
960 for (std::unique_ptr<Expression>& arg : constructorExpr.fArguments) {
961 this->visitExpression(&arg);
962 }
963 break;
964 }
965 case Expression::Kind::kExternalFunctionCall: {
966 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
967 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
968 this->visitExpression(&arg);
969 }
970 break;
971 }
972 case Expression::Kind::kFunctionCall: {
973 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
974 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
975 this->visitExpression(&arg);
976 }
977 this->addInlineCandidate(expr);
978 break;
979 }
980 case Expression::Kind::kIndex:{
981 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
982 this->visitExpression(&indexExpr.fBase);
983 this->visitExpression(&indexExpr.fIndex);
984 break;
985 }
986 case Expression::Kind::kPostfix: {
987 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
988 this->visitExpression(&postfixExpr.fOperand);
989 break;
990 }
991 case Expression::Kind::kPrefix: {
992 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
993 this->visitExpression(&prefixExpr.fOperand);
994 break;
995 }
996 case Expression::Kind::kSwizzle: {
997 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
998 this->visitExpression(&swizzleExpr.fBase);
999 break;
1000 }
1001 case Expression::Kind::kTernary: {
1002 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1003 // The test expression is a candidate for inlining.
1004 this->visitExpression(&ternaryExpr.fTest);
1005 // The true- and false-expressions cannot be inlined, because we are only
1006 // allowed to evaluate one side.
1007 break;
1008 }
1009 default:
1010 SkUNREACHABLE;
1011 }
1012 }
1013
1014 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1015 fInlineCandidates.push_back(InlineCandidate{fSymbolTableStack.back(),
John Stiles915a38c2020-09-14 09:38:13 -04001016 find_parent_statement(fEnclosingStmtStack),
1017 fEnclosingStmtStack.back(),
1018 candidate});
John Stiles93442622020-09-11 12:11:27 -04001019 }
1020 };
1021
John Stiles93442622020-09-11 12:11:27 -04001022 InlineCandidateAnalyzer analyzer;
1023 analyzer.visit(program);
John Stiles915a38c2020-09-14 09:38:13 -04001024
1025 // For each of our candidate function-call sites, check if it is actually safe to inline.
1026 // Memoize our results so we don't check a function more than once.
John Stiles93442622020-09-11 12:11:27 -04001027 std::unordered_map<const FunctionDeclaration*, bool> inlinableMap; // <function, safe-to-inline>
John Stiles915a38c2020-09-14 09:38:13 -04001028 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
John Stiles93442622020-09-11 12:11:27 -04001029 const FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1030 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1031 if (inlinableMap.find(funcDecl) == inlinableMap.end()) {
1032 // We do not perform inlining on recursive calls to avoid an infinite death spiral of
1033 // inlining.
1034 int inlineThreshold = (funcDecl->fCallCount.load() > 1) ? fSettings->fInlineThreshold
1035 : INT_MAX;
1036 inlinableMap[funcDecl] = this->isSafeToInline(funcCall, inlineThreshold) &&
1037 !contains_recursive_call(*funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001038 }
1039 }
1040
John Stiles915a38c2020-09-14 09:38:13 -04001041 // Inline the candidates where we've determined that it's safe to do so.
1042 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1043 bool madeChanges = false;
1044 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
1045 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1046 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1047
1048 // If we determined that this candidate was not actually inlinable, skip it.
1049 if (!inlinableMap[funcDecl]) {
1050 continue;
1051 }
1052
1053 // Inlining two expressions using the same enclosing statement in the same inlining pass
1054 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1055 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1056 if (!inserted) {
1057 continue;
1058 }
1059
1060 // Convert the function call to its inlined equivalent.
1061 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols);
1062 if (inlinedCall.fInlinedBody) {
1063 // Ensure that the inlined body has a scope if it needs one.
1064 ensure_scoped_blocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt);
1065
1066 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1067 // function, then replace the enclosing statement with that Block.
1068 // Before:
1069 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1070 // fEnclosingStmt = stmt4
1071 // After:
1072 // fInlinedBody = null
1073 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
1074 inlinedCall.fInlinedBody->fStatements.push_back(std::move(*candidate.fEnclosingStmt));
1075 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1076 }
1077
1078 // Replace the candidate function call with our replacement expression.
1079 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1080 madeChanges = true;
1081
1082 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1083 // remain valid.
1084 }
1085
1086 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001087}
1088
John Stiles44e96be2020-08-31 13:16:04 -04001089} // namespace SkSL