blob: c59d805373b1ba294ea6d53e33f5212f8ff41955 [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
266std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
267 VariableRewriteMap* varMap,
268 const Expression& expression) {
269 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
270 if (e) {
271 return this->inlineExpression(offset, varMap, *e);
272 }
273 return nullptr;
274 };
275 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
276 -> std::vector<std::unique_ptr<Expression>> {
277 std::vector<std::unique_ptr<Expression>> args;
278 args.reserve(originalArgs.size());
279 for (const std::unique_ptr<Expression>& arg : originalArgs) {
280 args.push_back(expr(arg));
281 }
282 return args;
283 };
284
Ethan Nicholase6592142020-09-08 10:22:09 -0400285 switch (expression.kind()) {
286 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400287 const BinaryExpression& b = expression.as<BinaryExpression>();
288 return std::make_unique<BinaryExpression>(offset,
289 expr(b.fLeft),
290 b.fOperator,
291 expr(b.fRight),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400292 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400293 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400294 case Expression::Kind::kBoolLiteral:
295 case Expression::Kind::kIntLiteral:
296 case Expression::Kind::kFloatLiteral:
297 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400298 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400299 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400300 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400301 return std::make_unique<Constructor>(offset, &constructor.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400302 argList(constructor.fArguments));
303 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400304 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400305 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400306 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400307 externalCall.fFunction,
308 argList(externalCall.fArguments));
309 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400310 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400311 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400312 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400313 const FieldAccess& f = expression.as<FieldAccess>();
314 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
315 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400316 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400317 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400318 return std::make_unique<FunctionCall>(offset, &funcCall.type(), funcCall.fFunction,
John Stiles44e96be2020-08-31 13:16:04 -0400319 argList(funcCall.fArguments));
320 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400321 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400322 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400323 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400324 const IndexExpression& idx = expression.as<IndexExpression>();
325 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
326 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400327 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400328 const PrefixExpression& p = expression.as<PrefixExpression>();
329 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
330 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400331 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400332 const PostfixExpression& p = expression.as<PostfixExpression>();
333 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
334 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400335 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400336 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400337 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400338 const Swizzle& s = expression.as<Swizzle>();
339 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
340 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400341 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400342 const TernaryExpression& t = expression.as<TernaryExpression>();
343 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
344 expr(t.fIfTrue), expr(t.fIfFalse));
345 }
Brian Osman83ba9302020-09-11 13:33:46 -0400346 case Expression::Kind::kTypeReference:
347 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400348 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400349 const VariableReference& v = expression.as<VariableReference>();
350 auto found = varMap->find(&v.fVariable);
351 if (found != varMap->end()) {
352 return std::make_unique<VariableReference>(offset, *found->second, v.fRefKind);
353 }
354 return v.clone();
355 }
356 default:
357 SkASSERT(false);
358 return nullptr;
359 }
360}
361
362std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
363 VariableRewriteMap* varMap,
364 SymbolTable* symbolTableForStatement,
365 const Variable* returnVar,
366 bool haveEarlyReturns,
367 const Statement& statement) {
368 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
369 if (s) {
370 return this->inlineStatement(offset, varMap, symbolTableForStatement, returnVar,
371 haveEarlyReturns, *s);
372 }
373 return nullptr;
374 };
375 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
376 std::vector<std::unique_ptr<Statement>> result;
377 for (const auto& s : ss) {
378 result.push_back(stmt(s));
379 }
380 return result;
381 };
382 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
383 if (e) {
384 return this->inlineExpression(offset, varMap, *e);
385 }
386 return nullptr;
387 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400388 switch (statement.kind()) {
389 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400390 const Block& b = statement.as<Block>();
391 return std::make_unique<Block>(offset, stmts(b.fStatements), b.fSymbols, b.fIsScope);
392 }
393
Ethan Nicholase6592142020-09-08 10:22:09 -0400394 case Statement::Kind::kBreak:
395 case Statement::Kind::kContinue:
396 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400397 return statement.clone();
398
Ethan Nicholase6592142020-09-08 10:22:09 -0400399 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400400 const DoStatement& d = statement.as<DoStatement>();
401 return std::make_unique<DoStatement>(offset, stmt(d.fStatement), expr(d.fTest));
402 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400403 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400404 const ExpressionStatement& e = statement.as<ExpressionStatement>();
405 return std::make_unique<ExpressionStatement>(expr(e.fExpression));
406 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400407 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400408 const ForStatement& f = statement.as<ForStatement>();
409 // need to ensure initializer is evaluated first so that we've already remapped its
410 // declarations by the time we evaluate test & next
411 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
412 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
413 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
414 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400415 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400416 const IfStatement& i = statement.as<IfStatement>();
417 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
418 stmt(i.fIfTrue), stmt(i.fIfFalse));
419 }
John Stiles98c1f822020-09-09 14:18:53 -0400420 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400421 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400422 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400423 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400424 const ReturnStatement& r = statement.as<ReturnStatement>();
425 if (r.fExpression) {
426 auto assignment = std::make_unique<ExpressionStatement>(
427 std::make_unique<BinaryExpression>(
428 offset,
429 std::make_unique<VariableReference>(offset, *returnVar,
430 VariableReference::kWrite_RefKind),
431 Token::Kind::TK_EQ,
432 expr(r.fExpression),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400433 &returnVar->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400434 if (haveEarlyReturns) {
435 std::vector<std::unique_ptr<Statement>> block;
436 block.push_back(std::move(assignment));
437 block.emplace_back(new BreakStatement(offset));
438 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
439 /*isScope=*/true);
440 } else {
441 return std::move(assignment);
442 }
443 } else {
444 if (haveEarlyReturns) {
445 return std::make_unique<BreakStatement>(offset);
446 } else {
447 return std::make_unique<Nop>();
448 }
449 }
450 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400451 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400452 const SwitchStatement& ss = statement.as<SwitchStatement>();
453 std::vector<std::unique_ptr<SwitchCase>> cases;
454 for (const auto& sc : ss.fCases) {
455 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
456 stmts(sc->fStatements)));
457 }
458 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
459 std::move(cases), ss.fSymbols);
460 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400461 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400462 const VarDeclaration& decl = statement.as<VarDeclaration>();
463 std::vector<std::unique_ptr<Expression>> sizes;
464 for (const auto& size : decl.fSizes) {
465 sizes.push_back(expr(size));
466 }
467 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
468 const Variable* old = decl.fVar;
469 // need to copy the var name in case the originating function is discarded and we lose
470 // its symbols
471 std::unique_ptr<String> name(new String(old->fName));
472 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas30d30222020-09-11 12:27:26 -0400473 const Type* typePtr = copy_if_needed(&old->type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400474 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
475 std::make_unique<Variable>(offset,
476 old->fModifiers,
477 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400478 typePtr,
John Stiles44e96be2020-08-31 13:16:04 -0400479 old->fStorage,
480 initialValue.get()));
481 (*varMap)[old] = clone;
482 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
483 std::move(initialValue));
484 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400485 case Statement::Kind::kVarDeclarations: {
John Stiles44e96be2020-08-31 13:16:04 -0400486 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
487 std::vector<std::unique_ptr<VarDeclaration>> vars;
488 for (const auto& var : decls.fVars) {
489 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
490 }
491 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
492 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
493 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
494 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400495 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400496 const WhileStatement& w = statement.as<WhileStatement>();
497 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
498 }
499 default:
500 SkASSERT(false);
501 return nullptr;
502 }
503}
504
John Stiles6eadf132020-09-08 10:16:10 -0400505Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles44e96be2020-08-31 13:16:04 -0400506 SymbolTable* symbolTableForCall) {
507 // Inlining is more complicated here than in a typical compiler, because we have to have a
508 // high-level IR and can't just drop statements into the middle of an expression or even use
509 // gotos.
510 //
511 // Since we can't insert statements into an expression, we run the inline function as extra
512 // statements before the statement we're currently processing, relying on a lack of execution
513 // order guarantees. Since we can't use gotos (which are normally used to replace return
514 // statements), we wrap the whole function in a loop and use break statements to jump to the
515 // end.
516 SkASSERT(fSettings);
517 SkASSERT(fContext);
518 SkASSERT(call);
519 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
520
John Stiles44e96be2020-08-31 13:16:04 -0400521 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
John Stiles6eadf132020-09-08 10:16:10 -0400522 const int offset = call->fOffset;
John Stiles44e96be2020-08-31 13:16:04 -0400523 const FunctionDefinition& function = *call->fFunction.fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400524 const bool hasEarlyReturn = has_early_return(function);
525
John Stiles44e96be2020-08-31 13:16:04 -0400526 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400527 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
528 std::vector<std::unique_ptr<Statement>>{},
529 /*symbols=*/nullptr,
530 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400531
John Stiles6eadf132020-09-08 10:16:10 -0400532 std::vector<std::unique_ptr<Statement>>& inlinedBody = inlinedCall.fInlinedBody->fStatements;
John Stiles98c1f822020-09-09 14:18:53 -0400533 inlinedBody.reserve(1 + // Inline marker
534 1 + // Result variable
535 arguments.size() + // Function arguments (passing in)
536 arguments.size() + // Function arguments (copy out-parameters back)
537 1); // Inlined code (either as a Block or do-while loop)
538
539 inlinedBody.push_back(std::make_unique<InlineMarker>(call->fFunction));
John Stiles44e96be2020-08-31 13:16:04 -0400540
John Stilesa003e812020-09-11 09:43:49 -0400541 auto makeInlineVar = [&](const String& baseName, const Type* type, Modifiers modifiers,
John Stiles44e96be2020-08-31 13:16:04 -0400542 std::unique_ptr<Expression>* initialValue) -> const Variable* {
John Stilesa003e812020-09-11 09:43:49 -0400543 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
544 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
545 // somewhere during compilation.
546 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400547 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400548 type = fContext->fFloat_Type.get();
549 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400550 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400551 type = fContext->fInt_Type.get();
552 }
553
John Stilescf936f92020-08-31 17:18:45 -0400554 // If the base name starts with an underscore, like "_coords", we can't append another
555 // underscore, because some OpenGL platforms error out when they see two consecutive
556 // underscores (anywhere in the string!). But in the general case, using the underscore as
557 // a splitter reads nicely enough that it's worth putting in this special case.
558 const char* splitter = baseName.startsWith("_") ? "_X" : "_";
559
560 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
561 // we're not reusing an existing name. (Note that within a single compilation pass, this
562 // check isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
563 String uniqueName;
564 for (;;) {
565 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
566 StringFragment frag{uniqueName.data(), uniqueName.length()};
567 if ((*symbolTableForCall)[frag] == nullptr) {
568 break;
569 }
570 }
571
John Stiles44e96be2020-08-31 13:16:04 -0400572 // Add our new variable's name to the symbol table.
John Stilescf936f92020-08-31 17:18:45 -0400573 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
574 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400575 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
576
577 // Add our new variable to the symbol table.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400578 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
John Stiles44e96be2020-08-31 13:16:04 -0400579 Variable::kLocal_Storage, initialValue->get());
580 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
581
582 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
583 // initial value).
584 std::vector<std::unique_ptr<VarDeclaration>> variables;
585 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
586 variables.push_back(std::make_unique<VarDeclaration>(
587 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
588 (*initialValue)->clone()));
589 } else {
590 variables.push_back(std::make_unique<VarDeclaration>(
591 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
592 std::move(*initialValue)));
593 }
594
595 // Add the new variable-declaration statement to our block of extra statements.
John Stiles39616ec2020-08-31 14:16:06 -0400596 inlinedBody.push_back(std::make_unique<VarDeclarationsStatement>(
John Stilesa003e812020-09-11 09:43:49 -0400597 std::make_unique<VarDeclarations>(offset, type, std::move(variables))));
John Stiles44e96be2020-08-31 13:16:04 -0400598
599 return variableSymbol;
600 };
601
602 // Create a variable to hold the result in the extra statements (excepting void).
603 const Variable* resultVar = nullptr;
604 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400605 std::unique_ptr<Expression> noInitialValue;
John Stilescf936f92020-08-31 17:18:45 -0400606 resultVar = makeInlineVar(String(function.fDeclaration.fName),
John Stilesa003e812020-09-11 09:43:49 -0400607 &function.fDeclaration.fReturnType, Modifiers{}, &noInitialValue);
John Stiles44e96be2020-08-31 13:16:04 -0400608 }
609
610 // Create variables in the extra statements to hold the arguments, and assign the arguments to
611 // them.
612 VariableRewriteMap varMap;
John Stiles44e96be2020-08-31 13:16:04 -0400613 for (int i = 0; i < (int) arguments.size(); ++i) {
614 const Variable* param = function.fDeclaration.fParameters[i];
615
John Stilesa003e812020-09-11 09:43:49 -0400616 if (arguments[i]->is<VariableReference>()) {
John Stiles44e96be2020-08-31 13:16:04 -0400617 // The argument is just a variable, so we only need to copy it if it's an out parameter
618 // or it's written to within the function.
619 if ((param->fModifiers.fFlags & Modifiers::kOut_Flag) ||
620 !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
621 varMap[param] = &arguments[i]->as<VariableReference>().fVariable;
622 continue;
623 }
624 }
625
Ethan Nicholas30d30222020-09-11 12:27:26 -0400626 varMap[param] = makeInlineVar(String(param->fName), &arguments[i]->type(),
627 param->fModifiers, &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400628 }
629
630 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400631 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
632 inlineBlock->fStatements.reserve(body.fStatements.size());
633 for (const std::unique_ptr<Statement>& stmt : body.fStatements) {
634 inlineBlock->fStatements.push_back(this->inlineStatement(
635 offset, &varMap, symbolTableForCall, resultVar, hasEarlyReturn, *stmt));
636 }
637 if (hasEarlyReturn) {
638 // Since we output to backends that don't have a goto statement (which would normally be
639 // used to perform an early return), we fake it by wrapping the function in a
640 // do { } while (false); and then use break statements to jump to the end in order to
641 // emulate a goto.
John Stiles39616ec2020-08-31 14:16:06 -0400642 inlinedBody.push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400643 /*offset=*/-1,
644 std::move(inlineBlock),
645 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
646 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400647 // No early returns, so we can just dump the code in. We still need to keep the block so we
648 // don't get name conflicts with locals.
John Stiles39616ec2020-08-31 14:16:06 -0400649 inlinedBody.push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400650 }
651
652 // Copy the values of `out` parameters into their destinations.
653 for (size_t i = 0; i < arguments.size(); ++i) {
654 const Variable* p = function.fDeclaration.fParameters[i];
655 if (p->fModifiers.fFlags & Modifiers::kOut_Flag) {
656 SkASSERT(varMap.find(p) != varMap.end());
Ethan Nicholase6592142020-09-08 10:22:09 -0400657 if (arguments[i]->kind() == Expression::Kind::kVariableReference &&
John Stiles44e96be2020-08-31 13:16:04 -0400658 &arguments[i]->as<VariableReference>().fVariable == varMap[p]) {
John Stiles6eadf132020-09-08 10:16:10 -0400659 // We didn't create a temporary for this parameter, so there's nothing to copy back
660 // out.
John Stiles44e96be2020-08-31 13:16:04 -0400661 continue;
662 }
663 auto varRef = std::make_unique<VariableReference>(offset, *varMap[p]);
John Stiles39616ec2020-08-31 14:16:06 -0400664 inlinedBody.push_back(std::make_unique<ExpressionStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400665 std::make_unique<BinaryExpression>(offset,
666 arguments[i]->clone(),
667 Token::Kind::TK_EQ,
668 std::move(varRef),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400669 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400670 }
671 }
672
673 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
674 // Return a reference to the result variable as our replacement expression.
675 inlinedCall.fReplacementExpr = std::make_unique<VariableReference>(offset, *resultVar);
676 } else {
677 // It's a void function, so it doesn't actually result in anything, but we have to return
678 // something non-null as a standin.
679 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
680 /*value=*/false);
681 }
682
John Stiles44e96be2020-08-31 13:16:04 -0400683 return inlinedCall;
684}
685
John Stiles93442622020-09-11 12:11:27 -0400686bool Inliner::isSafeToInline(const FunctionCall& functionCall, int inlineThreshold) {
John Stiles44e96be2020-08-31 13:16:04 -0400687 SkASSERT(fSettings);
688
689 if (functionCall.fFunction.fDefinition == nullptr) {
690 // Can't inline something if we don't actually have its definition.
691 return false;
692 }
693 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
694 if (inlineThreshold < INT_MAX) {
695 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
696 Analysis::NodeCount(functionDef) >= inlineThreshold) {
697 // The function exceeds our maximum inline size and is not flagged 'inline'.
698 return false;
699 }
700 }
John Stiles44e96be2020-08-31 13:16:04 -0400701 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
702 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
703 // can't inline functions that have an early return.
704 bool hasEarlyReturn = has_early_return(functionDef);
705
706 // If we didn't detect an early return, there shouldn't be any returns in breakable
707 // constructs either.
708 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
709 return !hasEarlyReturn;
710 }
711 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
712 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
713 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
714
715 // If we detected returns in breakable constructs, we should also detect an early return.
716 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
717 return !hasReturnInBreakableConstruct;
718}
719
John Stiles93442622020-09-11 12:11:27 -0400720bool Inliner::analyze(Program& program) {
721 // A candidate function for inlining, containing everything that `inlineCall` needs.
722 struct InlineCandidate {
John Stiles915a38c2020-09-14 09:38:13 -0400723 SymbolTable* fSymbols; // the SymbolTable of the candidate
724 Statement* fParentStmt; // the parent Statement of the enclosing stmt
725 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
726 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
John Stiles93442622020-09-11 12:11:27 -0400727 };
728
729 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
730 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
731 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
732 // `const T&`.
733 class InlineCandidateAnalyzer {
734 public:
735 // A list of all the inlining candidates we found during analysis.
736 std::vector<InlineCandidate> fInlineCandidates;
737 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower
738 // than the enclosing-statement stack.
739 std::vector<SymbolTable*> fSymbolTableStack;
740 // A stack of "enclosing" statements--these would be suitable for the inliner to use for
741 // adding new instructions. Not all statements are suitable (e.g. a for-loop's initializer).
742 // The inliner might replace a statement with a block containing the statement.
743 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
744
745 void visit(Program& program) {
746 fSymbolTableStack.push_back(program.fSymbols.get());
747
748 for (ProgramElement& pe : program) {
749 this->visitProgramElement(&pe);
750 }
751
752 fSymbolTableStack.pop_back();
753 }
754
755 void visitProgramElement(ProgramElement* pe) {
756 switch (pe->kind()) {
757 case ProgramElement::Kind::kFunction: {
758 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
759 this->visitStatement(&funcDef.fBody);
760 break;
761 }
762 default:
763 // The inliner can't operate outside of a function's scope.
764 break;
765 }
766 }
767
768 void visitStatement(std::unique_ptr<Statement>* stmt,
769 bool isViableAsEnclosingStatement = true) {
770 if (!*stmt) {
771 return;
772 }
773
774 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
775 size_t oldSymbolStackSize = fSymbolTableStack.size();
776
777 if (isViableAsEnclosingStatement) {
778 fEnclosingStmtStack.push_back(stmt);
779 }
780
781 switch ((*stmt)->kind()) {
782 case Statement::Kind::kBreak:
783 case Statement::Kind::kContinue:
784 case Statement::Kind::kDiscard:
785 case Statement::Kind::kInlineMarker:
786 case Statement::Kind::kNop:
787 break;
788
789 case Statement::Kind::kBlock: {
790 Block& block = (*stmt)->as<Block>();
791 if (block.fSymbols) {
792 fSymbolTableStack.push_back(block.fSymbols.get());
793 }
794
795 for (std::unique_ptr<Statement>& blockStmt : block.fStatements) {
796 this->visitStatement(&blockStmt);
797 }
798 break;
799 }
800 case Statement::Kind::kDo: {
801 DoStatement& doStmt = (*stmt)->as<DoStatement>();
802 // The loop body is a candidate for inlining.
803 this->visitStatement(&doStmt.fStatement);
804 // The inliner isn't smart enough to inline the test-expression for a do-while
805 // loop at this time. There are two limitations:
806 // - We would need to insert the inlined-body block at the very end of the do-
807 // statement's inner fStatement. We don't support that today, but it's doable.
808 // - We cannot inline the test expression if the loop uses `continue` anywhere;
809 // that would skip over the inlined block that evaluates the test expression.
810 // There isn't a good fix for this--any workaround would be more complex than
811 // the cost of a function call. However, loops that don't use `continue` would
812 // still be viable candidates for inlining.
813 break;
814 }
815 case Statement::Kind::kExpression: {
816 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
817 this->visitExpression(&expr.fExpression);
818 break;
819 }
820 case Statement::Kind::kFor: {
821 ForStatement& forStmt = (*stmt)->as<ForStatement>();
822 if (forStmt.fSymbols) {
823 fSymbolTableStack.push_back(forStmt.fSymbols.get());
824 }
825
826 // The initializer and loop body are candidates for inlining.
827 this->visitStatement(&forStmt.fInitializer,
828 /*isViableAsEnclosingStatement=*/false);
829 this->visitStatement(&forStmt.fStatement);
830
831 // The inliner isn't smart enough to inline the test- or increment-expressions
832 // of a for loop loop at this time. There are a handful of limitations:
833 // - We would need to insert the test-expression block at the very beginning of
834 // the for-loop's inner fStatement, and the increment-expression block at the
835 // very end. We don't support that today, but it's doable.
836 // - The for-loop's built-in test-expression would need to be dropped entirely,
837 // and the loop would be halted via a break statement at the end of the
838 // inlined test-expression. This is again something we don't support today,
839 // but it could be implemented.
840 // - We cannot inline the increment-expression if the loop uses `continue`
841 // anywhere; that would skip over the inlined block that evaluates the
842 // increment expression. There isn't a good fix for this--any workaround would
843 // be more complex than the cost of a function call. However, loops that don't
844 // use `continue` would still be viable candidates for increment-expression
845 // inlining.
846 break;
847 }
848 case Statement::Kind::kIf: {
849 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
850 this->visitExpression(&ifStmt.fTest);
851 this->visitStatement(&ifStmt.fIfTrue);
852 this->visitStatement(&ifStmt.fIfFalse);
853 break;
854 }
855 case Statement::Kind::kReturn: {
856 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
857 this->visitExpression(&returnStmt.fExpression);
858 break;
859 }
860 case Statement::Kind::kSwitch: {
861 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
862 if (switchStmt.fSymbols) {
863 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
864 }
865
866 this->visitExpression(&switchStmt.fValue);
867 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
868 // The switch-case's fValue cannot be a FunctionCall; skip it.
869 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
870 this->visitStatement(&caseBlock);
871 }
872 }
873 break;
874 }
875 case Statement::Kind::kVarDeclaration: {
876 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
877 // Don't need to scan the declaration's sizes; those are always IntLiterals.
878 this->visitExpression(&varDeclStmt.fValue);
879 break;
880 }
881 case Statement::Kind::kVarDeclarations: {
882 VarDeclarationsStatement& varDecls = (*stmt)->as<VarDeclarationsStatement>();
883 for (std::unique_ptr<Statement>& varDecl : varDecls.fDeclaration->fVars) {
884 this->visitStatement(&varDecl, /*isViableAsEnclosingStatement=*/false);
885 }
886 break;
887 }
888 case Statement::Kind::kWhile: {
889 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
890 // The loop body is a candidate for inlining.
891 this->visitStatement(&whileStmt.fStatement);
892 // The inliner isn't smart enough to inline the test-expression for a while
893 // loop at this time. There are two limitations:
894 // - We would need to insert the inlined-body block at the very beginning of the
895 // while loop's inner fStatement. We don't support that today, but it's
896 // doable.
897 // - The while-loop's built-in test-expression would need to be replaced with a
898 // `true` BoolLiteral, and the loop would be halted via a break statement at
899 // the end of the inlined test-expression. This is again something we don't
900 // support today, but it could be implemented.
901 break;
902 }
903 default:
904 SkUNREACHABLE;
905 }
906
907 // Pop our symbol and enclosing-statement stacks.
908 fSymbolTableStack.resize(oldSymbolStackSize);
909 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
910 }
911
912 void visitExpression(std::unique_ptr<Expression>* expr) {
913 if (!*expr) {
914 return;
915 }
916
917 switch ((*expr)->kind()) {
918 case Expression::Kind::kBoolLiteral:
919 case Expression::Kind::kDefined:
920 case Expression::Kind::kExternalValue:
921 case Expression::Kind::kFieldAccess:
922 case Expression::Kind::kFloatLiteral:
923 case Expression::Kind::kFunctionReference:
924 case Expression::Kind::kIntLiteral:
925 case Expression::Kind::kNullLiteral:
926 case Expression::Kind::kSetting:
927 case Expression::Kind::kTypeReference:
928 case Expression::Kind::kVariableReference:
929 // Nothing to scan here.
930 break;
931
932 case Expression::Kind::kBinary: {
933 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
934 this->visitExpression(&binaryExpr.fLeft);
935
936 // Logical-and and logical-or binary expressions do not inline the right side,
937 // because that would invalidate short-circuiting. That is, when evaluating
938 // expressions like these:
939 // (false && x()) // always false
940 // (true || y()) // always true
941 // It is illegal for side-effects from x() or y() to occur. The simplest way to
942 // enforce that rule is to avoid inlining the right side entirely. However, it
943 // is safe for other types of binary expression to inline both sides.
944 bool shortCircuitable = (binaryExpr.fOperator == Token::Kind::TK_LOGICALAND ||
945 binaryExpr.fOperator == Token::Kind::TK_LOGICALOR);
946 if (!shortCircuitable) {
947 this->visitExpression(&binaryExpr.fRight);
948 }
949 break;
950 }
951 case Expression::Kind::kConstructor: {
952 Constructor& constructorExpr = (*expr)->as<Constructor>();
953 for (std::unique_ptr<Expression>& arg : constructorExpr.fArguments) {
954 this->visitExpression(&arg);
955 }
956 break;
957 }
958 case Expression::Kind::kExternalFunctionCall: {
959 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
960 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
961 this->visitExpression(&arg);
962 }
963 break;
964 }
965 case Expression::Kind::kFunctionCall: {
966 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
967 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
968 this->visitExpression(&arg);
969 }
970 this->addInlineCandidate(expr);
971 break;
972 }
973 case Expression::Kind::kIndex:{
974 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
975 this->visitExpression(&indexExpr.fBase);
976 this->visitExpression(&indexExpr.fIndex);
977 break;
978 }
979 case Expression::Kind::kPostfix: {
980 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
981 this->visitExpression(&postfixExpr.fOperand);
982 break;
983 }
984 case Expression::Kind::kPrefix: {
985 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
986 this->visitExpression(&prefixExpr.fOperand);
987 break;
988 }
989 case Expression::Kind::kSwizzle: {
990 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
991 this->visitExpression(&swizzleExpr.fBase);
992 break;
993 }
994 case Expression::Kind::kTernary: {
995 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
996 // The test expression is a candidate for inlining.
997 this->visitExpression(&ternaryExpr.fTest);
998 // The true- and false-expressions cannot be inlined, because we are only
999 // allowed to evaluate one side.
1000 break;
1001 }
1002 default:
1003 SkUNREACHABLE;
1004 }
1005 }
1006
1007 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1008 fInlineCandidates.push_back(InlineCandidate{fSymbolTableStack.back(),
John Stiles915a38c2020-09-14 09:38:13 -04001009 find_parent_statement(fEnclosingStmtStack),
1010 fEnclosingStmtStack.back(),
1011 candidate});
John Stiles93442622020-09-11 12:11:27 -04001012 }
1013 };
1014
John Stiles93442622020-09-11 12:11:27 -04001015 InlineCandidateAnalyzer analyzer;
1016 analyzer.visit(program);
John Stiles915a38c2020-09-14 09:38:13 -04001017
1018 // For each of our candidate function-call sites, check if it is actually safe to inline.
1019 // Memoize our results so we don't check a function more than once.
John Stiles93442622020-09-11 12:11:27 -04001020 std::unordered_map<const FunctionDeclaration*, bool> inlinableMap; // <function, safe-to-inline>
John Stiles915a38c2020-09-14 09:38:13 -04001021 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
John Stiles93442622020-09-11 12:11:27 -04001022 const FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1023 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1024 if (inlinableMap.find(funcDecl) == inlinableMap.end()) {
1025 // We do not perform inlining on recursive calls to avoid an infinite death spiral of
1026 // inlining.
1027 int inlineThreshold = (funcDecl->fCallCount.load() > 1) ? fSettings->fInlineThreshold
1028 : INT_MAX;
1029 inlinableMap[funcDecl] = this->isSafeToInline(funcCall, inlineThreshold) &&
1030 !contains_recursive_call(*funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001031 }
1032 }
1033
John Stiles915a38c2020-09-14 09:38:13 -04001034 // Inline the candidates where we've determined that it's safe to do so.
1035 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1036 bool madeChanges = false;
1037 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
1038 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1039 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1040
1041 // If we determined that this candidate was not actually inlinable, skip it.
1042 if (!inlinableMap[funcDecl]) {
1043 continue;
1044 }
1045
1046 // Inlining two expressions using the same enclosing statement in the same inlining pass
1047 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1048 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1049 if (!inserted) {
1050 continue;
1051 }
1052
1053 // Convert the function call to its inlined equivalent.
1054 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols);
1055 if (inlinedCall.fInlinedBody) {
1056 // Ensure that the inlined body has a scope if it needs one.
1057 ensure_scoped_blocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt);
1058
1059 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1060 // function, then replace the enclosing statement with that Block.
1061 // Before:
1062 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1063 // fEnclosingStmt = stmt4
1064 // After:
1065 // fInlinedBody = null
1066 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
1067 inlinedCall.fInlinedBody->fStatements.push_back(std::move(*candidate.fEnclosingStmt));
1068 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1069 }
1070
1071 // Replace the candidate function call with our replacement expression.
1072 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1073 madeChanges = true;
1074
1075 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1076 // remain valid.
1077 }
1078
1079 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001080}
1081
John Stiles44e96be2020-08-31 13:16:04 -04001082} // namespace SkSL