blob: 023c1a094b3c74f35722f503d46d6df2f77abd6e [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
John Stiles44dff4f2020-09-21 12:28:01 -040060static bool contains_returns_above_limit(const FunctionDefinition& funcDef, int limit) {
61 class CountReturnsWithLimit : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040062 public:
John Stiles44dff4f2020-09-21 12:28:01 -040063 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
John Stiles44e96be2020-08-31 13:16:04 -040064 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;
John Stiles44dff4f2020-09-21 12:28:01 -040071 return (fNumReturns > fLimit) || INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040072
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;
John Stiles44dff4f2020-09-21 12:28:01 -040079 int fLimit = 0;
John Stiles44e96be2020-08-31 13:16:04 -040080 using INHERITED = ProgramVisitor;
81 };
82
John Stiles44dff4f2020-09-21 12:28:01 -040083 return CountReturnsWithLimit{funcDef, limit}.fNumReturns > limit;
John Stiles44e96be2020-08-31 13:16:04 -040084}
85
86static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
87 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
88 public:
89 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
90 this->visitProgramElement(funcDef);
91 }
92
93 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040094 switch (stmt.kind()) {
95 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040096 // Check only the last statement of a block.
97 const auto& blockStmts = stmt.as<Block>().fStatements;
98 return (blockStmts.size() > 0) ? this->visitStatement(*blockStmts.back())
99 : false;
100 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400101 case Statement::Kind::kSwitch:
102 case Statement::Kind::kWhile:
103 case Statement::Kind::kDo:
104 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -0400105 // Don't introspect switches or loop structures at all.
106 return false;
107
Ethan Nicholase6592142020-09-08 10:22:09 -0400108 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400109 ++fNumReturns;
110 [[fallthrough]];
111
112 default:
John Stiles93442622020-09-11 12:11:27 -0400113 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400114 }
115 }
116
117 int fNumReturns = 0;
118 using INHERITED = ProgramVisitor;
119 };
120
121 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
122}
123
124static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
125 class CountReturnsInBreakableConstructs : public ProgramVisitor {
126 public:
127 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
128 this->visitProgramElement(funcDef);
129 }
130
131 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400132 switch (stmt.kind()) {
133 case Statement::Kind::kSwitch:
134 case Statement::Kind::kWhile:
135 case Statement::Kind::kDo:
136 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400137 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400138 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400139 --fInsideBreakableConstruct;
140 return result;
141 }
142
Ethan Nicholase6592142020-09-08 10:22:09 -0400143 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400144 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
145 [[fallthrough]];
146
147 default:
John Stiles93442622020-09-11 12:11:27 -0400148 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400149 }
150 }
151
152 int fNumReturns = 0;
153 int fInsideBreakableConstruct = 0;
154 using INHERITED = ProgramVisitor;
155 };
156
157 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
158}
159
160static bool has_early_return(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400161 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
John Stiles44dff4f2020-09-21 12:28:01 -0400162 return contains_returns_above_limit(funcDef, returnsAtEndOfControlFlow);
John Stiles44e96be2020-08-31 13:16:04 -0400163}
164
John Stiles991b09d2020-09-10 13:33:40 -0400165static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
166 class ContainsRecursiveCall : public ProgramVisitor {
167 public:
168 bool visit(const FunctionDeclaration& funcDecl) {
169 fFuncDecl = &funcDecl;
170 return funcDecl.fDefinition ? this->visitProgramElement(*funcDecl.fDefinition)
171 : false;
172 }
173
174 bool visitExpression(const Expression& expr) override {
175 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().fFunction.matches(*fFuncDecl)) {
176 return true;
177 }
178 return INHERITED::visitExpression(expr);
179 }
180
181 bool visitStatement(const Statement& stmt) override {
182 if (stmt.is<InlineMarker>() && stmt.as<InlineMarker>().fFuncDecl->matches(*fFuncDecl)) {
183 return true;
184 }
185 return INHERITED::visitStatement(stmt);
186 }
187
188 const FunctionDeclaration* fFuncDecl;
189 using INHERITED = ProgramVisitor;
190 };
191
192 return ContainsRecursiveCall{}.visit(funcDecl);
193}
194
John Stiles44e96be2020-08-31 13:16:04 -0400195static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400196 if (src->typeKind() == Type::TypeKind::kArray) {
John Stiles44e96be2020-08-31 13:16:04 -0400197 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(*src));
198 }
199 return src;
200}
201
John Stiles915a38c2020-09-14 09:38:13 -0400202static Statement* find_parent_statement(const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
203 SkASSERT(!stmtStack.empty());
204
205 // Walk the statement stack from back to front, ignoring the last element (which is the
206 // enclosing statement).
207 auto iter = stmtStack.rbegin();
208 ++iter;
209
210 // Anything counts as a parent statement other than a scopeless Block.
211 for (; iter != stmtStack.rend(); ++iter) {
212 Statement* stmt = (*iter)->get();
213 if (!stmt->is<Block>() || stmt->as<Block>().fIsScope) {
214 return stmt;
215 }
216 }
217
218 // There wasn't any parent statement to be found.
219 return nullptr;
220}
221
John Stiles44e96be2020-08-31 13:16:04 -0400222} // namespace
223
John Stilesb61ee902020-09-21 12:26:59 -0400224void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
225 // No changes necessary if this statement isn't actually a block.
226 if (!inlinedBody || !inlinedBody->is<Block>()) {
227 return;
228 }
229
230 // No changes necessary if the parent statement doesn't require a scope.
231 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
232 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
233 return;
234 }
235
236 Block& block = inlinedBody->as<Block>();
237
238 // The inliner will create inlined function bodies as a Block containing multiple statements,
239 // but no scope. Normally, this is fine, but if this block is used as the statement for a
240 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
241 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
242 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
243 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
244 // absorbing the following statement into our loop--so we also add a scope to these.
245 for (Block* nestedBlock = &block;; ) {
246 if (nestedBlock->fIsScope) {
247 // We found an explicit scope; all is well.
248 return;
249 }
250 if (nestedBlock->fStatements.size() != 1) {
251 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
252 // to the outermost block.
253 block.fIsScope = true;
254 return;
255 }
256 if (!nestedBlock->fStatements[0]->is<Block>()) {
257 // This block has exactly one thing inside, and it's not another block. No need to scope
258 // it.
259 return;
260 }
261 // We have to go deeper.
262 nestedBlock = &nestedBlock->fStatements[0]->as<Block>();
263 }
264}
265
John Stiles44e96be2020-08-31 13:16:04 -0400266void Inliner::reset(const Context& context, const Program::Settings& settings) {
267 fContext = &context;
268 fSettings = &settings;
269 fInlineVarCounter = 0;
270}
271
John Stilesc75abb82020-09-14 18:24:12 -0400272String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
273 // If the base name starts with an underscore, like "_coords", we can't append another
274 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
275 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
276 // putting in this special case.
277 const char* splitter = baseName.startsWith("_") ? "" : "_";
278
279 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
280 // we're not reusing an existing name. (Note that within a single compilation pass, this check
281 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
282 String uniqueName;
283 for (;;) {
284 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
285 StringFragment frag{uniqueName.data(), uniqueName.length()};
286 if ((*symbolTable)[frag] == nullptr) {
287 break;
288 }
289 }
290
291 return uniqueName;
292}
293
John Stiles44e96be2020-08-31 13:16:04 -0400294std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
295 VariableRewriteMap* varMap,
296 const Expression& expression) {
297 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
298 if (e) {
299 return this->inlineExpression(offset, varMap, *e);
300 }
301 return nullptr;
302 };
303 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
304 -> std::vector<std::unique_ptr<Expression>> {
305 std::vector<std::unique_ptr<Expression>> args;
306 args.reserve(originalArgs.size());
307 for (const std::unique_ptr<Expression>& arg : originalArgs) {
308 args.push_back(expr(arg));
309 }
310 return args;
311 };
312
Ethan Nicholase6592142020-09-08 10:22:09 -0400313 switch (expression.kind()) {
314 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400315 const BinaryExpression& b = expression.as<BinaryExpression>();
316 return std::make_unique<BinaryExpression>(offset,
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000317 expr(b.fLeft),
318 b.fOperator,
319 expr(b.fRight),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400320 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400321 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400322 case Expression::Kind::kBoolLiteral:
323 case Expression::Kind::kIntLiteral:
324 case Expression::Kind::kFloatLiteral:
325 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400326 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400327 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400328 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400329 return std::make_unique<Constructor>(offset, &constructor.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400330 argList(constructor.fArguments));
331 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400332 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400333 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400334 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.type(),
John Stiles44e96be2020-08-31 13:16:04 -0400335 externalCall.fFunction,
336 argList(externalCall.fArguments));
337 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400338 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400339 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400340 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400341 const FieldAccess& f = expression.as<FieldAccess>();
342 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
343 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400344 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400345 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400346 return std::make_unique<FunctionCall>(offset, &funcCall.type(), funcCall.fFunction,
John Stiles44e96be2020-08-31 13:16:04 -0400347 argList(funcCall.fArguments));
348 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400349 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400350 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400351 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400352 const IndexExpression& idx = expression.as<IndexExpression>();
353 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
354 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400355 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400356 const PrefixExpression& p = expression.as<PrefixExpression>();
357 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
358 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400359 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400360 const PostfixExpression& p = expression.as<PostfixExpression>();
361 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
362 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400363 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400364 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400365 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400366 const Swizzle& s = expression.as<Swizzle>();
367 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
368 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400369 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400370 const TernaryExpression& t = expression.as<TernaryExpression>();
371 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
372 expr(t.fIfTrue), expr(t.fIfFalse));
373 }
Brian Osman83ba9302020-09-11 13:33:46 -0400374 case Expression::Kind::kTypeReference:
375 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400376 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400377 const VariableReference& v = expression.as<VariableReference>();
378 auto found = varMap->find(&v.fVariable);
379 if (found != varMap->end()) {
380 return std::make_unique<VariableReference>(offset, *found->second, v.fRefKind);
381 }
382 return v.clone();
383 }
384 default:
385 SkASSERT(false);
386 return nullptr;
387 }
388}
389
390std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
391 VariableRewriteMap* varMap,
392 SymbolTable* symbolTableForStatement,
393 const Variable* returnVar,
394 bool haveEarlyReturns,
395 const Statement& statement) {
396 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
397 if (s) {
398 return this->inlineStatement(offset, varMap, symbolTableForStatement, returnVar,
399 haveEarlyReturns, *s);
400 }
401 return nullptr;
402 };
403 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
404 std::vector<std::unique_ptr<Statement>> result;
405 for (const auto& s : ss) {
406 result.push_back(stmt(s));
407 }
408 return result;
409 };
410 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
411 if (e) {
412 return this->inlineExpression(offset, varMap, *e);
413 }
414 return nullptr;
415 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400416 switch (statement.kind()) {
417 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400418 const Block& b = statement.as<Block>();
419 return std::make_unique<Block>(offset, stmts(b.fStatements), b.fSymbols, b.fIsScope);
420 }
421
Ethan Nicholase6592142020-09-08 10:22:09 -0400422 case Statement::Kind::kBreak:
423 case Statement::Kind::kContinue:
424 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400425 return statement.clone();
426
Ethan Nicholase6592142020-09-08 10:22:09 -0400427 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400428 const DoStatement& d = statement.as<DoStatement>();
429 return std::make_unique<DoStatement>(offset, stmt(d.fStatement), expr(d.fTest));
430 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400431 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400432 const ExpressionStatement& e = statement.as<ExpressionStatement>();
433 return std::make_unique<ExpressionStatement>(expr(e.fExpression));
434 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400435 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400436 const ForStatement& f = statement.as<ForStatement>();
437 // need to ensure initializer is evaluated first so that we've already remapped its
438 // declarations by the time we evaluate test & next
439 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
440 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
441 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
442 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400443 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400444 const IfStatement& i = statement.as<IfStatement>();
445 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
446 stmt(i.fIfTrue), stmt(i.fIfFalse));
447 }
John Stiles98c1f822020-09-09 14:18:53 -0400448 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400449 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400450 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400451 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400452 const ReturnStatement& r = statement.as<ReturnStatement>();
453 if (r.fExpression) {
454 auto assignment = std::make_unique<ExpressionStatement>(
455 std::make_unique<BinaryExpression>(
456 offset,
457 std::make_unique<VariableReference>(offset, *returnVar,
458 VariableReference::kWrite_RefKind),
459 Token::Kind::TK_EQ,
460 expr(r.fExpression),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400461 &returnVar->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400462 if (haveEarlyReturns) {
463 std::vector<std::unique_ptr<Statement>> block;
464 block.push_back(std::move(assignment));
465 block.emplace_back(new BreakStatement(offset));
466 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
467 /*isScope=*/true);
468 } else {
469 return std::move(assignment);
470 }
471 } else {
472 if (haveEarlyReturns) {
473 return std::make_unique<BreakStatement>(offset);
474 } else {
475 return std::make_unique<Nop>();
476 }
477 }
478 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400479 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400480 const SwitchStatement& ss = statement.as<SwitchStatement>();
481 std::vector<std::unique_ptr<SwitchCase>> cases;
482 for (const auto& sc : ss.fCases) {
483 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
484 stmts(sc->fStatements)));
485 }
486 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
487 std::move(cases), ss.fSymbols);
488 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400489 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400490 const VarDeclaration& decl = statement.as<VarDeclaration>();
491 std::vector<std::unique_ptr<Expression>> sizes;
492 for (const auto& size : decl.fSizes) {
493 sizes.push_back(expr(size));
494 }
495 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
496 const Variable* old = decl.fVar;
John Stilesc75abb82020-09-14 18:24:12 -0400497 // We assign unique names to inlined variables--scopes hide most of the problems in this
498 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
499 // names are important.
500 auto name = std::make_unique<String>(
501 this->uniqueNameForInlineVar(String(old->fName), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400502 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas30d30222020-09-11 12:27:26 -0400503 const Type* typePtr = copy_if_needed(&old->type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400504 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
505 std::make_unique<Variable>(offset,
506 old->fModifiers,
507 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400508 typePtr,
John Stiles44e96be2020-08-31 13:16:04 -0400509 old->fStorage,
510 initialValue.get()));
511 (*varMap)[old] = clone;
512 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
513 std::move(initialValue));
514 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400515 case Statement::Kind::kVarDeclarations: {
John Stiles44e96be2020-08-31 13:16:04 -0400516 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
517 std::vector<std::unique_ptr<VarDeclaration>> vars;
518 for (const auto& var : decls.fVars) {
519 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
520 }
521 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
522 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
523 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
524 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400525 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400526 const WhileStatement& w = statement.as<WhileStatement>();
527 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
528 }
529 default:
530 SkASSERT(false);
531 return nullptr;
532 }
533}
534
John Stiles6eadf132020-09-08 10:16:10 -0400535Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles44e96be2020-08-31 13:16:04 -0400536 SymbolTable* symbolTableForCall) {
537 // Inlining is more complicated here than in a typical compiler, because we have to have a
538 // high-level IR and can't just drop statements into the middle of an expression or even use
539 // gotos.
540 //
541 // Since we can't insert statements into an expression, we run the inline function as extra
542 // statements before the statement we're currently processing, relying on a lack of execution
543 // order guarantees. Since we can't use gotos (which are normally used to replace return
544 // statements), we wrap the whole function in a loop and use break statements to jump to the
545 // end.
546 SkASSERT(fSettings);
547 SkASSERT(fContext);
548 SkASSERT(call);
549 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
550
John Stiles44e96be2020-08-31 13:16:04 -0400551 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
John Stiles6eadf132020-09-08 10:16:10 -0400552 const int offset = call->fOffset;
John Stiles44e96be2020-08-31 13:16:04 -0400553 const FunctionDefinition& function = *call->fFunction.fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400554 const bool hasEarlyReturn = has_early_return(function);
555
John Stiles44e96be2020-08-31 13:16:04 -0400556 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400557 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
558 std::vector<std::unique_ptr<Statement>>{},
559 /*symbols=*/nullptr,
560 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400561
John Stiles6eadf132020-09-08 10:16:10 -0400562 std::vector<std::unique_ptr<Statement>>& inlinedBody = inlinedCall.fInlinedBody->fStatements;
John Stiles98c1f822020-09-09 14:18:53 -0400563 inlinedBody.reserve(1 + // Inline marker
564 1 + // Result variable
565 arguments.size() + // Function arguments (passing in)
566 arguments.size() + // Function arguments (copy out-parameters back)
567 1); // Inlined code (either as a Block or do-while loop)
568
569 inlinedBody.push_back(std::make_unique<InlineMarker>(call->fFunction));
John Stiles44e96be2020-08-31 13:16:04 -0400570
John Stilesa003e812020-09-11 09:43:49 -0400571 auto makeInlineVar = [&](const String& baseName, const Type* type, Modifiers modifiers,
John Stiles44e96be2020-08-31 13:16:04 -0400572 std::unique_ptr<Expression>* initialValue) -> const Variable* {
John Stilesa003e812020-09-11 09:43:49 -0400573 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
574 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
575 // somewhere during compilation.
576 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400577 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400578 type = fContext->fFloat_Type.get();
579 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400580 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400581 type = fContext->fInt_Type.get();
582 }
583
John Stilesc75abb82020-09-14 18:24:12 -0400584 // Provide our new variable with a unique name, and add it to our symbol table.
585 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400586 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
587 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400588 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
589
590 // Add our new variable to the symbol table.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400591 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
John Stiles44e96be2020-08-31 13:16:04 -0400592 Variable::kLocal_Storage, initialValue->get());
593 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
594
595 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
596 // initial value).
597 std::vector<std::unique_ptr<VarDeclaration>> variables;
598 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
599 variables.push_back(std::make_unique<VarDeclaration>(
600 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
601 (*initialValue)->clone()));
602 } else {
603 variables.push_back(std::make_unique<VarDeclaration>(
604 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
605 std::move(*initialValue)));
606 }
607
608 // Add the new variable-declaration statement to our block of extra statements.
John Stiles39616ec2020-08-31 14:16:06 -0400609 inlinedBody.push_back(std::make_unique<VarDeclarationsStatement>(
John Stilesa003e812020-09-11 09:43:49 -0400610 std::make_unique<VarDeclarations>(offset, type, std::move(variables))));
John Stiles44e96be2020-08-31 13:16:04 -0400611
612 return variableSymbol;
613 };
614
615 // Create a variable to hold the result in the extra statements (excepting void).
616 const Variable* resultVar = nullptr;
617 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400618 std::unique_ptr<Expression> noInitialValue;
John Stilescf936f92020-08-31 17:18:45 -0400619 resultVar = makeInlineVar(String(function.fDeclaration.fName),
John Stilesa003e812020-09-11 09:43:49 -0400620 &function.fDeclaration.fReturnType, Modifiers{}, &noInitialValue);
John Stiles44e96be2020-08-31 13:16:04 -0400621 }
622
623 // Create variables in the extra statements to hold the arguments, and assign the arguments to
624 // them.
625 VariableRewriteMap varMap;
John Stiles44e96be2020-08-31 13:16:04 -0400626 for (int i = 0; i < (int) arguments.size(); ++i) {
627 const Variable* param = function.fDeclaration.fParameters[i];
628
John Stilesa003e812020-09-11 09:43:49 -0400629 if (arguments[i]->is<VariableReference>()) {
John Stiles44e96be2020-08-31 13:16:04 -0400630 // The argument is just a variable, so we only need to copy it if it's an out parameter
631 // or it's written to within the function.
632 if ((param->fModifiers.fFlags & Modifiers::kOut_Flag) ||
633 !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
634 varMap[param] = &arguments[i]->as<VariableReference>().fVariable;
635 continue;
636 }
637 }
638
Ethan Nicholas30d30222020-09-11 12:27:26 -0400639 varMap[param] = makeInlineVar(String(param->fName), &arguments[i]->type(),
640 param->fModifiers, &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400641 }
642
643 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400644 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
645 inlineBlock->fStatements.reserve(body.fStatements.size());
646 for (const std::unique_ptr<Statement>& stmt : body.fStatements) {
647 inlineBlock->fStatements.push_back(this->inlineStatement(
648 offset, &varMap, symbolTableForCall, resultVar, hasEarlyReturn, *stmt));
649 }
650 if (hasEarlyReturn) {
651 // Since we output to backends that don't have a goto statement (which would normally be
652 // used to perform an early return), we fake it by wrapping the function in a
653 // do { } while (false); and then use break statements to jump to the end in order to
654 // emulate a goto.
John Stiles39616ec2020-08-31 14:16:06 -0400655 inlinedBody.push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400656 /*offset=*/-1,
657 std::move(inlineBlock),
658 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
659 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400660 // No early returns, so we can just dump the code in. We still need to keep the block so we
661 // don't get name conflicts with locals.
John Stiles39616ec2020-08-31 14:16:06 -0400662 inlinedBody.push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400663 }
664
665 // Copy the values of `out` parameters into their destinations.
666 for (size_t i = 0; i < arguments.size(); ++i) {
667 const Variable* p = function.fDeclaration.fParameters[i];
668 if (p->fModifiers.fFlags & Modifiers::kOut_Flag) {
669 SkASSERT(varMap.find(p) != varMap.end());
Ethan Nicholase6592142020-09-08 10:22:09 -0400670 if (arguments[i]->kind() == Expression::Kind::kVariableReference &&
John Stiles44e96be2020-08-31 13:16:04 -0400671 &arguments[i]->as<VariableReference>().fVariable == varMap[p]) {
John Stiles6eadf132020-09-08 10:16:10 -0400672 // We didn't create a temporary for this parameter, so there's nothing to copy back
673 // out.
John Stiles44e96be2020-08-31 13:16:04 -0400674 continue;
675 }
676 auto varRef = std::make_unique<VariableReference>(offset, *varMap[p]);
John Stiles39616ec2020-08-31 14:16:06 -0400677 inlinedBody.push_back(std::make_unique<ExpressionStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400678 std::make_unique<BinaryExpression>(offset,
679 arguments[i]->clone(),
680 Token::Kind::TK_EQ,
681 std::move(varRef),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400682 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400683 }
684 }
685
686 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
687 // Return a reference to the result variable as our replacement expression.
688 inlinedCall.fReplacementExpr = std::make_unique<VariableReference>(offset, *resultVar);
689 } else {
690 // It's a void function, so it doesn't actually result in anything, but we have to return
691 // something non-null as a standin.
692 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
693 /*value=*/false);
694 }
695
John Stiles44e96be2020-08-31 13:16:04 -0400696 return inlinedCall;
697}
698
John Stiles93442622020-09-11 12:11:27 -0400699bool Inliner::isSafeToInline(const FunctionCall& functionCall, int inlineThreshold) {
John Stiles44e96be2020-08-31 13:16:04 -0400700 SkASSERT(fSettings);
701
702 if (functionCall.fFunction.fDefinition == nullptr) {
703 // Can't inline something if we don't actually have its definition.
704 return false;
705 }
706 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
707 if (inlineThreshold < INT_MAX) {
708 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
709 Analysis::NodeCount(functionDef) >= inlineThreshold) {
710 // The function exceeds our maximum inline size and is not flagged 'inline'.
711 return false;
712 }
713 }
John Stiles44e96be2020-08-31 13:16:04 -0400714 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
715 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
716 // can't inline functions that have an early return.
717 bool hasEarlyReturn = has_early_return(functionDef);
718
719 // If we didn't detect an early return, there shouldn't be any returns in breakable
720 // constructs either.
721 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
722 return !hasEarlyReturn;
723 }
724 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
725 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
726 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
727
728 // If we detected returns in breakable constructs, we should also detect an early return.
729 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
730 return !hasReturnInBreakableConstruct;
731}
732
John Stiles93442622020-09-11 12:11:27 -0400733bool Inliner::analyze(Program& program) {
734 // A candidate function for inlining, containing everything that `inlineCall` needs.
735 struct InlineCandidate {
John Stiles915a38c2020-09-14 09:38:13 -0400736 SymbolTable* fSymbols; // the SymbolTable of the candidate
737 Statement* fParentStmt; // the parent Statement of the enclosing stmt
738 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
739 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
John Stiles93442622020-09-11 12:11:27 -0400740 };
741
742 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
743 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
744 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
745 // `const T&`.
746 class InlineCandidateAnalyzer {
747 public:
748 // A list of all the inlining candidates we found during analysis.
749 std::vector<InlineCandidate> fInlineCandidates;
750 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower
751 // than the enclosing-statement stack.
752 std::vector<SymbolTable*> fSymbolTableStack;
753 // A stack of "enclosing" statements--these would be suitable for the inliner to use for
754 // adding new instructions. Not all statements are suitable (e.g. a for-loop's initializer).
755 // The inliner might replace a statement with a block containing the statement.
756 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
757
758 void visit(Program& program) {
759 fSymbolTableStack.push_back(program.fSymbols.get());
760
761 for (ProgramElement& pe : program) {
762 this->visitProgramElement(&pe);
763 }
764
765 fSymbolTableStack.pop_back();
766 }
767
768 void visitProgramElement(ProgramElement* pe) {
769 switch (pe->kind()) {
770 case ProgramElement::Kind::kFunction: {
771 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
772 this->visitStatement(&funcDef.fBody);
773 break;
774 }
775 default:
776 // The inliner can't operate outside of a function's scope.
777 break;
778 }
779 }
780
781 void visitStatement(std::unique_ptr<Statement>* stmt,
782 bool isViableAsEnclosingStatement = true) {
783 if (!*stmt) {
784 return;
785 }
786
787 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
788 size_t oldSymbolStackSize = fSymbolTableStack.size();
789
790 if (isViableAsEnclosingStatement) {
791 fEnclosingStmtStack.push_back(stmt);
792 }
793
794 switch ((*stmt)->kind()) {
795 case Statement::Kind::kBreak:
796 case Statement::Kind::kContinue:
797 case Statement::Kind::kDiscard:
798 case Statement::Kind::kInlineMarker:
799 case Statement::Kind::kNop:
800 break;
801
802 case Statement::Kind::kBlock: {
803 Block& block = (*stmt)->as<Block>();
804 if (block.fSymbols) {
805 fSymbolTableStack.push_back(block.fSymbols.get());
806 }
807
808 for (std::unique_ptr<Statement>& blockStmt : block.fStatements) {
809 this->visitStatement(&blockStmt);
810 }
811 break;
812 }
813 case Statement::Kind::kDo: {
814 DoStatement& doStmt = (*stmt)->as<DoStatement>();
815 // The loop body is a candidate for inlining.
816 this->visitStatement(&doStmt.fStatement);
817 // The inliner isn't smart enough to inline the test-expression for a do-while
818 // loop at this time. There are two limitations:
819 // - We would need to insert the inlined-body block at the very end of the do-
820 // statement's inner fStatement. We don't support that today, but it's doable.
821 // - We cannot inline the test expression if the loop uses `continue` anywhere;
822 // that would skip over the inlined block that evaluates the test expression.
823 // There isn't a good fix for this--any workaround would be more complex than
824 // the cost of a function call. However, loops that don't use `continue` would
825 // still be viable candidates for inlining.
826 break;
827 }
828 case Statement::Kind::kExpression: {
829 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
830 this->visitExpression(&expr.fExpression);
831 break;
832 }
833 case Statement::Kind::kFor: {
834 ForStatement& forStmt = (*stmt)->as<ForStatement>();
835 if (forStmt.fSymbols) {
836 fSymbolTableStack.push_back(forStmt.fSymbols.get());
837 }
838
839 // The initializer and loop body are candidates for inlining.
840 this->visitStatement(&forStmt.fInitializer,
841 /*isViableAsEnclosingStatement=*/false);
842 this->visitStatement(&forStmt.fStatement);
843
844 // The inliner isn't smart enough to inline the test- or increment-expressions
845 // of a for loop loop at this time. There are a handful of limitations:
846 // - We would need to insert the test-expression block at the very beginning of
847 // the for-loop's inner fStatement, and the increment-expression block at the
848 // very end. We don't support that today, but it's doable.
849 // - The for-loop's built-in test-expression would need to be dropped entirely,
850 // and the loop would be halted via a break statement at the end of the
851 // inlined test-expression. This is again something we don't support today,
852 // but it could be implemented.
853 // - We cannot inline the increment-expression if the loop uses `continue`
854 // anywhere; that would skip over the inlined block that evaluates the
855 // increment expression. There isn't a good fix for this--any workaround would
856 // be more complex than the cost of a function call. However, loops that don't
857 // use `continue` would still be viable candidates for increment-expression
858 // inlining.
859 break;
860 }
861 case Statement::Kind::kIf: {
862 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
863 this->visitExpression(&ifStmt.fTest);
864 this->visitStatement(&ifStmt.fIfTrue);
865 this->visitStatement(&ifStmt.fIfFalse);
866 break;
867 }
868 case Statement::Kind::kReturn: {
869 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
870 this->visitExpression(&returnStmt.fExpression);
871 break;
872 }
873 case Statement::Kind::kSwitch: {
874 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
875 if (switchStmt.fSymbols) {
876 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
877 }
878
879 this->visitExpression(&switchStmt.fValue);
880 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
881 // The switch-case's fValue cannot be a FunctionCall; skip it.
882 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
883 this->visitStatement(&caseBlock);
884 }
885 }
886 break;
887 }
888 case Statement::Kind::kVarDeclaration: {
889 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
890 // Don't need to scan the declaration's sizes; those are always IntLiterals.
891 this->visitExpression(&varDeclStmt.fValue);
892 break;
893 }
894 case Statement::Kind::kVarDeclarations: {
895 VarDeclarationsStatement& varDecls = (*stmt)->as<VarDeclarationsStatement>();
896 for (std::unique_ptr<Statement>& varDecl : varDecls.fDeclaration->fVars) {
897 this->visitStatement(&varDecl, /*isViableAsEnclosingStatement=*/false);
898 }
899 break;
900 }
901 case Statement::Kind::kWhile: {
902 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
903 // The loop body is a candidate for inlining.
904 this->visitStatement(&whileStmt.fStatement);
905 // The inliner isn't smart enough to inline the test-expression for a while
906 // loop at this time. There are two limitations:
907 // - We would need to insert the inlined-body block at the very beginning of the
908 // while loop's inner fStatement. We don't support that today, but it's
909 // doable.
910 // - The while-loop's built-in test-expression would need to be replaced with a
911 // `true` BoolLiteral, and the loop would be halted via a break statement at
912 // the end of the inlined test-expression. This is again something we don't
913 // support today, but it could be implemented.
914 break;
915 }
916 default:
917 SkUNREACHABLE;
918 }
919
920 // Pop our symbol and enclosing-statement stacks.
921 fSymbolTableStack.resize(oldSymbolStackSize);
922 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
923 }
924
925 void visitExpression(std::unique_ptr<Expression>* expr) {
926 if (!*expr) {
927 return;
928 }
929
930 switch ((*expr)->kind()) {
931 case Expression::Kind::kBoolLiteral:
932 case Expression::Kind::kDefined:
933 case Expression::Kind::kExternalValue:
934 case Expression::Kind::kFieldAccess:
935 case Expression::Kind::kFloatLiteral:
936 case Expression::Kind::kFunctionReference:
937 case Expression::Kind::kIntLiteral:
938 case Expression::Kind::kNullLiteral:
939 case Expression::Kind::kSetting:
940 case Expression::Kind::kTypeReference:
941 case Expression::Kind::kVariableReference:
942 // Nothing to scan here.
943 break;
944
945 case Expression::Kind::kBinary: {
946 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000947 this->visitExpression(&binaryExpr.fLeft);
John Stiles93442622020-09-11 12:11:27 -0400948
949 // Logical-and and logical-or binary expressions do not inline the right side,
950 // because that would invalidate short-circuiting. That is, when evaluating
951 // expressions like these:
952 // (false && x()) // always false
953 // (true || y()) // always true
954 // It is illegal for side-effects from x() or y() to occur. The simplest way to
955 // enforce that rule is to avoid inlining the right side entirely. However, it
956 // is safe for other types of binary expression to inline both sides.
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000957 bool shortCircuitable = (binaryExpr.fOperator == Token::Kind::TK_LOGICALAND ||
958 binaryExpr.fOperator == Token::Kind::TK_LOGICALOR);
John Stiles93442622020-09-11 12:11:27 -0400959 if (!shortCircuitable) {
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000960 this->visitExpression(&binaryExpr.fRight);
John Stiles93442622020-09-11 12:11:27 -0400961 }
962 break;
963 }
964 case Expression::Kind::kConstructor: {
965 Constructor& constructorExpr = (*expr)->as<Constructor>();
966 for (std::unique_ptr<Expression>& arg : constructorExpr.fArguments) {
967 this->visitExpression(&arg);
968 }
969 break;
970 }
971 case Expression::Kind::kExternalFunctionCall: {
972 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
973 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
974 this->visitExpression(&arg);
975 }
976 break;
977 }
978 case Expression::Kind::kFunctionCall: {
979 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
980 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
981 this->visitExpression(&arg);
982 }
983 this->addInlineCandidate(expr);
984 break;
985 }
986 case Expression::Kind::kIndex:{
987 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
988 this->visitExpression(&indexExpr.fBase);
989 this->visitExpression(&indexExpr.fIndex);
990 break;
991 }
992 case Expression::Kind::kPostfix: {
993 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
994 this->visitExpression(&postfixExpr.fOperand);
995 break;
996 }
997 case Expression::Kind::kPrefix: {
998 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
999 this->visitExpression(&prefixExpr.fOperand);
1000 break;
1001 }
1002 case Expression::Kind::kSwizzle: {
1003 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
1004 this->visitExpression(&swizzleExpr.fBase);
1005 break;
1006 }
1007 case Expression::Kind::kTernary: {
1008 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1009 // The test expression is a candidate for inlining.
1010 this->visitExpression(&ternaryExpr.fTest);
1011 // The true- and false-expressions cannot be inlined, because we are only
1012 // allowed to evaluate one side.
1013 break;
1014 }
1015 default:
1016 SkUNREACHABLE;
1017 }
1018 }
1019
1020 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1021 fInlineCandidates.push_back(InlineCandidate{fSymbolTableStack.back(),
John Stiles915a38c2020-09-14 09:38:13 -04001022 find_parent_statement(fEnclosingStmtStack),
1023 fEnclosingStmtStack.back(),
1024 candidate});
John Stiles93442622020-09-11 12:11:27 -04001025 }
1026 };
1027
John Stiles93442622020-09-11 12:11:27 -04001028 InlineCandidateAnalyzer analyzer;
1029 analyzer.visit(program);
John Stiles915a38c2020-09-14 09:38:13 -04001030
1031 // For each of our candidate function-call sites, check if it is actually safe to inline.
1032 // Memoize our results so we don't check a function more than once.
John Stiles93442622020-09-11 12:11:27 -04001033 std::unordered_map<const FunctionDeclaration*, bool> inlinableMap; // <function, safe-to-inline>
John Stiles915a38c2020-09-14 09:38:13 -04001034 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
John Stiles93442622020-09-11 12:11:27 -04001035 const FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1036 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1037 if (inlinableMap.find(funcDecl) == inlinableMap.end()) {
1038 // We do not perform inlining on recursive calls to avoid an infinite death spiral of
1039 // inlining.
1040 int inlineThreshold = (funcDecl->fCallCount.load() > 1) ? fSettings->fInlineThreshold
1041 : INT_MAX;
1042 inlinableMap[funcDecl] = this->isSafeToInline(funcCall, inlineThreshold) &&
1043 !contains_recursive_call(*funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001044 }
1045 }
1046
John Stiles915a38c2020-09-14 09:38:13 -04001047 // Inline the candidates where we've determined that it's safe to do so.
1048 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1049 bool madeChanges = false;
1050 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
1051 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1052 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1053
1054 // If we determined that this candidate was not actually inlinable, skip it.
1055 if (!inlinableMap[funcDecl]) {
1056 continue;
1057 }
1058
1059 // Inlining two expressions using the same enclosing statement in the same inlining pass
1060 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1061 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1062 if (!inserted) {
1063 continue;
1064 }
1065
1066 // Convert the function call to its inlined equivalent.
1067 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols);
1068 if (inlinedCall.fInlinedBody) {
1069 // Ensure that the inlined body has a scope if it needs one.
John Stilesb61ee902020-09-21 12:26:59 -04001070 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt);
John Stiles915a38c2020-09-14 09:38:13 -04001071
1072 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1073 // function, then replace the enclosing statement with that Block.
1074 // Before:
1075 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1076 // fEnclosingStmt = stmt4
1077 // After:
1078 // fInlinedBody = null
1079 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
1080 inlinedCall.fInlinedBody->fStatements.push_back(std::move(*candidate.fEnclosingStmt));
1081 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1082 }
1083
1084 // Replace the candidate function call with our replacement expression.
1085 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1086 madeChanges = true;
1087
1088 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1089 // remain valid.
1090 }
1091
1092 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001093}
1094
John Stiles44e96be2020-08-31 13:16:04 -04001095} // namespace SkSL