blob: 950d949cd2305f14c45b610d8760555e020b8738 [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 Stiles70b82422020-09-30 10:55:12 -0400185 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400186 public:
187 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400188 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400189 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400190 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400191 }
192 return INHERITED::visitExpression(expr);
193 }
194
195 private:
196 VariableReference::RefKind fRefKind;
197
John Stiles70b82422020-09-30 10:55:12 -0400198 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400199 };
200
201 SetRefKindInExpression{refKind}.visitExpression(*clone);
202 return clone;
203}
204
John Stiles77702f12020-12-17 14:38:56 -0500205class CountReturnsWithLimit : public ProgramVisitor {
206public:
207 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
208 this->visitProgramElement(funcDef);
209 }
210
211 bool visitStatement(const Statement& stmt) override {
212 switch (stmt.kind()) {
213 case Statement::Kind::kReturn: {
214 ++fNumReturns;
215 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
216 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
217 }
John Stilesc5ff4862020-12-22 13:47:05 -0500218 case Statement::Kind::kVarDeclaration: {
219 if (fScopedBlockDepth > 1) {
220 fVariablesInBlocks = true;
221 }
222 return INHERITED::visitStatement(stmt);
223 }
John Stiles77702f12020-12-17 14:38:56 -0500224 case Statement::Kind::kBlock: {
225 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
226 fScopedBlockDepth += depthIncrement;
227 bool result = INHERITED::visitStatement(stmt);
228 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500229 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
230 // If closing this block puts us back at the top level, and we haven't
231 // encountered any return statements yet, any vardecls we may have encountered
232 // up until this point can be ignored. They are out of scope now, and they were
233 // never used in a return statement.
234 fVariablesInBlocks = false;
235 }
John Stiles77702f12020-12-17 14:38:56 -0500236 return result;
237 }
238 default:
239 return INHERITED::visitStatement(stmt);
240 }
241 }
242
243 int fNumReturns = 0;
244 int fDeepestReturn = 0;
245 int fLimit = 0;
246 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500247 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500248 using INHERITED = ProgramVisitor;
249};
250
John Stiles44e96be2020-08-31 13:16:04 -0400251} // namespace
252
John Stiles77702f12020-12-17 14:38:56 -0500253Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
254 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
255 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500256 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
257 return ReturnComplexity::kEarlyReturns;
258 }
John Stilesc5ff4862020-12-22 13:47:05 -0500259 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500260 return ReturnComplexity::kScopedReturns;
261 }
John Stilesc5ff4862020-12-22 13:47:05 -0500262 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
263 return ReturnComplexity::kScopedReturns;
264 }
265 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500266}
267
John Stilesb61ee902020-09-21 12:26:59 -0400268void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
269 // No changes necessary if this statement isn't actually a block.
270 if (!inlinedBody || !inlinedBody->is<Block>()) {
271 return;
272 }
273
274 // No changes necessary if the parent statement doesn't require a scope.
275 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500276 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400277 return;
278 }
279
280 Block& block = inlinedBody->as<Block>();
281
282 // The inliner will create inlined function bodies as a Block containing multiple statements,
283 // but no scope. Normally, this is fine, but if this block is used as the statement for a
284 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
285 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
286 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
287 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
288 // absorbing the following statement into our loop--so we also add a scope to these.
289 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400290 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400291 // We found an explicit scope; all is well.
292 return;
293 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400294 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400295 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
296 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400297 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400298 return;
299 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400300 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400301 // This block has exactly one thing inside, and it's not another block. No need to scope
302 // it.
303 return;
304 }
305 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400306 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400307 }
308}
309
Brian Osman0006ad02020-11-18 15:38:39 -0500310void Inliner::reset(ModifiersPool* modifiers, const Program::Settings* settings) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400311 fModifiers = modifiers;
312 fSettings = settings;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500313 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500314 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400315}
316
317std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
318 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500319 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400320 const Expression& expression) {
321 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
322 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500323 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400324 }
325 return nullptr;
326 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400327 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
328 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400329 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400330 for (const std::unique_ptr<Expression>& arg : originalArgs) {
331 args.push_back(expr(arg));
332 }
333 return args;
334 };
335
Ethan Nicholase6592142020-09-08 10:22:09 -0400336 switch (expression.kind()) {
337 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500338 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilesddcc8432021-01-15 15:32:32 -0500339 return std::make_unique<BinaryExpression>(
340 offset,
341 expr(binaryExpr.left()),
342 binaryExpr.getOperator(),
343 expr(binaryExpr.right()),
344 binaryExpr.type().clone(symbolTableForExpression));
John Stiles44e96be2020-08-31 13:16:04 -0400345 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400346 case Expression::Kind::kBoolLiteral:
347 case Expression::Kind::kIntLiteral:
348 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400349 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400350 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400351 const Constructor& constructor = expression.as<Constructor>();
John Stilesddcc8432021-01-15 15:32:32 -0500352 return std::make_unique<Constructor>(offset,
353 constructor.type().clone(symbolTableForExpression),
354 argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400355 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400356 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400357 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400358 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400359 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400360 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500361 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400362 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400363 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400364 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400365 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400366 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400367 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400368 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilesddcc8432021-01-15 15:32:32 -0500369 return std::make_unique<FunctionCall>(offset,
370 funcCall.type().clone(symbolTableForExpression),
371 &funcCall.function(),
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400372 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400373 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400374 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400375 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400376 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400377 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400378 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
379 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400380 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400381 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400382 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400383 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400384 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400385 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400386 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400387 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400388 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400389 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400390 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400391 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400392 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400393 return std::make_unique<Swizzle>(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400394 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400395 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400396 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400397 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
398 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400399 }
Brian Osman83ba9302020-09-11 13:33:46 -0400400 case Expression::Kind::kTypeReference:
401 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400402 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400403 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400404 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400405 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400406 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400407 }
408 return v.clone();
409 }
410 default:
411 SkASSERT(false);
412 return nullptr;
413 }
414}
415
416std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
417 VariableRewriteMap* varMap,
418 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500419 std::unique_ptr<Expression>* resultExpr,
420 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400421 const Statement& statement,
422 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400423 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
424 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400425 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500426 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400427 }
428 return nullptr;
429 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400430 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400431 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400432 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400433 for (const std::unique_ptr<Statement>& child : block.children()) {
434 result.push_back(stmt(child));
435 }
436 return result;
437 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400438 auto stmts = [&](const StatementArray& ss) {
439 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400440 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400441 for (const auto& s : ss) {
442 result.push_back(stmt(s));
443 }
444 return result;
445 };
446 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
447 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500448 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400449 }
450 return nullptr;
451 };
John Stiles031a7672020-11-13 16:13:18 -0500452
453 ++fInlinedStatementCounter;
454
Ethan Nicholase6592142020-09-08 10:22:09 -0400455 switch (statement.kind()) {
456 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400457 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400458 return std::make_unique<Block>(offset, blockStmts(b),
459 SymbolTable::WrapIfBuiltin(b.symbolTable()),
460 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400461 }
462
Ethan Nicholase6592142020-09-08 10:22:09 -0400463 case Statement::Kind::kBreak:
464 case Statement::Kind::kContinue:
465 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400466 return statement.clone();
467
Ethan Nicholase6592142020-09-08 10:22:09 -0400468 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400469 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400470 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400471 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400472 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400473 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400474 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400475 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400476 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400477 const ForStatement& f = statement.as<ForStatement>();
478 // need to ensure initializer is evaluated first so that we've already remapped its
479 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400480 std::unique_ptr<Statement> initializer = stmt(f.initializer());
481 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400482 expr(f.next()), stmt(f.statement()),
483 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400484 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400485 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400486 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400487 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
488 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400489 }
John Stiles98c1f822020-09-09 14:18:53 -0400490 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400491 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400492 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400493 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400494 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500495 if (!r.expression()) {
496 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
497 // This function doesn't return a value, but has early returns, so we've wrapped
498 // it in a for loop. Use a continue to jump to the end of the loop and "leave"
499 // the function.
John Stiles7b920442020-12-17 10:43:41 -0500500 return std::make_unique<ContinueStatement>(offset);
John Stiles44e96be2020-08-31 13:16:04 -0400501 } else {
John Stiles77702f12020-12-17 14:38:56 -0500502 // This function doesn't exit early or return a value. A return statement at the
503 // end is a no-op and can be treated as such.
John Stiles44e96be2020-08-31 13:16:04 -0400504 return std::make_unique<Nop>();
505 }
506 }
John Stiles77702f12020-12-17 14:38:56 -0500507
John Stilesc5ff4862020-12-22 13:47:05 -0500508 // If a function only contains a single return, and it doesn't reference variables from
509 // inside an Block's scope, we don't need to store the result in a variable at all. Just
510 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500511 SkASSERT(resultExpr);
512 SkASSERT(*resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500513 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500514 *resultExpr = expr(r.expression());
515 return std::make_unique<Nop>();
516 }
517
518 // For more complex functions, assign their result into a variable.
519 auto assignment =
520 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
521 offset,
522 clone_with_ref_kind(**resultExpr, VariableReference::RefKind::kWrite),
523 Token::Kind::TK_EQ,
524 expr(r.expression()),
John Stilesddcc8432021-01-15 15:32:32 -0500525 (*resultExpr)->type().clone(symbolTableForStatement)));
John Stiles77702f12020-12-17 14:38:56 -0500526
527 // Early returns are wrapped in a for loop; we need to synthesize a continue statement
528 // to "leave" the function.
529 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
530 StatementArray block;
531 block.reserve_back(2);
532 block.push_back(std::move(assignment));
533 block.push_back(std::make_unique<ContinueStatement>(offset));
534 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
535 /*isScope=*/true);
536 }
537 // Functions without early returns aren't wrapped in a for loop and don't need to worry
538 // about breaking out of the control flow.
539 return std::move(assignment);
540
John Stiles44e96be2020-08-31 13:16:04 -0400541 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400542 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400543 const SwitchStatement& ss = statement.as<SwitchStatement>();
544 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400545 cases.reserve(ss.cases().size());
546 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
547 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
548 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400549 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400550 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400551 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400552 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400553 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400554 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400555 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000556 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500557 const Variable& variable = decl.var();
558
John Stiles35fee4c2020-12-16 18:25:14 +0000559 // We assign unique names to inlined variables--scopes hide most of the problems in this
560 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
561 // names are important.
John Stilesddcc8432021-01-15 15:32:32 -0500562 auto name = std::make_unique<String>(fMangler.uniqueName(variable.name(),
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500563 symbolTableForStatement));
John Stiles35fee4c2020-12-16 18:25:14 +0000564 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
John Stilesddcc8432021-01-15 15:32:32 -0500565 const Variable* clonedVar = symbolTableForStatement->takeOwnershipOfSymbol(
John Stiles35fee4c2020-12-16 18:25:14 +0000566 std::make_unique<Variable>(offset,
John Stilesddcc8432021-01-15 15:32:32 -0500567 &variable.modifiers(),
John Stiles35fee4c2020-12-16 18:25:14 +0000568 namePtr->c_str(),
John Stilesddcc8432021-01-15 15:32:32 -0500569 variable.type().clone(symbolTableForStatement),
John Stiles35fee4c2020-12-16 18:25:14 +0000570 isBuiltinCode,
John Stilesddcc8432021-01-15 15:32:32 -0500571 variable.storage(),
John Stiles35fee4c2020-12-16 18:25:14 +0000572 initialValue.get()));
John Stilesddcc8432021-01-15 15:32:32 -0500573 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar);
574 return std::make_unique<VarDeclaration>(clonedVar,
575 decl.baseType().clone(symbolTableForStatement),
576 decl.arraySize(),
John Stiles35fee4c2020-12-16 18:25:14 +0000577 std::move(initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400578 }
John Stiles44e96be2020-08-31 13:16:04 -0400579 default:
580 SkASSERT(false);
581 return nullptr;
582 }
583}
584
John Stiles7b920442020-12-17 10:43:41 -0500585Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
586 const Type* type,
587 SymbolTable* symbolTable,
588 Modifiers modifiers,
589 bool isBuiltinCode,
590 std::unique_ptr<Expression>* initialValue) {
591 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
592 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
593 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500594 if (type->isLiteral()) {
595 SkDEBUGFAIL("found a $literal type while inlining");
596 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500597 }
598
599 // Provide our new variable with a unique name, and add it to our symbol table.
600 const String* namePtr = symbolTable->takeOwnershipOfString(
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500601 std::make_unique<String>(fMangler.uniqueName(baseName, symbolTable)));
John Stiles7b920442020-12-17 10:43:41 -0500602 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
603
604 // Create our new variable and add it to the symbol table.
605 InlineVariable result;
606 result.fVarSymbol =
607 symbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
608 fModifiers->addToPool(Modifiers()),
609 nameFrag,
610 type,
611 isBuiltinCode,
612 Variable::Storage::kLocal,
613 initialValue->get()));
614
615 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
616 // initial value).
617 if (*initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
618 result.fVarDecl = std::make_unique<VarDeclaration>(result.fVarSymbol, type, /*arraySize=*/0,
619 (*initialValue)->clone());
620 } else {
621 result.fVarDecl = std::make_unique<VarDeclaration>(result.fVarSymbol, type, /*arraySize=*/0,
622 std::move(*initialValue));
623 }
624 return result;
625}
626
John Stiles6eadf132020-09-08 10:16:10 -0400627Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500628 std::shared_ptr<SymbolTable> symbolTable,
Brian Osman3887a012020-09-30 13:22:27 -0400629 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400630 // Inlining is more complicated here than in a typical compiler, because we have to have a
631 // high-level IR and can't just drop statements into the middle of an expression or even use
632 // gotos.
633 //
634 // Since we can't insert statements into an expression, we run the inline function as extra
635 // statements before the statement we're currently processing, relying on a lack of execution
636 // order guarantees. Since we can't use gotos (which are normally used to replace return
637 // statements), we wrap the whole function in a loop and use break statements to jump to the
638 // end.
639 SkASSERT(fSettings);
640 SkASSERT(fContext);
641 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400642 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400643
John Stiles8e3b6be2020-10-13 11:14:08 -0400644 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400645 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400646 const FunctionDefinition& function = *call->function().definition();
John Stiles77702f12020-12-17 14:38:56 -0500647 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
648 bool hasEarlyReturn = (returnComplexity >= ReturnComplexity::kEarlyReturns);
John Stiles6eadf132020-09-08 10:16:10 -0400649
John Stiles44e96be2020-08-31 13:16:04 -0400650 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400651 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400652 /*symbols=*/nullptr,
653 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400654
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400655 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400656 inlinedBody.children().reserve_back(
657 1 + // Inline marker
658 1 + // Result variable
659 arguments.size() + // Function arguments (passing in)
660 arguments.size() + // Function arguments (copy out-params back)
John Stiles7b920442020-12-17 10:43:41 -0500661 1); // Block for inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400662
Ethan Nicholasceb62142020-10-09 16:51:18 -0400663 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400664
John Stiles44e96be2020-08-31 13:16:04 -0400665 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400666 std::unique_ptr<Expression> resultExpr;
John Stiles54e7c052021-01-11 14:22:36 -0500667 if (function.declaration().returnType() != *fContext->fTypes.fVoid) {
John Stiles44e96be2020-08-31 13:16:04 -0400668 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500669 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
670 &function.declaration().returnType(),
671 symbolTable.get(), Modifiers{},
672 caller->isBuiltin(), &noInitialValue);
673 inlinedBody.children().push_back(std::move(var.fVarDecl));
674 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles35fee4c2020-12-16 18:25:14 +0000675 }
John Stiles44e96be2020-08-31 13:16:04 -0400676
677 // Create variables in the extra statements to hold the arguments, and assign the arguments to
678 // them.
679 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400680 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400681 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400682 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400683 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400684
John Stiles44733aa2020-09-29 17:42:23 -0400685 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500686 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400687 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400688 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400689 // ... we don't need to copy it at all! We can just use the existing expression.
690 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400691 continue;
692 }
693 }
John Stilese41b4ee2020-09-28 12:28:16 -0400694 if (isOutParam) {
695 argsToCopyBack.push_back(i);
696 }
John Stiles7b920442020-12-17 10:43:41 -0500697 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
698 symbolTable.get(), param->modifiers(),
699 caller->isBuiltin(), &arguments[i]);
700 inlinedBody.children().push_back(std::move(var.fVarDecl));
701 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400702 }
703
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400704 const Block& body = function.body()->as<Block>();
John Stiles7b920442020-12-17 10:43:41 -0500705 StatementArray* inlineStatements;
706
John Stiles44e96be2020-08-31 13:16:04 -0400707 if (hasEarlyReturn) {
708 // Since we output to backends that don't have a goto statement (which would normally be
John Stiles7b920442020-12-17 10:43:41 -0500709 // used to perform an early return), we fake it by wrapping the function in a single-
710 // iteration for loop, and use a continue statement to jump to the end of the loop
711 // prematurely.
712
713 // int _1_loop = 0;
714 symbolTable = std::make_shared<SymbolTable>(std::move(symbolTable), caller->isBuiltin());
John Stiles54e7c052021-01-11 14:22:36 -0500715 const Type* intType = fContext->fTypes.fInt.get();
John Stiles7b920442020-12-17 10:43:41 -0500716 std::unique_ptr<Expression> initialValue = std::make_unique<IntLiteral>(/*offset=*/-1,
717 /*value=*/0,
718 intType);
719 InlineVariable loopVar = this->makeInlineVariable("loop", intType, symbolTable.get(),
720 Modifiers{}, caller->isBuiltin(),
721 &initialValue);
722
723 // _1_loop < 1;
724 std::unique_ptr<Expression> test = std::make_unique<BinaryExpression>(
John Stiles44e96be2020-08-31 13:16:04 -0400725 /*offset=*/-1,
John Stiles7b920442020-12-17 10:43:41 -0500726 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol),
727 Token::Kind::TK_LT,
728 std::make_unique<IntLiteral>(/*offset=*/-1, /*value=*/1, intType),
John Stiles54e7c052021-01-11 14:22:36 -0500729 fContext->fTypes.fBool.get());
John Stiles7b920442020-12-17 10:43:41 -0500730
731 // _1_loop++
732 std::unique_ptr<Expression> increment = std::make_unique<PostfixExpression>(
733 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol,
734 VariableReference::RefKind::kReadWrite),
735 Token::Kind::TK_PLUSPLUS);
736
737 // {...}
738 auto innerBlock = std::make_unique<Block>(offset, StatementArray{},
739 /*symbols=*/nullptr, /*isScope=*/true);
740 inlineStatements = &innerBlock->children();
741
742 // for (int _1_loop = 0; _1_loop < 1; _1_loop++) {...}
743 inlinedBody.children().push_back(std::make_unique<ForStatement>(/*offset=*/-1,
744 std::move(loopVar.fVarDecl),
745 std::move(test),
746 std::move(increment),
747 std::move(innerBlock),
748 symbolTable));
John Stiles44e96be2020-08-31 13:16:04 -0400749 } else {
John Stilesfa9a0832020-12-17 10:43:58 -0500750 // No early returns, so we can just dump the code into our existing scopeless block.
751 inlineStatements = &inlinedBody.children();
John Stiles7b920442020-12-17 10:43:41 -0500752 }
753
754 inlineStatements->reserve_back(body.children().size() + argsToCopyBack.size());
755 for (const std::unique_ptr<Statement>& stmt : body.children()) {
756 inlineStatements->push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles77702f12020-12-17 14:38:56 -0500757 &resultExpr, returnComplexity, *stmt,
John Stiles7b920442020-12-17 10:43:41 -0500758 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400759 }
760
John Stilese41b4ee2020-09-28 12:28:16 -0400761 // Copy back the values of `out` parameters into their real destinations.
762 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400763 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400764 SkASSERT(varMap.find(p) != varMap.end());
John Stiles7b920442020-12-17 10:43:41 -0500765 inlineStatements->push_back(
John Stilese41b4ee2020-09-28 12:28:16 -0400766 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
767 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400768 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400769 Token::Kind::TK_EQ,
770 std::move(varMap[p]),
771 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400772 }
773
John Stilese41b4ee2020-09-28 12:28:16 -0400774 if (resultExpr != nullptr) {
775 // Return our result variable as our replacement expression.
John Stilese41b4ee2020-09-28 12:28:16 -0400776 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400777 } else {
778 // It's a void function, so it doesn't actually result in anything, but we have to return
779 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400780 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
781 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400782 /*value=*/false);
783 }
784
John Stiles44e96be2020-08-31 13:16:04 -0400785 return inlinedCall;
786}
787
John Stiles2d7973a2020-10-02 15:01:03 -0400788bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400789 SkASSERT(fSettings);
790
John Stiles1c03d332020-10-13 10:30:23 -0400791 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
792 if (fSettings->fInlineThreshold <= 0) {
793 return false;
794 }
795
John Stiles031a7672020-11-13 16:13:18 -0500796 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
797 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
798 return false;
799 }
800
John Stiles2d7973a2020-10-02 15:01:03 -0400801 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400802 // Can't inline something if we don't actually have its definition.
803 return false;
804 }
John Stiles2d7973a2020-10-02 15:01:03 -0400805
John Stiles74ebd7e2020-12-17 14:41:50 -0500806 // We don't have any mechanism to simulate early returns within a construct that supports
807 // continues (for/do/while), so we can't inline if there's a return inside one.
808 bool hasReturnInContinuableConstruct =
809 (count_returns_in_continuable_constructs(*functionDef) > 0);
810 return !hasReturnInContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400811}
812
John Stiles2d7973a2020-10-02 15:01:03 -0400813// A candidate function for inlining, containing everything that `inlineCall` needs.
814struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500815 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400816 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
817 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
818 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
819 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400820};
John Stiles93442622020-09-11 12:11:27 -0400821
John Stiles2d7973a2020-10-02 15:01:03 -0400822struct InlineCandidateList {
823 std::vector<InlineCandidate> fCandidates;
824};
825
826class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400827public:
828 // A list of all the inlining candidates we found during analysis.
829 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400830
John Stiles70957c82020-10-02 16:42:10 -0400831 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
832 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500833 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400834 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
835 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
836 // inliner might replace a statement with a block containing the statement.
837 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
838 // The function that we're currently processing (i.e. inlining into).
839 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400840
Brian Osman0006ad02020-11-18 15:38:39 -0500841 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500842 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500843 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400844 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500845 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400846
Brian Osman0006ad02020-11-18 15:38:39 -0500847 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400848 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400849 }
850
John Stiles70957c82020-10-02 16:42:10 -0400851 fSymbolTableStack.pop_back();
852 fCandidateList = nullptr;
853 }
854
855 void visitProgramElement(ProgramElement* pe) {
856 switch (pe->kind()) {
857 case ProgramElement::Kind::kFunction: {
858 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500859 fEnclosingFunction = &funcDef;
860 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400861 break;
John Stiles93442622020-09-11 12:11:27 -0400862 }
John Stiles70957c82020-10-02 16:42:10 -0400863 default:
864 // The inliner can't operate outside of a function's scope.
865 break;
866 }
867 }
868
869 void visitStatement(std::unique_ptr<Statement>* stmt,
870 bool isViableAsEnclosingStatement = true) {
871 if (!*stmt) {
872 return;
John Stiles93442622020-09-11 12:11:27 -0400873 }
874
John Stiles70957c82020-10-02 16:42:10 -0400875 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
876 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400877
John Stiles70957c82020-10-02 16:42:10 -0400878 if (isViableAsEnclosingStatement) {
879 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400880 }
881
John Stiles70957c82020-10-02 16:42:10 -0400882 switch ((*stmt)->kind()) {
883 case Statement::Kind::kBreak:
884 case Statement::Kind::kContinue:
885 case Statement::Kind::kDiscard:
886 case Statement::Kind::kInlineMarker:
887 case Statement::Kind::kNop:
888 break;
889
890 case Statement::Kind::kBlock: {
891 Block& block = (*stmt)->as<Block>();
892 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500893 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400894 }
895
896 for (std::unique_ptr<Statement>& stmt : block.children()) {
897 this->visitStatement(&stmt);
898 }
899 break;
John Stiles93442622020-09-11 12:11:27 -0400900 }
John Stiles70957c82020-10-02 16:42:10 -0400901 case Statement::Kind::kDo: {
902 DoStatement& doStmt = (*stmt)->as<DoStatement>();
903 // The loop body is a candidate for inlining.
904 this->visitStatement(&doStmt.statement());
905 // The inliner isn't smart enough to inline the test-expression for a do-while
906 // loop at this time. There are two limitations:
907 // - We would need to insert the inlined-body block at the very end of the do-
908 // statement's inner fStatement. We don't support that today, but it's doable.
909 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
910 // would skip over the inlined block that evaluates the test expression. There
911 // isn't a good fix for this--any workaround would be more complex than the cost
912 // of a function call. However, loops that don't use `continue` would still be
913 // viable candidates for inlining.
914 break;
John Stiles93442622020-09-11 12:11:27 -0400915 }
John Stiles70957c82020-10-02 16:42:10 -0400916 case Statement::Kind::kExpression: {
917 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
918 this->visitExpression(&expr.expression());
919 break;
920 }
921 case Statement::Kind::kFor: {
922 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400923 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500924 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400925 }
926
927 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400928 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400929 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400930 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400931
932 // The inliner isn't smart enough to inline the test- or increment-expressions
933 // of a for loop loop at this time. There are a handful of limitations:
934 // - We would need to insert the test-expression block at the very beginning of the
935 // for-loop's inner fStatement, and the increment-expression block at the very
936 // end. We don't support that today, but it's doable.
937 // - The for-loop's built-in test-expression would need to be dropped entirely,
938 // and the loop would be halted via a break statement at the end of the inlined
939 // test-expression. This is again something we don't support today, but it could
940 // be implemented.
941 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
942 // that would skip over the inlined block that evaluates the increment expression.
943 // There isn't a good fix for this--any workaround would be more complex than the
944 // cost of a function call. However, loops that don't use `continue` would still
945 // be viable candidates for increment-expression inlining.
946 break;
947 }
948 case Statement::Kind::kIf: {
949 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400950 this->visitExpression(&ifStmt.test());
951 this->visitStatement(&ifStmt.ifTrue());
952 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400953 break;
954 }
955 case Statement::Kind::kReturn: {
956 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400957 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400958 break;
959 }
960 case Statement::Kind::kSwitch: {
961 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400962 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500963 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400964 }
965
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400966 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400967 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400968 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400969 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -0400970 this->visitStatement(&caseBlock);
971 }
972 }
973 break;
974 }
975 case Statement::Kind::kVarDeclaration: {
976 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
977 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400978 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400979 break;
980 }
John Stiles70957c82020-10-02 16:42:10 -0400981 default:
982 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400983 }
984
John Stiles70957c82020-10-02 16:42:10 -0400985 // Pop our symbol and enclosing-statement stacks.
986 fSymbolTableStack.resize(oldSymbolStackSize);
987 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
988 }
989
990 void visitExpression(std::unique_ptr<Expression>* expr) {
991 if (!*expr) {
992 return;
John Stiles93442622020-09-11 12:11:27 -0400993 }
John Stiles70957c82020-10-02 16:42:10 -0400994
995 switch ((*expr)->kind()) {
996 case Expression::Kind::kBoolLiteral:
997 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500998 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400999 case Expression::Kind::kFieldAccess:
1000 case Expression::Kind::kFloatLiteral:
1001 case Expression::Kind::kFunctionReference:
1002 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -04001003 case Expression::Kind::kSetting:
1004 case Expression::Kind::kTypeReference:
1005 case Expression::Kind::kVariableReference:
1006 // Nothing to scan here.
1007 break;
1008
1009 case Expression::Kind::kBinary: {
1010 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001011 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -04001012
1013 // Logical-and and logical-or binary expressions do not inline the right side,
1014 // because that would invalidate short-circuiting. That is, when evaluating
1015 // expressions like these:
1016 // (false && x()) // always false
1017 // (true || y()) // always true
1018 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1019 // enforce that rule is to avoid inlining the right side entirely. However, it is
1020 // safe for other types of binary expression to inline both sides.
1021 Token::Kind op = binaryExpr.getOperator();
1022 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1023 op == Token::Kind::TK_LOGICALOR);
1024 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001025 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001026 }
1027 break;
1028 }
1029 case Expression::Kind::kConstructor: {
1030 Constructor& constructorExpr = (*expr)->as<Constructor>();
1031 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1032 this->visitExpression(&arg);
1033 }
1034 break;
1035 }
1036 case Expression::Kind::kExternalFunctionCall: {
1037 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1038 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1039 this->visitExpression(&arg);
1040 }
1041 break;
1042 }
1043 case Expression::Kind::kFunctionCall: {
1044 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001045 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001046 this->visitExpression(&arg);
1047 }
1048 this->addInlineCandidate(expr);
1049 break;
1050 }
1051 case Expression::Kind::kIndex:{
1052 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001053 this->visitExpression(&indexExpr.base());
1054 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001055 break;
1056 }
1057 case Expression::Kind::kPostfix: {
1058 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001059 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001060 break;
1061 }
1062 case Expression::Kind::kPrefix: {
1063 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001064 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001065 break;
1066 }
1067 case Expression::Kind::kSwizzle: {
1068 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001069 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001070 break;
1071 }
1072 case Expression::Kind::kTernary: {
1073 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1074 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001075 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001076 // The true- and false-expressions cannot be inlined, because we are only allowed to
1077 // evaluate one side.
1078 break;
1079 }
1080 default:
1081 SkUNREACHABLE;
1082 }
1083 }
1084
1085 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1086 fCandidateList->fCandidates.push_back(
1087 InlineCandidate{fSymbolTableStack.back(),
1088 find_parent_statement(fEnclosingStmtStack),
1089 fEnclosingStmtStack.back(),
1090 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001091 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001092 }
John Stiles2d7973a2020-10-02 15:01:03 -04001093};
John Stiles93442622020-09-11 12:11:27 -04001094
John Stiles9b9415e2020-11-23 14:48:06 -05001095static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1096 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1097}
John Stiles915a38c2020-09-14 09:38:13 -04001098
John Stiles9b9415e2020-11-23 14:48:06 -05001099bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1100 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001101 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001102 if (wasInserted) {
1103 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001104 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1105 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001106 }
1107
John Stiles2d7973a2020-10-02 15:01:03 -04001108 return iter->second;
1109}
1110
John Stiles9b9415e2020-11-23 14:48:06 -05001111int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1112 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001113 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001114 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
1115 fSettings->fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001116 }
John Stiles2d7973a2020-10-02 15:01:03 -04001117 return iter->second;
1118}
1119
Brian Osman0006ad02020-11-18 15:38:39 -05001120void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001121 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001122 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001123 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1124 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1125 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1126 // `const T&`.
1127 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001128 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001129
John Stiles0ad233f2020-11-25 11:02:05 -05001130 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001131 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001132 if (candidates.empty()) {
1133 return;
1134 }
1135
1136 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001137 InlinabilityCache cache;
1138 candidates.erase(std::remove_if(candidates.begin(),
1139 candidates.end(),
1140 [&](const InlineCandidate& candidate) {
1141 return !this->candidateCanBeInlined(candidate, &cache);
1142 }),
1143 candidates.end());
1144
John Stiles0ad233f2020-11-25 11:02:05 -05001145 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1146 // complete.
1147 if (fSettings->fInlineThreshold == INT_MAX || candidates.empty()) {
1148 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001149 }
John Stiles0ad233f2020-11-25 11:02:05 -05001150
1151 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1152 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1153 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1154 FunctionSizeCache functionSizeCache;
1155 FunctionSizeCache candidateTotalCost;
1156 for (InlineCandidate& candidate : candidates) {
1157 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1158 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1159 }
1160
1161 candidates.erase(
1162 std::remove_if(candidates.begin(),
1163 candidates.end(),
1164 [&](const InlineCandidate& candidate) {
1165 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1166 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1167 // Functions marked `inline` ignore size limitations.
1168 return false;
1169 }
1170 if (usage->get(fnDecl) == 1) {
1171 // If a function is only used once, it's cost-free to inline.
1172 return false;
1173 }
1174 if (candidateTotalCost[&fnDecl] <= fSettings->fInlineThreshold) {
1175 // We won't exceed the inline threshold by inlining this.
1176 return false;
1177 }
1178 // Inlining this function will add too many IRNodes.
1179 return true;
1180 }),
1181 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001182}
1183
Brian Osman0006ad02020-11-18 15:38:39 -05001184bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001185 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001186 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001187 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1188 if (fSettings->fInlineThreshold <= 0) {
1189 return false;
1190 }
1191
John Stiles031a7672020-11-13 16:13:18 -05001192 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1193 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1194 return false;
1195 }
1196
John Stiles2d7973a2020-10-02 15:01:03 -04001197 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001198 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001199
John Stiles915a38c2020-09-14 09:38:13 -04001200 // Inline the candidates where we've determined that it's safe to do so.
1201 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1202 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001203 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001204 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001205
1206 // Inlining two expressions using the same enclosing statement in the same inlining pass
1207 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1208 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1209 if (!inserted) {
1210 continue;
1211 }
1212
1213 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001214 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001215 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001216 if (inlinedCall.fInlinedBody) {
1217 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001218 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001219
Brian Osman010ce6a2020-10-19 16:34:10 -04001220 // Add references within the inlined body
1221 usage->add(inlinedCall.fInlinedBody.get());
1222
John Stiles915a38c2020-09-14 09:38:13 -04001223 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1224 // function, then replace the enclosing statement with that Block.
1225 // Before:
1226 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1227 // fEnclosingStmt = stmt4
1228 // After:
1229 // fInlinedBody = null
1230 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001231 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001232 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1233 }
1234
1235 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001236 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001237 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1238 madeChanges = true;
1239
John Stiles031a7672020-11-13 16:13:18 -05001240 // Stop inlining if we've reached our hard cap on new statements.
1241 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1242 break;
1243 }
1244
John Stiles915a38c2020-09-14 09:38:13 -04001245 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1246 // remain valid.
1247 }
1248
1249 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001250}
1251
John Stiles44e96be2020-08-31 13:16:04 -04001252} // namespace SkSL