blob: 464855d9e310af6da6ac0df0e9f889cc824a22fe [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
John Stiles2d7973a2020-10-02 15:01:03 -040010#include <limits.h>
John Stiles44e96be2020-08-31 13:16:04 -040011#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"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050025#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040026#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"
John Stiles44e96be2020-08-31 13:16:04 -040041#include "src/sksl/ir/SkSLPostfixExpression.h"
42#include "src/sksl/ir/SkSLPrefixExpression.h"
43#include "src/sksl/ir/SkSLReturnStatement.h"
44#include "src/sksl/ir/SkSLSetting.h"
45#include "src/sksl/ir/SkSLSwitchCase.h"
46#include "src/sksl/ir/SkSLSwitchStatement.h"
47#include "src/sksl/ir/SkSLSwizzle.h"
48#include "src/sksl/ir/SkSLTernaryExpression.h"
49#include "src/sksl/ir/SkSLUnresolvedFunction.h"
50#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040051#include "src/sksl/ir/SkSLVariable.h"
52#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040053
54namespace SkSL {
55namespace {
56
John Stiles031a7672020-11-13 16:13:18 -050057static constexpr int kInlinedStatementLimit = 2500;
58
John Stiles44e96be2020-08-31 13:16:04 -040059static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
60 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
61 public:
62 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
63 this->visitProgramElement(funcDef);
64 }
65
66 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040067 switch (stmt.kind()) {
68 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040069 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040070 const auto& block = stmt.as<Block>();
71 return block.children().size() &&
72 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040073 }
Ethan Nicholase6592142020-09-08 10:22:09 -040074 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040075 case Statement::Kind::kDo:
76 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040077 // Don't introspect switches or loop structures at all.
78 return false;
79
Ethan Nicholase6592142020-09-08 10:22:09 -040080 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040081 ++fNumReturns;
82 [[fallthrough]];
83
84 default:
John Stiles93442622020-09-11 12:11:27 -040085 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040086 }
87 }
88
89 int fNumReturns = 0;
90 using INHERITED = ProgramVisitor;
91 };
92
93 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
94}
95
John Stiles74ebd7e2020-12-17 14:41:50 -050096static int count_returns_in_continuable_constructs(const FunctionDefinition& funcDef) {
97 class CountReturnsInContinuableConstructs : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040098 public:
John Stiles74ebd7e2020-12-17 14:41:50 -050099 CountReturnsInContinuableConstructs(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400100 this->visitProgramElement(funcDef);
101 }
102
103 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400104 switch (stmt.kind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400105 case Statement::Kind::kDo:
106 case Statement::Kind::kFor: {
John Stiles74ebd7e2020-12-17 14:41:50 -0500107 ++fInsideContinuableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400108 bool result = INHERITED::visitStatement(stmt);
John Stiles74ebd7e2020-12-17 14:41:50 -0500109 --fInsideContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400110 return result;
111 }
112
Ethan Nicholase6592142020-09-08 10:22:09 -0400113 case Statement::Kind::kReturn:
John Stiles74ebd7e2020-12-17 14:41:50 -0500114 fNumReturns += (fInsideContinuableConstruct > 0) ? 1 : 0;
John Stiles44e96be2020-08-31 13:16:04 -0400115 [[fallthrough]];
116
117 default:
John Stiles93442622020-09-11 12:11:27 -0400118 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400119 }
120 }
121
122 int fNumReturns = 0;
John Stiles74ebd7e2020-12-17 14:41:50 -0500123 int fInsideContinuableConstruct = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400124 using INHERITED = ProgramVisitor;
125 };
126
John Stiles74ebd7e2020-12-17 14:41:50 -0500127 return CountReturnsInContinuableConstructs{funcDef}.fNumReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400128}
129
John Stiles991b09d2020-09-10 13:33:40 -0400130static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
131 class ContainsRecursiveCall : public ProgramVisitor {
132 public:
133 bool visit(const FunctionDeclaration& funcDecl) {
134 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400135 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
136 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400137 }
138
139 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400140 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400141 return true;
142 }
143 return INHERITED::visitExpression(expr);
144 }
145
146 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400147 if (stmt.is<InlineMarker>() &&
148 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400149 return true;
150 }
151 return INHERITED::visitStatement(stmt);
152 }
153
154 const FunctionDeclaration* fFuncDecl;
155 using INHERITED = ProgramVisitor;
156 };
157
158 return ContainsRecursiveCall{}.visit(funcDecl);
159}
160
John Stiles6d696082020-10-01 10:18:54 -0400161static std::unique_ptr<Statement>* find_parent_statement(
162 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400163 SkASSERT(!stmtStack.empty());
164
165 // Walk the statement stack from back to front, ignoring the last element (which is the
166 // enclosing statement).
167 auto iter = stmtStack.rbegin();
168 ++iter;
169
170 // Anything counts as a parent statement other than a scopeless Block.
171 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400172 std::unique_ptr<Statement>* stmt = *iter;
173 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400174 return stmt;
175 }
176 }
177
178 // There wasn't any parent statement to be found.
179 return nullptr;
180}
181
John Stilese41b4ee2020-09-28 12:28:16 -0400182std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
183 VariableReference::RefKind refKind) {
184 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500185 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400186 return clone;
187}
188
John Stiles77702f12020-12-17 14:38:56 -0500189class CountReturnsWithLimit : public ProgramVisitor {
190public:
191 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
192 this->visitProgramElement(funcDef);
193 }
194
195 bool visitStatement(const Statement& stmt) override {
196 switch (stmt.kind()) {
197 case Statement::Kind::kReturn: {
198 ++fNumReturns;
199 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
200 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
201 }
John Stilesc5ff4862020-12-22 13:47:05 -0500202 case Statement::Kind::kVarDeclaration: {
203 if (fScopedBlockDepth > 1) {
204 fVariablesInBlocks = true;
205 }
206 return INHERITED::visitStatement(stmt);
207 }
John Stiles77702f12020-12-17 14:38:56 -0500208 case Statement::Kind::kBlock: {
209 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
210 fScopedBlockDepth += depthIncrement;
211 bool result = INHERITED::visitStatement(stmt);
212 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500213 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
214 // If closing this block puts us back at the top level, and we haven't
215 // encountered any return statements yet, any vardecls we may have encountered
216 // up until this point can be ignored. They are out of scope now, and they were
217 // never used in a return statement.
218 fVariablesInBlocks = false;
219 }
John Stiles77702f12020-12-17 14:38:56 -0500220 return result;
221 }
222 default:
223 return INHERITED::visitStatement(stmt);
224 }
225 }
226
227 int fNumReturns = 0;
228 int fDeepestReturn = 0;
229 int fLimit = 0;
230 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500231 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500232 using INHERITED = ProgramVisitor;
233};
234
John Stiles44e96be2020-08-31 13:16:04 -0400235} // namespace
236
John Stiles77702f12020-12-17 14:38:56 -0500237Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
238 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
239 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500240 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
241 return ReturnComplexity::kEarlyReturns;
242 }
John Stilesc5ff4862020-12-22 13:47:05 -0500243 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500244 return ReturnComplexity::kScopedReturns;
245 }
John Stilesc5ff4862020-12-22 13:47:05 -0500246 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
247 return ReturnComplexity::kScopedReturns;
248 }
249 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500250}
251
John Stilesb61ee902020-09-21 12:26:59 -0400252void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
253 // No changes necessary if this statement isn't actually a block.
254 if (!inlinedBody || !inlinedBody->is<Block>()) {
255 return;
256 }
257
258 // No changes necessary if the parent statement doesn't require a scope.
259 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500260 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400261 return;
262 }
263
264 Block& block = inlinedBody->as<Block>();
265
266 // The inliner will create inlined function bodies as a Block containing multiple statements,
267 // but no scope. Normally, this is fine, but if this block is used as the statement for a
268 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
269 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
270 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
271 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
272 // absorbing the following statement into our loop--so we also add a scope to these.
273 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400274 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400275 // We found an explicit scope; all is well.
276 return;
277 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400278 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400279 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
280 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400281 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400282 return;
283 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400284 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400285 // This block has exactly one thing inside, and it's not another block. No need to scope
286 // it.
287 return;
288 }
289 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400290 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400291 }
292}
293
John Stilesd1204642021-02-17 16:30:02 -0500294void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400295 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500296 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500297 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400298}
299
300std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
301 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500302 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400303 const Expression& expression) {
304 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
305 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500306 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400307 }
308 return nullptr;
309 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400310 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
311 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400312 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400313 for (const std::unique_ptr<Expression>& arg : originalArgs) {
314 args.push_back(expr(arg));
315 }
316 return args;
317 };
318
Ethan Nicholase6592142020-09-08 10:22:09 -0400319 switch (expression.kind()) {
320 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500321 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilesddcc8432021-01-15 15:32:32 -0500322 return std::make_unique<BinaryExpression>(
323 offset,
324 expr(binaryExpr.left()),
325 binaryExpr.getOperator(),
326 expr(binaryExpr.right()),
327 binaryExpr.type().clone(symbolTableForExpression));
John Stiles44e96be2020-08-31 13:16:04 -0400328 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400329 case Expression::Kind::kBoolLiteral:
330 case Expression::Kind::kIntLiteral:
331 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400332 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400333 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400334 const Constructor& constructor = expression.as<Constructor>();
John Stiles54f00492021-02-19 11:46:10 -0500335 return Constructor::Make(*fContext, offset,
336 *constructor.type().clone(symbolTableForExpression),
337 argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400338 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400339 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400340 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400341 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400342 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400343 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500344 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400345 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400346 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400347 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400348 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400349 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400350 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400351 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilesddcc8432021-01-15 15:32:32 -0500352 return std::make_unique<FunctionCall>(offset,
353 funcCall.type().clone(symbolTableForExpression),
354 &funcCall.function(),
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400355 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400356 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400357 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400358 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400359 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400360 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400361 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
362 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400363 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400364 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400365 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400366 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400367 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400368 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400369 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400370 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400371 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400372 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400373 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400374 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400375 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500376 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400377 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400378 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400379 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400380 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
381 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400382 }
Brian Osman83ba9302020-09-11 13:33:46 -0400383 case Expression::Kind::kTypeReference:
384 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400385 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400386 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400387 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400388 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400389 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400390 }
391 return v.clone();
392 }
393 default:
394 SkASSERT(false);
395 return nullptr;
396 }
397}
398
399std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
400 VariableRewriteMap* varMap,
401 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500402 std::unique_ptr<Expression>* resultExpr,
403 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400404 const Statement& statement,
405 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400406 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
407 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400408 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500409 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400410 }
411 return nullptr;
412 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400413 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400414 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400415 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400416 for (const std::unique_ptr<Statement>& child : block.children()) {
417 result.push_back(stmt(child));
418 }
419 return result;
420 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400421 auto stmts = [&](const StatementArray& ss) {
422 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400423 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400424 for (const auto& s : ss) {
425 result.push_back(stmt(s));
426 }
427 return result;
428 };
429 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
430 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500431 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400432 }
433 return nullptr;
434 };
John Stiles031a7672020-11-13 16:13:18 -0500435
436 ++fInlinedStatementCounter;
437
Ethan Nicholase6592142020-09-08 10:22:09 -0400438 switch (statement.kind()) {
439 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400440 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400441 return std::make_unique<Block>(offset, blockStmts(b),
442 SymbolTable::WrapIfBuiltin(b.symbolTable()),
443 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400444 }
445
Ethan Nicholase6592142020-09-08 10:22:09 -0400446 case Statement::Kind::kBreak:
447 case Statement::Kind::kContinue:
448 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400449 return statement.clone();
450
Ethan Nicholase6592142020-09-08 10:22:09 -0400451 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400452 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400453 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400454 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400455 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400456 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400457 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400458 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400459 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400460 const ForStatement& f = statement.as<ForStatement>();
461 // need to ensure initializer is evaluated first so that we've already remapped its
462 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400463 std::unique_ptr<Statement> initializer = stmt(f.initializer());
464 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400465 expr(f.next()), stmt(f.statement()),
466 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400467 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400468 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400469 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400470 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
471 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400472 }
John Stiles98c1f822020-09-09 14:18:53 -0400473 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400474 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400475 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400476 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400477 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500478 if (!r.expression()) {
479 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
480 // This function doesn't return a value, but has early returns, so we've wrapped
481 // it in a for loop. Use a continue to jump to the end of the loop and "leave"
482 // the function.
John Stiles7b920442020-12-17 10:43:41 -0500483 return std::make_unique<ContinueStatement>(offset);
John Stiles44e96be2020-08-31 13:16:04 -0400484 } else {
John Stiles77702f12020-12-17 14:38:56 -0500485 // This function doesn't exit early or return a value. A return statement at the
486 // end is a no-op and can be treated as such.
John Stiles44e96be2020-08-31 13:16:04 -0400487 return std::make_unique<Nop>();
488 }
489 }
John Stiles77702f12020-12-17 14:38:56 -0500490
John Stilesc5ff4862020-12-22 13:47:05 -0500491 // If a function only contains a single return, and it doesn't reference variables from
492 // inside an Block's scope, we don't need to store the result in a variable at all. Just
493 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500494 SkASSERT(resultExpr);
495 SkASSERT(*resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500496 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500497 *resultExpr = expr(r.expression());
498 return std::make_unique<Nop>();
499 }
500
501 // For more complex functions, assign their result into a variable.
502 auto assignment =
503 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
504 offset,
505 clone_with_ref_kind(**resultExpr, VariableReference::RefKind::kWrite),
506 Token::Kind::TK_EQ,
507 expr(r.expression()),
John Stilesddcc8432021-01-15 15:32:32 -0500508 (*resultExpr)->type().clone(symbolTableForStatement)));
John Stiles77702f12020-12-17 14:38:56 -0500509
510 // Early returns are wrapped in a for loop; we need to synthesize a continue statement
511 // to "leave" the function.
512 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
513 StatementArray block;
514 block.reserve_back(2);
515 block.push_back(std::move(assignment));
516 block.push_back(std::make_unique<ContinueStatement>(offset));
517 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
518 /*isScope=*/true);
519 }
520 // Functions without early returns aren't wrapped in a for loop and don't need to worry
521 // about breaking out of the control flow.
522 return std::move(assignment);
523
John Stiles44e96be2020-08-31 13:16:04 -0400524 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400525 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400526 const SwitchStatement& ss = statement.as<SwitchStatement>();
527 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400528 cases.reserve(ss.cases().size());
529 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
530 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
531 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400532 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400533 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400534 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400535 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400536 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400537 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400538 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000539 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500540 const Variable& variable = decl.var();
541
John Stiles35fee4c2020-12-16 18:25:14 +0000542 // We assign unique names to inlined variables--scopes hide most of the problems in this
543 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
544 // names are important.
John Stilesddcc8432021-01-15 15:32:32 -0500545 auto name = std::make_unique<String>(fMangler.uniqueName(variable.name(),
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500546 symbolTableForStatement));
John Stiles35fee4c2020-12-16 18:25:14 +0000547 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500548 auto clonedVar = std::make_unique<Variable>(
549 offset,
550 &variable.modifiers(),
551 namePtr->c_str(),
552 variable.type().clone(symbolTableForStatement),
553 isBuiltinCode,
554 variable.storage());
555 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
556 auto result = std::make_unique<VarDeclaration>(clonedVar.get(),
John Stilesddcc8432021-01-15 15:32:32 -0500557 decl.baseType().clone(symbolTableForStatement),
558 decl.arraySize(),
John Stiles35fee4c2020-12-16 18:25:14 +0000559 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500560 clonedVar->setDeclaration(result.get());
561 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
562 return std::move(result);
John Stiles44e96be2020-08-31 13:16:04 -0400563 }
John Stiles44e96be2020-08-31 13:16:04 -0400564 default:
565 SkASSERT(false);
566 return nullptr;
567 }
568}
569
John Stiles7b920442020-12-17 10:43:41 -0500570Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
571 const Type* type,
572 SymbolTable* symbolTable,
573 Modifiers modifiers,
574 bool isBuiltinCode,
575 std::unique_ptr<Expression>* initialValue) {
576 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
577 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
578 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500579 if (type->isLiteral()) {
580 SkDEBUGFAIL("found a $literal type while inlining");
581 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500582 }
583
584 // Provide our new variable with a unique name, and add it to our symbol table.
585 const String* namePtr = symbolTable->takeOwnershipOfString(
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500586 std::make_unique<String>(fMangler.uniqueName(baseName, symbolTable)));
John Stiles7b920442020-12-17 10:43:41 -0500587 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
588
589 // Create our new variable and add it to the symbol table.
590 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500591 auto var = std::make_unique<Variable>(/*offset=*/-1,
592 fModifiers->addToPool(Modifiers()),
593 nameFrag,
594 type,
595 isBuiltinCode,
596 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500597
598 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
599 // initial value).
600 if (*initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500601 result.fVarDecl = std::make_unique<VarDeclaration>(var.get(), type, /*arraySize=*/0,
John Stiles7b920442020-12-17 10:43:41 -0500602 (*initialValue)->clone());
603 } else {
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500604 result.fVarDecl = std::make_unique<VarDeclaration>(var.get(), type, /*arraySize=*/0,
John Stiles7b920442020-12-17 10:43:41 -0500605 std::move(*initialValue));
606 }
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500607 var->setDeclaration(&result.fVarDecl->as<VarDeclaration>());
608 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500609 return result;
610}
611
John Stiles6eadf132020-09-08 10:16:10 -0400612Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500613 std::shared_ptr<SymbolTable> symbolTable,
Brian Osman3887a012020-09-30 13:22:27 -0400614 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400615 // Inlining is more complicated here than in a typical compiler, because we have to have a
616 // high-level IR and can't just drop statements into the middle of an expression or even use
617 // gotos.
618 //
619 // Since we can't insert statements into an expression, we run the inline function as extra
620 // statements before the statement we're currently processing, relying on a lack of execution
621 // order guarantees. Since we can't use gotos (which are normally used to replace return
622 // statements), we wrap the whole function in a loop and use break statements to jump to the
623 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400624 SkASSERT(fContext);
625 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400626 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400627
John Stiles8e3b6be2020-10-13 11:14:08 -0400628 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400629 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400630 const FunctionDefinition& function = *call->function().definition();
John Stiles77702f12020-12-17 14:38:56 -0500631 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
632 bool hasEarlyReturn = (returnComplexity >= ReturnComplexity::kEarlyReturns);
John Stiles6eadf132020-09-08 10:16:10 -0400633
John Stiles44e96be2020-08-31 13:16:04 -0400634 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400635 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400636 /*symbols=*/nullptr,
637 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400638
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400639 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400640 inlinedBody.children().reserve_back(
641 1 + // Inline marker
642 1 + // Result variable
643 arguments.size() + // Function arguments (passing in)
644 arguments.size() + // Function arguments (copy out-params back)
John Stiles7b920442020-12-17 10:43:41 -0500645 1); // Block for inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400646
Ethan Nicholasceb62142020-10-09 16:51:18 -0400647 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400648
John Stiles44e96be2020-08-31 13:16:04 -0400649 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400650 std::unique_ptr<Expression> resultExpr;
John Stiles54e7c052021-01-11 14:22:36 -0500651 if (function.declaration().returnType() != *fContext->fTypes.fVoid) {
John Stiles44e96be2020-08-31 13:16:04 -0400652 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500653 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
654 &function.declaration().returnType(),
655 symbolTable.get(), Modifiers{},
656 caller->isBuiltin(), &noInitialValue);
657 inlinedBody.children().push_back(std::move(var.fVarDecl));
658 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles35fee4c2020-12-16 18:25:14 +0000659 }
John Stiles44e96be2020-08-31 13:16:04 -0400660
661 // Create variables in the extra statements to hold the arguments, and assign the arguments to
662 // them.
663 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400664 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400665 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400666 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400667 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400668
John Stiles44733aa2020-09-29 17:42:23 -0400669 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500670 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400671 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400672 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400673 // ... we don't need to copy it at all! We can just use the existing expression.
674 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400675 continue;
676 }
677 }
John Stilese41b4ee2020-09-28 12:28:16 -0400678 if (isOutParam) {
679 argsToCopyBack.push_back(i);
680 }
John Stiles7b920442020-12-17 10:43:41 -0500681 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
682 symbolTable.get(), param->modifiers(),
683 caller->isBuiltin(), &arguments[i]);
684 inlinedBody.children().push_back(std::move(var.fVarDecl));
685 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400686 }
687
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400688 const Block& body = function.body()->as<Block>();
John Stiles7b920442020-12-17 10:43:41 -0500689 StatementArray* inlineStatements;
690
John Stiles44e96be2020-08-31 13:16:04 -0400691 if (hasEarlyReturn) {
692 // Since we output to backends that don't have a goto statement (which would normally be
John Stiles7b920442020-12-17 10:43:41 -0500693 // used to perform an early return), we fake it by wrapping the function in a single-
694 // iteration for loop, and use a continue statement to jump to the end of the loop
695 // prematurely.
696
697 // int _1_loop = 0;
698 symbolTable = std::make_shared<SymbolTable>(std::move(symbolTable), caller->isBuiltin());
John Stiles54e7c052021-01-11 14:22:36 -0500699 const Type* intType = fContext->fTypes.fInt.get();
John Stiles7b920442020-12-17 10:43:41 -0500700 std::unique_ptr<Expression> initialValue = std::make_unique<IntLiteral>(/*offset=*/-1,
701 /*value=*/0,
702 intType);
703 InlineVariable loopVar = this->makeInlineVariable("loop", intType, symbolTable.get(),
704 Modifiers{}, caller->isBuiltin(),
705 &initialValue);
706
707 // _1_loop < 1;
708 std::unique_ptr<Expression> test = std::make_unique<BinaryExpression>(
John Stiles44e96be2020-08-31 13:16:04 -0400709 /*offset=*/-1,
John Stiles7b920442020-12-17 10:43:41 -0500710 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol),
711 Token::Kind::TK_LT,
712 std::make_unique<IntLiteral>(/*offset=*/-1, /*value=*/1, intType),
John Stiles54e7c052021-01-11 14:22:36 -0500713 fContext->fTypes.fBool.get());
John Stiles7b920442020-12-17 10:43:41 -0500714
715 // _1_loop++
716 std::unique_ptr<Expression> increment = std::make_unique<PostfixExpression>(
717 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol,
718 VariableReference::RefKind::kReadWrite),
719 Token::Kind::TK_PLUSPLUS);
720
721 // {...}
722 auto innerBlock = std::make_unique<Block>(offset, StatementArray{},
723 /*symbols=*/nullptr, /*isScope=*/true);
724 inlineStatements = &innerBlock->children();
725
726 // for (int _1_loop = 0; _1_loop < 1; _1_loop++) {...}
727 inlinedBody.children().push_back(std::make_unique<ForStatement>(/*offset=*/-1,
728 std::move(loopVar.fVarDecl),
729 std::move(test),
730 std::move(increment),
731 std::move(innerBlock),
732 symbolTable));
John Stiles44e96be2020-08-31 13:16:04 -0400733 } else {
John Stilesfa9a0832020-12-17 10:43:58 -0500734 // No early returns, so we can just dump the code into our existing scopeless block.
735 inlineStatements = &inlinedBody.children();
John Stiles7b920442020-12-17 10:43:41 -0500736 }
737
738 inlineStatements->reserve_back(body.children().size() + argsToCopyBack.size());
739 for (const std::unique_ptr<Statement>& stmt : body.children()) {
740 inlineStatements->push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles77702f12020-12-17 14:38:56 -0500741 &resultExpr, returnComplexity, *stmt,
John Stiles7b920442020-12-17 10:43:41 -0500742 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400743 }
744
John Stilese41b4ee2020-09-28 12:28:16 -0400745 // Copy back the values of `out` parameters into their real destinations.
746 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400747 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400748 SkASSERT(varMap.find(p) != varMap.end());
John Stiles7b920442020-12-17 10:43:41 -0500749 inlineStatements->push_back(
John Stilese41b4ee2020-09-28 12:28:16 -0400750 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
751 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400752 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400753 Token::Kind::TK_EQ,
754 std::move(varMap[p]),
755 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400756 }
757
John Stilese41b4ee2020-09-28 12:28:16 -0400758 if (resultExpr != nullptr) {
759 // Return our result variable as our replacement expression.
John Stilese41b4ee2020-09-28 12:28:16 -0400760 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400761 } else {
762 // It's a void function, so it doesn't actually result in anything, but we have to return
763 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400764 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
765 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400766 /*value=*/false);
767 }
768
John Stiles44e96be2020-08-31 13:16:04 -0400769 return inlinedCall;
770}
771
John Stiles2d7973a2020-10-02 15:01:03 -0400772bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400773 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500774 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400775 return false;
776 }
777
John Stiles031a7672020-11-13 16:13:18 -0500778 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
779 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
780 return false;
781 }
782
John Stiles2d7973a2020-10-02 15:01:03 -0400783 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400784 // Can't inline something if we don't actually have its definition.
785 return false;
786 }
John Stiles2d7973a2020-10-02 15:01:03 -0400787
John Stiles74ebd7e2020-12-17 14:41:50 -0500788 // We don't have any mechanism to simulate early returns within a construct that supports
789 // continues (for/do/while), so we can't inline if there's a return inside one.
790 bool hasReturnInContinuableConstruct =
791 (count_returns_in_continuable_constructs(*functionDef) > 0);
792 return !hasReturnInContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400793}
794
John Stiles2d7973a2020-10-02 15:01:03 -0400795// A candidate function for inlining, containing everything that `inlineCall` needs.
796struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500797 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400798 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
799 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
800 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
801 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400802};
John Stiles93442622020-09-11 12:11:27 -0400803
John Stiles2d7973a2020-10-02 15:01:03 -0400804struct InlineCandidateList {
805 std::vector<InlineCandidate> fCandidates;
806};
807
808class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400809public:
810 // A list of all the inlining candidates we found during analysis.
811 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400812
John Stiles70957c82020-10-02 16:42:10 -0400813 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
814 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500815 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400816 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
817 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
818 // inliner might replace a statement with a block containing the statement.
819 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
820 // The function that we're currently processing (i.e. inlining into).
821 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400822
Brian Osman0006ad02020-11-18 15:38:39 -0500823 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500824 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500825 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400826 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500827 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400828
Brian Osman0006ad02020-11-18 15:38:39 -0500829 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400830 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400831 }
832
John Stiles70957c82020-10-02 16:42:10 -0400833 fSymbolTableStack.pop_back();
834 fCandidateList = nullptr;
835 }
836
837 void visitProgramElement(ProgramElement* pe) {
838 switch (pe->kind()) {
839 case ProgramElement::Kind::kFunction: {
840 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500841 fEnclosingFunction = &funcDef;
842 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400843 break;
John Stiles93442622020-09-11 12:11:27 -0400844 }
John Stiles70957c82020-10-02 16:42:10 -0400845 default:
846 // The inliner can't operate outside of a function's scope.
847 break;
848 }
849 }
850
851 void visitStatement(std::unique_ptr<Statement>* stmt,
852 bool isViableAsEnclosingStatement = true) {
853 if (!*stmt) {
854 return;
John Stiles93442622020-09-11 12:11:27 -0400855 }
856
John Stiles70957c82020-10-02 16:42:10 -0400857 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
858 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400859
John Stiles70957c82020-10-02 16:42:10 -0400860 if (isViableAsEnclosingStatement) {
861 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400862 }
863
John Stiles70957c82020-10-02 16:42:10 -0400864 switch ((*stmt)->kind()) {
865 case Statement::Kind::kBreak:
866 case Statement::Kind::kContinue:
867 case Statement::Kind::kDiscard:
868 case Statement::Kind::kInlineMarker:
869 case Statement::Kind::kNop:
870 break;
871
872 case Statement::Kind::kBlock: {
873 Block& block = (*stmt)->as<Block>();
874 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500875 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400876 }
877
878 for (std::unique_ptr<Statement>& stmt : block.children()) {
879 this->visitStatement(&stmt);
880 }
881 break;
John Stiles93442622020-09-11 12:11:27 -0400882 }
John Stiles70957c82020-10-02 16:42:10 -0400883 case Statement::Kind::kDo: {
884 DoStatement& doStmt = (*stmt)->as<DoStatement>();
885 // The loop body is a candidate for inlining.
886 this->visitStatement(&doStmt.statement());
887 // The inliner isn't smart enough to inline the test-expression for a do-while
888 // loop at this time. There are two limitations:
889 // - We would need to insert the inlined-body block at the very end of the do-
890 // statement's inner fStatement. We don't support that today, but it's doable.
891 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
892 // would skip over the inlined block that evaluates the test expression. There
893 // isn't a good fix for this--any workaround would be more complex than the cost
894 // of a function call. However, loops that don't use `continue` would still be
895 // viable candidates for inlining.
896 break;
John Stiles93442622020-09-11 12:11:27 -0400897 }
John Stiles70957c82020-10-02 16:42:10 -0400898 case Statement::Kind::kExpression: {
899 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
900 this->visitExpression(&expr.expression());
901 break;
902 }
903 case Statement::Kind::kFor: {
904 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400905 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500906 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400907 }
908
909 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400910 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400911 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400912 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400913
914 // The inliner isn't smart enough to inline the test- or increment-expressions
915 // of a for loop loop at this time. There are a handful of limitations:
916 // - We would need to insert the test-expression block at the very beginning of the
917 // for-loop's inner fStatement, and the increment-expression block at the very
918 // end. We don't support that today, but it's doable.
919 // - The for-loop's built-in test-expression would need to be dropped entirely,
920 // and the loop would be halted via a break statement at the end of the inlined
921 // test-expression. This is again something we don't support today, but it could
922 // be implemented.
923 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
924 // that would skip over the inlined block that evaluates the increment expression.
925 // There isn't a good fix for this--any workaround would be more complex than the
926 // cost of a function call. However, loops that don't use `continue` would still
927 // be viable candidates for increment-expression inlining.
928 break;
929 }
930 case Statement::Kind::kIf: {
931 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400932 this->visitExpression(&ifStmt.test());
933 this->visitStatement(&ifStmt.ifTrue());
934 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400935 break;
936 }
937 case Statement::Kind::kReturn: {
938 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400939 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400940 break;
941 }
942 case Statement::Kind::kSwitch: {
943 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400944 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500945 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400946 }
947
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400948 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400949 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400950 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400951 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -0400952 this->visitStatement(&caseBlock);
953 }
954 }
955 break;
956 }
957 case Statement::Kind::kVarDeclaration: {
958 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
959 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400960 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400961 break;
962 }
John Stiles70957c82020-10-02 16:42:10 -0400963 default:
964 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400965 }
966
John Stiles70957c82020-10-02 16:42:10 -0400967 // Pop our symbol and enclosing-statement stacks.
968 fSymbolTableStack.resize(oldSymbolStackSize);
969 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
970 }
971
972 void visitExpression(std::unique_ptr<Expression>* expr) {
973 if (!*expr) {
974 return;
John Stiles93442622020-09-11 12:11:27 -0400975 }
John Stiles70957c82020-10-02 16:42:10 -0400976
977 switch ((*expr)->kind()) {
978 case Expression::Kind::kBoolLiteral:
979 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500980 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400981 case Expression::Kind::kFieldAccess:
982 case Expression::Kind::kFloatLiteral:
983 case Expression::Kind::kFunctionReference:
984 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400985 case Expression::Kind::kSetting:
986 case Expression::Kind::kTypeReference:
987 case Expression::Kind::kVariableReference:
988 // Nothing to scan here.
989 break;
990
991 case Expression::Kind::kBinary: {
992 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400993 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400994
995 // Logical-and and logical-or binary expressions do not inline the right side,
996 // because that would invalidate short-circuiting. That is, when evaluating
997 // expressions like these:
998 // (false && x()) // always false
999 // (true || y()) // always true
1000 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1001 // enforce that rule is to avoid inlining the right side entirely. However, it is
1002 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -05001003 Operator op = binaryExpr.getOperator();
1004 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
1005 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -04001006 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001007 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001008 }
1009 break;
1010 }
1011 case Expression::Kind::kConstructor: {
1012 Constructor& constructorExpr = (*expr)->as<Constructor>();
1013 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1014 this->visitExpression(&arg);
1015 }
1016 break;
1017 }
1018 case Expression::Kind::kExternalFunctionCall: {
1019 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1020 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1021 this->visitExpression(&arg);
1022 }
1023 break;
1024 }
1025 case Expression::Kind::kFunctionCall: {
1026 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001027 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001028 this->visitExpression(&arg);
1029 }
1030 this->addInlineCandidate(expr);
1031 break;
1032 }
1033 case Expression::Kind::kIndex:{
1034 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001035 this->visitExpression(&indexExpr.base());
1036 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001037 break;
1038 }
1039 case Expression::Kind::kPostfix: {
1040 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001041 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001042 break;
1043 }
1044 case Expression::Kind::kPrefix: {
1045 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001046 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001047 break;
1048 }
1049 case Expression::Kind::kSwizzle: {
1050 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001051 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001052 break;
1053 }
1054 case Expression::Kind::kTernary: {
1055 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1056 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001057 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001058 // The true- and false-expressions cannot be inlined, because we are only allowed to
1059 // evaluate one side.
1060 break;
1061 }
1062 default:
1063 SkUNREACHABLE;
1064 }
1065 }
1066
1067 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1068 fCandidateList->fCandidates.push_back(
1069 InlineCandidate{fSymbolTableStack.back(),
1070 find_parent_statement(fEnclosingStmtStack),
1071 fEnclosingStmtStack.back(),
1072 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001073 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001074 }
John Stiles2d7973a2020-10-02 15:01:03 -04001075};
John Stiles93442622020-09-11 12:11:27 -04001076
John Stiles9b9415e2020-11-23 14:48:06 -05001077static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1078 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1079}
John Stiles915a38c2020-09-14 09:38:13 -04001080
John Stiles9b9415e2020-11-23 14:48:06 -05001081bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1082 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001083 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001084 if (wasInserted) {
1085 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001086 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1087 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001088 }
1089
John Stiles2d7973a2020-10-02 15:01:03 -04001090 return iter->second;
1091}
1092
John Stiles9b9415e2020-11-23 14:48:06 -05001093int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1094 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001095 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001096 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001097 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001098 }
John Stiles2d7973a2020-10-02 15:01:03 -04001099 return iter->second;
1100}
1101
Brian Osman0006ad02020-11-18 15:38:39 -05001102void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001103 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001104 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001105 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1106 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1107 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1108 // `const T&`.
1109 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001110 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001111
John Stiles0ad233f2020-11-25 11:02:05 -05001112 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001113 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001114 if (candidates.empty()) {
1115 return;
1116 }
1117
1118 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001119 InlinabilityCache cache;
1120 candidates.erase(std::remove_if(candidates.begin(),
1121 candidates.end(),
1122 [&](const InlineCandidate& candidate) {
1123 return !this->candidateCanBeInlined(candidate, &cache);
1124 }),
1125 candidates.end());
1126
John Stiles0ad233f2020-11-25 11:02:05 -05001127 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1128 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001129 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001130 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001131 }
John Stiles0ad233f2020-11-25 11:02:05 -05001132
1133 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1134 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1135 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1136 FunctionSizeCache functionSizeCache;
1137 FunctionSizeCache candidateTotalCost;
1138 for (InlineCandidate& candidate : candidates) {
1139 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1140 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1141 }
1142
John Stilesd1204642021-02-17 16:30:02 -05001143 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1144 [&](const InlineCandidate& candidate) {
1145 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1146 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1147 // Functions marked `inline` ignore size limitations.
1148 return false;
1149 }
1150 if (usage->get(fnDecl) == 1) {
1151 // If a function is only used once, it's cost-free to inline.
1152 return false;
1153 }
1154 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1155 // We won't exceed the inline threshold by inlining this.
1156 return false;
1157 }
1158 // Inlining this function will add too many IRNodes.
1159 return true;
1160 }),
1161 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001162}
1163
Brian Osman0006ad02020-11-18 15:38:39 -05001164bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001165 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001166 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001167 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001168 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001169 return false;
1170 }
1171
John Stiles031a7672020-11-13 16:13:18 -05001172 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1173 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1174 return false;
1175 }
1176
John Stiles2d7973a2020-10-02 15:01:03 -04001177 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001178 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001179
John Stiles915a38c2020-09-14 09:38:13 -04001180 // Inline the candidates where we've determined that it's safe to do so.
1181 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1182 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001183 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001184 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001185
1186 // Inlining two expressions using the same enclosing statement in the same inlining pass
1187 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1188 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1189 if (!inserted) {
1190 continue;
1191 }
1192
1193 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001194 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001195 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001196 if (inlinedCall.fInlinedBody) {
1197 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001198 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001199
Brian Osman010ce6a2020-10-19 16:34:10 -04001200 // Add references within the inlined body
1201 usage->add(inlinedCall.fInlinedBody.get());
1202
John Stiles915a38c2020-09-14 09:38:13 -04001203 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1204 // function, then replace the enclosing statement with that Block.
1205 // Before:
1206 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1207 // fEnclosingStmt = stmt4
1208 // After:
1209 // fInlinedBody = null
1210 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001211 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001212 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1213 }
1214
1215 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001216 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001217 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1218 madeChanges = true;
1219
John Stiles031a7672020-11-13 16:13:18 -05001220 // Stop inlining if we've reached our hard cap on new statements.
1221 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1222 break;
1223 }
1224
John Stiles915a38c2020-09-14 09:38:13 -04001225 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1226 // remain valid.
1227 }
1228
1229 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001230}
1231
John Stiles44e96be2020-08-31 13:16:04 -04001232} // namespace SkSL