blob: 90c5fad3e96ee218d002d4596c498458bd462867 [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
Ethan Nicholasdaed2592021-03-04 14:30:25 -050014#include "include/private/SkSLLayout.h"
John Stiles44e96be2020-08-31 13:16:04 -040015#include "src/sksl/SkSLAnalysis.h"
16#include "src/sksl/ir/SkSLBinaryExpression.h"
17#include "src/sksl/ir/SkSLBoolLiteral.h"
18#include "src/sksl/ir/SkSLBreakStatement.h"
19#include "src/sksl/ir/SkSLConstructor.h"
20#include "src/sksl/ir/SkSLContinueStatement.h"
21#include "src/sksl/ir/SkSLDiscardStatement.h"
22#include "src/sksl/ir/SkSLDoStatement.h"
23#include "src/sksl/ir/SkSLEnum.h"
24#include "src/sksl/ir/SkSLExpressionStatement.h"
25#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050026#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040027#include "src/sksl/ir/SkSLField.h"
28#include "src/sksl/ir/SkSLFieldAccess.h"
29#include "src/sksl/ir/SkSLFloatLiteral.h"
30#include "src/sksl/ir/SkSLForStatement.h"
31#include "src/sksl/ir/SkSLFunctionCall.h"
32#include "src/sksl/ir/SkSLFunctionDeclaration.h"
33#include "src/sksl/ir/SkSLFunctionDefinition.h"
34#include "src/sksl/ir/SkSLFunctionReference.h"
35#include "src/sksl/ir/SkSLIfStatement.h"
36#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040037#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040038#include "src/sksl/ir/SkSLIntLiteral.h"
39#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040040#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: {
John Stiles99b2d042021-03-15 11:42:47 -0400203 ++fNumNonReturnStatements;
John Stilesc5ff4862020-12-22 13:47:05 -0500204 if (fScopedBlockDepth > 1) {
205 fVariablesInBlocks = true;
206 }
207 return INHERITED::visitStatement(stmt);
208 }
John Stiles77702f12020-12-17 14:38:56 -0500209 case Statement::Kind::kBlock: {
John Stiles99b2d042021-03-15 11:42:47 -0400210 // Don't count Block as a statement.
John Stiles77702f12020-12-17 14:38:56 -0500211 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
212 fScopedBlockDepth += depthIncrement;
213 bool result = INHERITED::visitStatement(stmt);
214 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500215 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
216 // If closing this block puts us back at the top level, and we haven't
217 // encountered any return statements yet, any vardecls we may have encountered
218 // up until this point can be ignored. They are out of scope now, and they were
219 // never used in a return statement.
220 fVariablesInBlocks = false;
221 }
John Stiles77702f12020-12-17 14:38:56 -0500222 return result;
223 }
John Stiles99b2d042021-03-15 11:42:47 -0400224 case Statement::Kind::kNop:
225 case Statement::Kind::kInlineMarker:
226 // Don't count no-op statements.
227 return false;
John Stiles77702f12020-12-17 14:38:56 -0500228 default:
John Stiles99b2d042021-03-15 11:42:47 -0400229 ++fNumNonReturnStatements;
John Stiles77702f12020-12-17 14:38:56 -0500230 return INHERITED::visitStatement(stmt);
231 }
232 }
233
234 int fNumReturns = 0;
John Stiles99b2d042021-03-15 11:42:47 -0400235 int fNumNonReturnStatements = 0;
John Stiles77702f12020-12-17 14:38:56 -0500236 int fDeepestReturn = 0;
237 int fLimit = 0;
238 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500239 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500240 using INHERITED = ProgramVisitor;
241};
242
John Stiles44e96be2020-08-31 13:16:04 -0400243} // namespace
244
John Stiles77702f12020-12-17 14:38:56 -0500245Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
246 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
247 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500248 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
249 return ReturnComplexity::kEarlyReturns;
250 }
John Stilesc5ff4862020-12-22 13:47:05 -0500251 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500252 return ReturnComplexity::kScopedReturns;
253 }
John Stilesc5ff4862020-12-22 13:47:05 -0500254 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
255 return ReturnComplexity::kScopedReturns;
256 }
John Stiles99b2d042021-03-15 11:42:47 -0400257 if (counter.fNumNonReturnStatements > 0) {
258 return ReturnComplexity::kSingleSafeReturn;
259 }
260 return ReturnComplexity::kOnlySingleReturn;
John Stiles77702f12020-12-17 14:38:56 -0500261}
262
John Stilesb61ee902020-09-21 12:26:59 -0400263void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
264 // No changes necessary if this statement isn't actually a block.
265 if (!inlinedBody || !inlinedBody->is<Block>()) {
266 return;
267 }
268
269 // No changes necessary if the parent statement doesn't require a scope.
270 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500271 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400272 return;
273 }
274
275 Block& block = inlinedBody->as<Block>();
276
277 // The inliner will create inlined function bodies as a Block containing multiple statements,
278 // but no scope. Normally, this is fine, but if this block is used as the statement for a
279 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
280 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
281 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
282 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
283 // absorbing the following statement into our loop--so we also add a scope to these.
284 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400285 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400286 // We found an explicit scope; all is well.
287 return;
288 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400289 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400290 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
291 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400292 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400293 return;
294 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400295 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400296 // This block has exactly one thing inside, and it's not another block. No need to scope
297 // it.
298 return;
299 }
300 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400301 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400302 }
303}
304
John Stilesd1204642021-02-17 16:30:02 -0500305void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400306 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500307 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500308 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400309}
310
311std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
312 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500313 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400314 const Expression& expression) {
315 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
316 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500317 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400318 }
319 return nullptr;
320 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400321 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
322 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400323 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400324 for (const std::unique_ptr<Expression>& arg : originalArgs) {
325 args.push_back(expr(arg));
326 }
327 return args;
328 };
329
Ethan Nicholase6592142020-09-08 10:22:09 -0400330 switch (expression.kind()) {
331 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500332 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500333 return BinaryExpression::Make(*fContext,
334 expr(binaryExpr.left()),
335 binaryExpr.getOperator(),
336 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400337 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400338 case Expression::Kind::kBoolLiteral:
339 case Expression::Kind::kIntLiteral:
340 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400341 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400342 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400343 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500344 auto inlinedCtor = Constructor::Convert(
345 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
346 argList(constructor.arguments()));
347 SkASSERT(inlinedCtor);
348 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400349 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400350 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400351 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400352 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400353 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400354 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500355 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400356 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400357 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400358 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500359 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400360 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400361 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400362 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilesddcc8432021-01-15 15:32:32 -0500363 return std::make_unique<FunctionCall>(offset,
364 funcCall.type().clone(symbolTableForExpression),
365 &funcCall.function(),
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400366 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400367 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400368 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400369 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400370 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400371 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500372 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400373 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400374 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400375 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500376 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400377 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400378 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400379 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500380 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400381 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400382 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400383 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400384 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400385 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500386 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400387 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400388 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400389 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500390 return TernaryExpression::Make(*fContext, expr(t.test()),
391 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400392 }
Brian Osman83ba9302020-09-11 13:33:46 -0400393 case Expression::Kind::kTypeReference:
394 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400395 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400396 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400397 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400398 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400399 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400400 }
401 return v.clone();
402 }
403 default:
404 SkASSERT(false);
405 return nullptr;
406 }
407}
408
409std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
410 VariableRewriteMap* varMap,
411 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500412 std::unique_ptr<Expression>* resultExpr,
413 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400414 const Statement& statement,
415 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400416 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
417 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400418 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500419 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400420 }
421 return nullptr;
422 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400423 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400424 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400425 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400426 for (const std::unique_ptr<Statement>& child : block.children()) {
427 result.push_back(stmt(child));
428 }
429 return result;
430 };
John Stiles44e96be2020-08-31 13:16:04 -0400431 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
432 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500433 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400434 }
435 return nullptr;
436 };
John Stiles031a7672020-11-13 16:13:18 -0500437
438 ++fInlinedStatementCounter;
439
Ethan Nicholase6592142020-09-08 10:22:09 -0400440 switch (statement.kind()) {
441 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400442 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500443 return Block::Make(offset, blockStmts(b),
444 SymbolTable::WrapIfBuiltin(b.symbolTable()),
445 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400446 }
447
Ethan Nicholase6592142020-09-08 10:22:09 -0400448 case Statement::Kind::kBreak:
449 case Statement::Kind::kContinue:
450 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400451 return statement.clone();
452
Ethan Nicholase6592142020-09-08 10:22:09 -0400453 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400454 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500455 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400456 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400457 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400458 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500459 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400460 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400461 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400462 const ForStatement& f = statement.as<ForStatement>();
463 // need to ensure initializer is evaluated first so that we've already remapped its
464 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400465 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500466 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
467 expr(f.next()), stmt(f.statement()),
468 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400469 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400470 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400471 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500472 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
473 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400474 }
John Stiles98c1f822020-09-09 14:18:53 -0400475 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400476 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400477 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500478
Ethan Nicholase6592142020-09-08 10:22:09 -0400479 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400480 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500481 if (!r.expression()) {
482 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
483 // This function doesn't return a value, but has early returns, so we've wrapped
484 // it in a for loop. Use a continue to jump to the end of the loop and "leave"
485 // the function.
John Stilesa0c04d62021-03-11 23:07:24 -0500486 return ContinueStatement::Make(offset);
John Stiles44e96be2020-08-31 13:16:04 -0400487 } else {
John Stiles77702f12020-12-17 14:38:56 -0500488 // This function doesn't exit early or return a value. A return statement at the
489 // end is a no-op and can be treated as such.
John Stilesa0c04d62021-03-11 23:07:24 -0500490 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400491 }
492 }
John Stiles77702f12020-12-17 14:38:56 -0500493
John Stilesc5ff4862020-12-22 13:47:05 -0500494 // If a function only contains a single return, and it doesn't reference variables from
495 // inside an Block's scope, we don't need to store the result in a variable at all. Just
496 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500497 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500498 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500499 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500500 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500501 }
502
503 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500504 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500505 auto assignment = ExpressionStatement::Make(
506 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500507 BinaryExpression::Make(
508 *fContext,
509 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500510 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500511 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500512
513 // Early returns are wrapped in a for loop; we need to synthesize a continue statement
514 // to "leave" the function.
515 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
516 StatementArray block;
517 block.reserve_back(2);
518 block.push_back(std::move(assignment));
John Stilesa0c04d62021-03-11 23:07:24 -0500519 block.push_back(ContinueStatement::Make(offset));
John Stilesbf16b6c2021-03-12 19:24:31 -0500520 return Block::Make(offset, std::move(block), /*symbols=*/nullptr, /*isScope=*/true);
John Stiles77702f12020-12-17 14:38:56 -0500521 }
522 // Functions without early returns aren't wrapped in a for loop and don't need to worry
523 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500524 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400525 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400526 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400527 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500528 StatementArray cases;
529 cases.reserve_back(ss.cases().size());
530 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
531 const SwitchCase& sc = statement->as<SwitchCase>();
532 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
533 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400534 }
John Stilese1d1b082021-02-23 13:44:36 -0500535 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
536 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400537 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400538 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400539 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000540 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500541 const Variable& variable = decl.var();
542
John Stiles35fee4c2020-12-16 18:25:14 +0000543 // We assign unique names to inlined variables--scopes hide most of the problems in this
544 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
545 // names are important.
John Stilesddcc8432021-01-15 15:32:32 -0500546 auto name = std::make_unique<String>(fMangler.uniqueName(variable.name(),
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500547 symbolTableForStatement));
John Stiles35fee4c2020-12-16 18:25:14 +0000548 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500549 auto clonedVar = std::make_unique<Variable>(
550 offset,
551 &variable.modifiers(),
552 namePtr->c_str(),
553 variable.type().clone(symbolTableForStatement),
554 isBuiltinCode,
555 variable.storage());
556 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
557 auto result = std::make_unique<VarDeclaration>(clonedVar.get(),
John Stilesddcc8432021-01-15 15:32:32 -0500558 decl.baseType().clone(symbolTableForStatement),
559 decl.arraySize(),
John Stiles35fee4c2020-12-16 18:25:14 +0000560 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500561 clonedVar->setDeclaration(result.get());
562 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
563 return std::move(result);
John Stiles44e96be2020-08-31 13:16:04 -0400564 }
John Stiles44e96be2020-08-31 13:16:04 -0400565 default:
566 SkASSERT(false);
567 return nullptr;
568 }
569}
570
John Stiles7b920442020-12-17 10:43:41 -0500571Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
572 const Type* type,
573 SymbolTable* symbolTable,
574 Modifiers modifiers,
575 bool isBuiltinCode,
576 std::unique_ptr<Expression>* initialValue) {
577 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
578 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
579 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500580 if (type->isLiteral()) {
581 SkDEBUGFAIL("found a $literal type while inlining");
582 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500583 }
584
585 // Provide our new variable with a unique name, and add it to our symbol table.
586 const String* namePtr = symbolTable->takeOwnershipOfString(
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500587 std::make_unique<String>(fMangler.uniqueName(baseName, symbolTable)));
John Stiles7b920442020-12-17 10:43:41 -0500588 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
589
590 // Create our new variable and add it to the symbol table.
591 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500592 auto var = std::make_unique<Variable>(/*offset=*/-1,
593 fModifiers->addToPool(Modifiers()),
594 nameFrag,
595 type,
596 isBuiltinCode,
597 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500598
599 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
600 // initial value).
601 if (*initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500602 result.fVarDecl = std::make_unique<VarDeclaration>(var.get(), type, /*arraySize=*/0,
John Stiles7b920442020-12-17 10:43:41 -0500603 (*initialValue)->clone());
604 } else {
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500605 result.fVarDecl = std::make_unique<VarDeclaration>(var.get(), type, /*arraySize=*/0,
John Stiles7b920442020-12-17 10:43:41 -0500606 std::move(*initialValue));
607 }
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500608 var->setDeclaration(&result.fVarDecl->as<VarDeclaration>());
609 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500610 return result;
611}
612
John Stiles6eadf132020-09-08 10:16:10 -0400613Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500614 std::shared_ptr<SymbolTable> symbolTable,
Brian Osman3887a012020-09-30 13:22:27 -0400615 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400616 // Inlining is more complicated here than in a typical compiler, because we have to have a
617 // high-level IR and can't just drop statements into the middle of an expression or even use
618 // gotos.
619 //
620 // Since we can't insert statements into an expression, we run the inline function as extra
621 // statements before the statement we're currently processing, relying on a lack of execution
622 // order guarantees. Since we can't use gotos (which are normally used to replace return
623 // statements), we wrap the whole function in a loop and use break statements to jump to the
624 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400625 SkASSERT(fContext);
626 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400627 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400628
John Stiles8e3b6be2020-10-13 11:14:08 -0400629 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400630 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400631 const FunctionDefinition& function = *call->function().definition();
John Stiles77702f12020-12-17 14:38:56 -0500632 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
633 bool hasEarlyReturn = (returnComplexity >= ReturnComplexity::kEarlyReturns);
John Stiles6eadf132020-09-08 10:16:10 -0400634
John Stiles44e96be2020-08-31 13:16:04 -0400635 InlinedCall inlinedCall;
John Stilesbf16b6c2021-03-12 19:24:31 -0500636 StatementArray inlinedBlockStmts;
637 inlinedBlockStmts.reserve_back(1 + // Inline marker
638 1 + // Result variable
639 arguments.size() + // Function arguments (passing in)
640 arguments.size() + // Function arguments (copy out-params back)
641 1); // Block for inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400642
John Stilesbf16b6c2021-03-12 19:24:31 -0500643 inlinedBlockStmts.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400644
John Stilese41b4ee2020-09-28 12:28:16 -0400645 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500646 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
647 function.declaration().returnType() != *fContext->fTypes.fVoid) {
648 // Create a variable to hold the result in the extra statements. We don't need to do this
649 // for void-return functions, or in cases that are simple enough that we can just replace
650 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400651 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500652 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
653 &function.declaration().returnType(),
654 symbolTable.get(), Modifiers{},
655 caller->isBuiltin(), &noInitialValue);
John Stilesbf16b6c2021-03-12 19:24:31 -0500656 inlinedBlockStmts.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500657 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500658 }
John Stiles44e96be2020-08-31 13:16:04 -0400659
660 // Create variables in the extra statements to hold the arguments, and assign the arguments to
661 // them.
662 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400663 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400664 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400665 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400666 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400667
John Stiles44733aa2020-09-29 17:42:23 -0400668 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500669 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400670 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400671 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400672 // ... we don't need to copy it at all! We can just use the existing expression.
673 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400674 continue;
675 }
676 }
John Stilese41b4ee2020-09-28 12:28:16 -0400677 if (isOutParam) {
678 argsToCopyBack.push_back(i);
679 }
John Stiles7b920442020-12-17 10:43:41 -0500680 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
681 symbolTable.get(), param->modifiers(),
682 caller->isBuiltin(), &arguments[i]);
John Stilesbf16b6c2021-03-12 19:24:31 -0500683 inlinedBlockStmts.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500684 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400685 }
686
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400687 const Block& body = function.body()->as<Block>();
John Stiles7b920442020-12-17 10:43:41 -0500688 StatementArray* inlineStatements;
689
John Stiles44e96be2020-08-31 13:16:04 -0400690 if (hasEarlyReturn) {
691 // Since we output to backends that don't have a goto statement (which would normally be
John Stiles7b920442020-12-17 10:43:41 -0500692 // used to perform an early return), we fake it by wrapping the function in a single-
693 // iteration for loop, and use a continue statement to jump to the end of the loop
694 // prematurely.
695
696 // int _1_loop = 0;
697 symbolTable = std::make_shared<SymbolTable>(std::move(symbolTable), caller->isBuiltin());
John Stiles54e7c052021-01-11 14:22:36 -0500698 const Type* intType = fContext->fTypes.fInt.get();
John Stiles9ce80f72021-03-11 22:35:19 -0500699 std::unique_ptr<Expression> initialValue = IntLiteral::Make(/*offset=*/-1,
700 /*value=*/0,
701 intType);
John Stiles7b920442020-12-17 10:43:41 -0500702 InlineVariable loopVar = this->makeInlineVariable("loop", intType, symbolTable.get(),
703 Modifiers{}, caller->isBuiltin(),
704 &initialValue);
705
706 // _1_loop < 1;
John Stilese2aec432021-03-01 09:27:48 -0500707 std::unique_ptr<Expression> test = BinaryExpression::Make(
708 *fContext,
John Stiles7b920442020-12-17 10:43:41 -0500709 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol),
710 Token::Kind::TK_LT,
John Stiles9ce80f72021-03-11 22:35:19 -0500711 IntLiteral::Make(/*offset=*/-1, /*value=*/1, intType));
John Stiles7b920442020-12-17 10:43:41 -0500712
713 // _1_loop++
John Stiles52d3b012021-02-26 15:56:48 -0500714 std::unique_ptr<Expression> increment = PostfixExpression::Make(
715 *fContext,
John Stiles7b920442020-12-17 10:43:41 -0500716 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol,
717 VariableReference::RefKind::kReadWrite),
718 Token::Kind::TK_PLUSPLUS);
719
720 // {...}
John Stilesbf16b6c2021-03-12 19:24:31 -0500721 auto innerBlock = Block::Make(offset, StatementArray{},
722 /*symbols=*/nullptr, /*isScope=*/true);
John Stiles7b920442020-12-17 10:43:41 -0500723 inlineStatements = &innerBlock->children();
724
725 // for (int _1_loop = 0; _1_loop < 1; _1_loop++) {...}
John Stilesbf16b6c2021-03-12 19:24:31 -0500726 inlinedBlockStmts.push_back(ForStatement::Make(*fContext, /*offset=*/-1,
727 std::move(loopVar.fVarDecl),
728 std::move(test),
729 std::move(increment),
730 std::move(innerBlock),
731 symbolTable));
John Stiles44e96be2020-08-31 13:16:04 -0400732 } else {
John Stilesfa9a0832020-12-17 10:43:58 -0500733 // No early returns, so we can just dump the code into our existing scopeless block.
John Stilesbf16b6c2021-03-12 19:24:31 -0500734 inlineStatements = &inlinedBlockStmts;
John Stiles7b920442020-12-17 10:43:41 -0500735 }
736
737 inlineStatements->reserve_back(body.children().size() + argsToCopyBack.size());
738 for (const std::unique_ptr<Statement>& stmt : body.children()) {
739 inlineStatements->push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles77702f12020-12-17 14:38:56 -0500740 &resultExpr, returnComplexity, *stmt,
John Stiles7b920442020-12-17 10:43:41 -0500741 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400742 }
743
John Stilese41b4ee2020-09-28 12:28:16 -0400744 // Copy back the values of `out` parameters into their real destinations.
745 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400746 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400747 SkASSERT(varMap.find(p) != varMap.end());
John Stiles3e5871c2021-02-25 20:52:03 -0500748 inlineStatements->push_back(ExpressionStatement::Make(
749 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500750 BinaryExpression::Make(*fContext,
751 clone_with_ref_kind(*arguments[i], VariableRefKind::kWrite),
752 Token::Kind::TK_EQ,
753 std::move(varMap[p]))));
John Stiles44e96be2020-08-31 13:16:04 -0400754 }
755
John Stilesbf16b6c2021-03-12 19:24:31 -0500756 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
757 // MakeUnscoped. This is because we need to add another child statement to the Block later.
758 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlinedBlockStmts),
759 /*symbols=*/nullptr, /*isScope=*/false);
760
John Stiles0c2d14a2021-03-01 10:08:08 -0500761 if (resultExpr) {
762 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400763 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles0c2d14a2021-03-01 10:08:08 -0500764 } else if (function.declaration().returnType() == *fContext->fTypes.fVoid) {
John Stiles44e96be2020-08-31 13:16:04 -0400765 // It's a void function, so it doesn't actually result in anything, but we have to return
766 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500767 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500768 } else {
769 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500770 // returned anything on any path! This should have been detected in the function finalizer.
771 // Still, discard our output and generate an error.
772 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
773 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500774 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500775 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500776 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400777 }
778
John Stiles44e96be2020-08-31 13:16:04 -0400779 return inlinedCall;
780}
781
John Stiles2d7973a2020-10-02 15:01:03 -0400782bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400783 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500784 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400785 return false;
786 }
787
John Stiles031a7672020-11-13 16:13:18 -0500788 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
789 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
790 return false;
791 }
792
John Stiles2d7973a2020-10-02 15:01:03 -0400793 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400794 // Can't inline something if we don't actually have its definition.
795 return false;
796 }
John Stiles2d7973a2020-10-02 15:01:03 -0400797
John Stiles0dd1a772021-03-09 22:14:27 -0500798 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
799 // Refuse to inline functions decorated with `noinline`.
800 return false;
801 }
802
John Stiles74ebd7e2020-12-17 14:41:50 -0500803 // We don't have any mechanism to simulate early returns within a construct that supports
804 // continues (for/do/while), so we can't inline if there's a return inside one.
805 bool hasReturnInContinuableConstruct =
806 (count_returns_in_continuable_constructs(*functionDef) > 0);
807 return !hasReturnInContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400808}
809
John Stiles2d7973a2020-10-02 15:01:03 -0400810// A candidate function for inlining, containing everything that `inlineCall` needs.
811struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500812 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400813 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
814 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
815 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
816 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400817};
John Stiles93442622020-09-11 12:11:27 -0400818
John Stiles2d7973a2020-10-02 15:01:03 -0400819struct InlineCandidateList {
820 std::vector<InlineCandidate> fCandidates;
821};
822
823class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400824public:
825 // A list of all the inlining candidates we found during analysis.
826 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400827
John Stiles70957c82020-10-02 16:42:10 -0400828 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
829 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500830 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400831 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
832 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
833 // inliner might replace a statement with a block containing the statement.
834 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
835 // The function that we're currently processing (i.e. inlining into).
836 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400837
Brian Osman0006ad02020-11-18 15:38:39 -0500838 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500839 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500840 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400841 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500842 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400843
Brian Osman0006ad02020-11-18 15:38:39 -0500844 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400845 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400846 }
847
John Stiles70957c82020-10-02 16:42:10 -0400848 fSymbolTableStack.pop_back();
849 fCandidateList = nullptr;
850 }
851
852 void visitProgramElement(ProgramElement* pe) {
853 switch (pe->kind()) {
854 case ProgramElement::Kind::kFunction: {
855 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500856 fEnclosingFunction = &funcDef;
857 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400858 break;
John Stiles93442622020-09-11 12:11:27 -0400859 }
John Stiles70957c82020-10-02 16:42:10 -0400860 default:
861 // The inliner can't operate outside of a function's scope.
862 break;
863 }
864 }
865
866 void visitStatement(std::unique_ptr<Statement>* stmt,
867 bool isViableAsEnclosingStatement = true) {
868 if (!*stmt) {
869 return;
John Stiles93442622020-09-11 12:11:27 -0400870 }
871
John Stiles70957c82020-10-02 16:42:10 -0400872 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
873 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400874
John Stiles70957c82020-10-02 16:42:10 -0400875 if (isViableAsEnclosingStatement) {
876 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400877 }
878
John Stiles70957c82020-10-02 16:42:10 -0400879 switch ((*stmt)->kind()) {
880 case Statement::Kind::kBreak:
881 case Statement::Kind::kContinue:
882 case Statement::Kind::kDiscard:
883 case Statement::Kind::kInlineMarker:
884 case Statement::Kind::kNop:
885 break;
886
887 case Statement::Kind::kBlock: {
888 Block& block = (*stmt)->as<Block>();
889 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500890 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400891 }
892
893 for (std::unique_ptr<Statement>& stmt : block.children()) {
894 this->visitStatement(&stmt);
895 }
896 break;
John Stiles93442622020-09-11 12:11:27 -0400897 }
John Stiles70957c82020-10-02 16:42:10 -0400898 case Statement::Kind::kDo: {
899 DoStatement& doStmt = (*stmt)->as<DoStatement>();
900 // The loop body is a candidate for inlining.
901 this->visitStatement(&doStmt.statement());
902 // The inliner isn't smart enough to inline the test-expression for a do-while
903 // loop at this time. There are two limitations:
904 // - We would need to insert the inlined-body block at the very end of the do-
905 // statement's inner fStatement. We don't support that today, but it's doable.
906 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
907 // would skip over the inlined block that evaluates the test expression. There
908 // isn't a good fix for this--any workaround would be more complex than the cost
909 // of a function call. However, loops that don't use `continue` would still be
910 // viable candidates for inlining.
911 break;
John Stiles93442622020-09-11 12:11:27 -0400912 }
John Stiles70957c82020-10-02 16:42:10 -0400913 case Statement::Kind::kExpression: {
914 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
915 this->visitExpression(&expr.expression());
916 break;
917 }
918 case Statement::Kind::kFor: {
919 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400920 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500921 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400922 }
923
924 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400925 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400926 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400927 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400928
929 // The inliner isn't smart enough to inline the test- or increment-expressions
930 // of a for loop loop at this time. There are a handful of limitations:
931 // - We would need to insert the test-expression block at the very beginning of the
932 // for-loop's inner fStatement, and the increment-expression block at the very
933 // end. We don't support that today, but it's doable.
934 // - The for-loop's built-in test-expression would need to be dropped entirely,
935 // and the loop would be halted via a break statement at the end of the inlined
936 // test-expression. This is again something we don't support today, but it could
937 // be implemented.
938 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
939 // that would skip over the inlined block that evaluates the increment expression.
940 // There isn't a good fix for this--any workaround would be more complex than the
941 // cost of a function call. However, loops that don't use `continue` would still
942 // be viable candidates for increment-expression inlining.
943 break;
944 }
945 case Statement::Kind::kIf: {
946 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400947 this->visitExpression(&ifStmt.test());
948 this->visitStatement(&ifStmt.ifTrue());
949 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400950 break;
951 }
952 case Statement::Kind::kReturn: {
953 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400954 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400955 break;
956 }
957 case Statement::Kind::kSwitch: {
958 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400959 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500960 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400961 }
962
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400963 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500964 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400965 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500966 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400967 }
968 break;
969 }
970 case Statement::Kind::kVarDeclaration: {
971 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
972 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400973 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400974 break;
975 }
John Stiles70957c82020-10-02 16:42:10 -0400976 default:
977 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400978 }
979
John Stiles70957c82020-10-02 16:42:10 -0400980 // Pop our symbol and enclosing-statement stacks.
981 fSymbolTableStack.resize(oldSymbolStackSize);
982 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
983 }
984
985 void visitExpression(std::unique_ptr<Expression>* expr) {
986 if (!*expr) {
987 return;
John Stiles93442622020-09-11 12:11:27 -0400988 }
John Stiles70957c82020-10-02 16:42:10 -0400989
990 switch ((*expr)->kind()) {
991 case Expression::Kind::kBoolLiteral:
992 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500993 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400994 case Expression::Kind::kFieldAccess:
995 case Expression::Kind::kFloatLiteral:
996 case Expression::Kind::kFunctionReference:
997 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400998 case Expression::Kind::kSetting:
999 case Expression::Kind::kTypeReference:
1000 case Expression::Kind::kVariableReference:
1001 // Nothing to scan here.
1002 break;
1003
1004 case Expression::Kind::kBinary: {
1005 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001006 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -04001007
1008 // Logical-and and logical-or binary expressions do not inline the right side,
1009 // because that would invalidate short-circuiting. That is, when evaluating
1010 // expressions like these:
1011 // (false && x()) // always false
1012 // (true || y()) // always true
1013 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1014 // enforce that rule is to avoid inlining the right side entirely. However, it is
1015 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -05001016 Operator op = binaryExpr.getOperator();
1017 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
1018 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -04001019 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001020 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001021 }
1022 break;
1023 }
1024 case Expression::Kind::kConstructor: {
1025 Constructor& constructorExpr = (*expr)->as<Constructor>();
1026 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1027 this->visitExpression(&arg);
1028 }
1029 break;
1030 }
1031 case Expression::Kind::kExternalFunctionCall: {
1032 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1033 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1034 this->visitExpression(&arg);
1035 }
1036 break;
1037 }
1038 case Expression::Kind::kFunctionCall: {
1039 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001040 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001041 this->visitExpression(&arg);
1042 }
1043 this->addInlineCandidate(expr);
1044 break;
1045 }
1046 case Expression::Kind::kIndex:{
1047 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001048 this->visitExpression(&indexExpr.base());
1049 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001050 break;
1051 }
1052 case Expression::Kind::kPostfix: {
1053 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001054 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001055 break;
1056 }
1057 case Expression::Kind::kPrefix: {
1058 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001059 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001060 break;
1061 }
1062 case Expression::Kind::kSwizzle: {
1063 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001064 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001065 break;
1066 }
1067 case Expression::Kind::kTernary: {
1068 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1069 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001070 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001071 // The true- and false-expressions cannot be inlined, because we are only allowed to
1072 // evaluate one side.
1073 break;
1074 }
1075 default:
1076 SkUNREACHABLE;
1077 }
1078 }
1079
1080 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1081 fCandidateList->fCandidates.push_back(
1082 InlineCandidate{fSymbolTableStack.back(),
1083 find_parent_statement(fEnclosingStmtStack),
1084 fEnclosingStmtStack.back(),
1085 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001086 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001087 }
John Stiles2d7973a2020-10-02 15:01:03 -04001088};
John Stiles93442622020-09-11 12:11:27 -04001089
John Stiles9b9415e2020-11-23 14:48:06 -05001090static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1091 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1092}
John Stiles915a38c2020-09-14 09:38:13 -04001093
John Stiles9b9415e2020-11-23 14:48:06 -05001094bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1095 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001096 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001097 if (wasInserted) {
1098 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +00001099 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1100 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001101 }
1102
John Stiles2d7973a2020-10-02 15:01:03 -04001103 return iter->second;
1104}
1105
John Stiles9b9415e2020-11-23 14:48:06 -05001106int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1107 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001108 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001109 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001110 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001111 }
John Stiles2d7973a2020-10-02 15:01:03 -04001112 return iter->second;
1113}
1114
Brian Osman0006ad02020-11-18 15:38:39 -05001115void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001116 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001117 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001118 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1119 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1120 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1121 // `const T&`.
1122 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001123 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001124
John Stiles0ad233f2020-11-25 11:02:05 -05001125 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001126 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001127 if (candidates.empty()) {
1128 return;
1129 }
1130
1131 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001132 InlinabilityCache cache;
1133 candidates.erase(std::remove_if(candidates.begin(),
1134 candidates.end(),
1135 [&](const InlineCandidate& candidate) {
1136 return !this->candidateCanBeInlined(candidate, &cache);
1137 }),
1138 candidates.end());
1139
John Stiles0ad233f2020-11-25 11:02:05 -05001140 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1141 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001142 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001143 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001144 }
John Stiles0ad233f2020-11-25 11:02:05 -05001145
1146 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1147 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1148 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1149 FunctionSizeCache functionSizeCache;
1150 FunctionSizeCache candidateTotalCost;
1151 for (InlineCandidate& candidate : candidates) {
1152 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1153 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1154 }
1155
John Stilesd1204642021-02-17 16:30:02 -05001156 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1157 [&](const InlineCandidate& candidate) {
1158 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1159 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1160 // Functions marked `inline` ignore size limitations.
1161 return false;
1162 }
1163 if (usage->get(fnDecl) == 1) {
1164 // If a function is only used once, it's cost-free to inline.
1165 return false;
1166 }
1167 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1168 // We won't exceed the inline threshold by inlining this.
1169 return false;
1170 }
1171 // Inlining this function will add too many IRNodes.
1172 return true;
1173 }),
1174 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001175}
1176
Brian Osman0006ad02020-11-18 15:38:39 -05001177bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001178 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001179 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001180 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001181 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001182 return false;
1183 }
1184
John Stiles031a7672020-11-13 16:13:18 -05001185 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1186 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1187 return false;
1188 }
1189
John Stiles2d7973a2020-10-02 15:01:03 -04001190 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001191 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001192
John Stiles915a38c2020-09-14 09:38:13 -04001193 // Inline the candidates where we've determined that it's safe to do so.
1194 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1195 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001196 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001197 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001198
1199 // Inlining two expressions using the same enclosing statement in the same inlining pass
1200 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1201 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1202 if (!inserted) {
1203 continue;
1204 }
1205
1206 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001207 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001208 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001209
John Stiles0c2d14a2021-03-01 10:08:08 -05001210 // Stop if an error was detected during the inlining process.
1211 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1212 break;
John Stiles915a38c2020-09-14 09:38:13 -04001213 }
1214
John Stiles0c2d14a2021-03-01 10:08:08 -05001215 // Ensure that the inlined body has a scope if it needs one.
1216 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1217
1218 // Add references within the inlined body
1219 usage->add(inlinedCall.fInlinedBody.get());
1220
1221 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1222 // function, then replace the enclosing statement with that Block.
1223 // Before:
1224 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1225 // fEnclosingStmt = stmt4
1226 // After:
1227 // fInlinedBody = null
1228 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
1229 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
1230 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1231
John Stiles915a38c2020-09-14 09:38:13 -04001232 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001233 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001234 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1235 madeChanges = true;
1236
John Stiles031a7672020-11-13 16:13:18 -05001237 // Stop inlining if we've reached our hard cap on new statements.
1238 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1239 break;
1240 }
1241
John Stiles915a38c2020-09-14 09:38:13 -04001242 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1243 // remain valid.
1244 }
1245
1246 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001247}
1248
John Stiles44e96be2020-08-31 13:16:04 -04001249} // namespace SkSL