blob: cbd973bbc3b235ab9c03f95c753b6439c8b644f6 [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"
John Stiles7384b372021-04-01 13:48:15 -040020#include "src/sksl/ir/SkSLConstructorArray.h"
John Stilese1182782021-03-30 22:09:37 -040021#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040022#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stilesfd7252f2021-04-04 22:24:40 -040023#include "src/sksl/ir/SkSLConstructorScalarCast.h"
John Stiles2938eea2021-04-01 18:58:25 -040024#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd986f472021-04-06 15:54:43 -040025#include "src/sksl/ir/SkSLConstructorVector.h"
John Stilesb14a8192021-04-05 11:40:46 -040026#include "src/sksl/ir/SkSLConstructorVectorCast.h"
John Stiles44e96be2020-08-31 13:16:04 -040027#include "src/sksl/ir/SkSLContinueStatement.h"
28#include "src/sksl/ir/SkSLDiscardStatement.h"
29#include "src/sksl/ir/SkSLDoStatement.h"
30#include "src/sksl/ir/SkSLEnum.h"
31#include "src/sksl/ir/SkSLExpressionStatement.h"
32#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050033#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040034#include "src/sksl/ir/SkSLField.h"
35#include "src/sksl/ir/SkSLFieldAccess.h"
36#include "src/sksl/ir/SkSLFloatLiteral.h"
37#include "src/sksl/ir/SkSLForStatement.h"
38#include "src/sksl/ir/SkSLFunctionCall.h"
39#include "src/sksl/ir/SkSLFunctionDeclaration.h"
40#include "src/sksl/ir/SkSLFunctionDefinition.h"
41#include "src/sksl/ir/SkSLFunctionReference.h"
42#include "src/sksl/ir/SkSLIfStatement.h"
43#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040044#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040045#include "src/sksl/ir/SkSLIntLiteral.h"
46#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040047#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040048#include "src/sksl/ir/SkSLPostfixExpression.h"
49#include "src/sksl/ir/SkSLPrefixExpression.h"
50#include "src/sksl/ir/SkSLReturnStatement.h"
51#include "src/sksl/ir/SkSLSetting.h"
52#include "src/sksl/ir/SkSLSwitchCase.h"
53#include "src/sksl/ir/SkSLSwitchStatement.h"
54#include "src/sksl/ir/SkSLSwizzle.h"
55#include "src/sksl/ir/SkSLTernaryExpression.h"
56#include "src/sksl/ir/SkSLUnresolvedFunction.h"
57#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040058#include "src/sksl/ir/SkSLVariable.h"
59#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040060
61namespace SkSL {
62namespace {
63
John Stiles031a7672020-11-13 16:13:18 -050064static constexpr int kInlinedStatementLimit = 2500;
65
John Stiles44e96be2020-08-31 13:16:04 -040066static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
67 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
68 public:
69 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
70 this->visitProgramElement(funcDef);
71 }
72
John Stiles5b408a32021-03-17 09:53:32 -040073 bool visitExpression(const Expression& expr) override {
74 // Do not recurse into expressions.
75 return false;
76 }
77
John Stiles44e96be2020-08-31 13:16:04 -040078 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040079 switch (stmt.kind()) {
80 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040081 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040082 const auto& block = stmt.as<Block>();
83 return block.children().size() &&
84 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040085 }
Ethan Nicholase6592142020-09-08 10:22:09 -040086 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040087 case Statement::Kind::kDo:
88 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040089 // Don't introspect switches or loop structures at all.
90 return false;
91
Ethan Nicholase6592142020-09-08 10:22:09 -040092 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040093 ++fNumReturns;
94 [[fallthrough]];
95
96 default:
John Stiles93442622020-09-11 12:11:27 -040097 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040098 }
99 }
100
101 int fNumReturns = 0;
102 using INHERITED = ProgramVisitor;
103 };
104
105 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
106}
107
John Stiles991b09d2020-09-10 13:33:40 -0400108static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
109 class ContainsRecursiveCall : public ProgramVisitor {
110 public:
111 bool visit(const FunctionDeclaration& funcDecl) {
112 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400113 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
114 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400115 }
116
117 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400118 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400119 return true;
120 }
121 return INHERITED::visitExpression(expr);
122 }
123
124 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400125 if (stmt.is<InlineMarker>() &&
126 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400127 return true;
128 }
129 return INHERITED::visitStatement(stmt);
130 }
131
132 const FunctionDeclaration* fFuncDecl;
133 using INHERITED = ProgramVisitor;
134 };
135
136 return ContainsRecursiveCall{}.visit(funcDecl);
137}
138
John Stiles6d696082020-10-01 10:18:54 -0400139static std::unique_ptr<Statement>* find_parent_statement(
140 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400141 SkASSERT(!stmtStack.empty());
142
143 // Walk the statement stack from back to front, ignoring the last element (which is the
144 // enclosing statement).
145 auto iter = stmtStack.rbegin();
146 ++iter;
147
148 // Anything counts as a parent statement other than a scopeless Block.
149 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400150 std::unique_ptr<Statement>* stmt = *iter;
151 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400152 return stmt;
153 }
154 }
155
156 // There wasn't any parent statement to be found.
157 return nullptr;
158}
159
John Stilese41b4ee2020-09-28 12:28:16 -0400160std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
161 VariableReference::RefKind refKind) {
162 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500163 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400164 return clone;
165}
166
John Stiles77702f12020-12-17 14:38:56 -0500167class CountReturnsWithLimit : public ProgramVisitor {
168public:
169 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
170 this->visitProgramElement(funcDef);
171 }
172
John Stiles5b408a32021-03-17 09:53:32 -0400173 bool visitExpression(const Expression& expr) override {
174 // Do not recurse into expressions.
175 return false;
176 }
177
John Stiles77702f12020-12-17 14:38:56 -0500178 bool visitStatement(const Statement& stmt) override {
179 switch (stmt.kind()) {
180 case Statement::Kind::kReturn: {
181 ++fNumReturns;
182 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
183 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
184 }
John Stilesc5ff4862020-12-22 13:47:05 -0500185 case Statement::Kind::kVarDeclaration: {
186 if (fScopedBlockDepth > 1) {
187 fVariablesInBlocks = true;
188 }
189 return INHERITED::visitStatement(stmt);
190 }
John Stiles77702f12020-12-17 14:38:56 -0500191 case Statement::Kind::kBlock: {
192 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
193 fScopedBlockDepth += depthIncrement;
194 bool result = INHERITED::visitStatement(stmt);
195 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500196 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
197 // If closing this block puts us back at the top level, and we haven't
198 // encountered any return statements yet, any vardecls we may have encountered
199 // up until this point can be ignored. They are out of scope now, and they were
200 // never used in a return statement.
201 fVariablesInBlocks = false;
202 }
John Stiles77702f12020-12-17 14:38:56 -0500203 return result;
204 }
205 default:
206 return INHERITED::visitStatement(stmt);
207 }
208 }
209
210 int fNumReturns = 0;
211 int fDeepestReturn = 0;
212 int fLimit = 0;
213 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500214 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500215 using INHERITED = ProgramVisitor;
216};
217
John Stiles44e96be2020-08-31 13:16:04 -0400218} // namespace
219
John Stiles77702f12020-12-17 14:38:56 -0500220Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
221 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
222 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500223 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
224 return ReturnComplexity::kEarlyReturns;
225 }
John Stilesc5ff4862020-12-22 13:47:05 -0500226 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500227 return ReturnComplexity::kScopedReturns;
228 }
John Stilesc5ff4862020-12-22 13:47:05 -0500229 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
230 return ReturnComplexity::kScopedReturns;
231 }
John Stiles8937cd42021-03-17 19:32:59 +0000232 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500233}
234
John Stilesb61ee902020-09-21 12:26:59 -0400235void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
236 // No changes necessary if this statement isn't actually a block.
237 if (!inlinedBody || !inlinedBody->is<Block>()) {
238 return;
239 }
240
241 // No changes necessary if the parent statement doesn't require a scope.
242 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500243 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400244 return;
245 }
246
247 Block& block = inlinedBody->as<Block>();
248
249 // The inliner will create inlined function bodies as a Block containing multiple statements,
250 // but no scope. Normally, this is fine, but if this block is used as the statement for a
251 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
252 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
253 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
254 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
255 // absorbing the following statement into our loop--so we also add a scope to these.
256 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400257 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400258 // We found an explicit scope; all is well.
259 return;
260 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400261 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400262 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
263 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400264 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400265 return;
266 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400267 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400268 // This block has exactly one thing inside, and it's not another block. No need to scope
269 // it.
270 return;
271 }
272 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400273 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400274 }
275}
276
John Stilesd1204642021-02-17 16:30:02 -0500277void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400278 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500279 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500280 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400281}
282
283std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
284 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500285 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400286 const Expression& expression) {
287 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
288 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500289 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400290 }
291 return nullptr;
292 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400293 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
294 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400295 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400296 for (const std::unique_ptr<Expression>& arg : originalArgs) {
297 args.push_back(expr(arg));
298 }
299 return args;
300 };
301
Ethan Nicholase6592142020-09-08 10:22:09 -0400302 switch (expression.kind()) {
303 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500304 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500305 return BinaryExpression::Make(*fContext,
306 expr(binaryExpr.left()),
307 binaryExpr.getOperator(),
308 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400309 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400310 case Expression::Kind::kBoolLiteral:
311 case Expression::Kind::kIntLiteral:
312 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400313 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400314 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400315 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500316 auto inlinedCtor = Constructor::Convert(
317 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
318 argList(constructor.arguments()));
319 SkASSERT(inlinedCtor);
320 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400321 }
John Stiles7384b372021-04-01 13:48:15 -0400322 case Expression::Kind::kConstructorArray: {
323 const ConstructorArray& ctor = expression.as<ConstructorArray>();
324 return ConstructorArray::Make(*fContext, offset,
325 *ctor.type().clone(symbolTableForExpression),
326 argList(ctor.arguments()));
327 }
John Stilese1182782021-03-30 22:09:37 -0400328 case Expression::Kind::kConstructorDiagonalMatrix: {
329 const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
330 return ConstructorDiagonalMatrix::Make(*fContext, offset,
331 *ctor.type().clone(symbolTableForExpression),
332 expr(ctor.argument()));
333 }
John Stiles5abb9e12021-04-06 13:47:19 -0400334 case Expression::Kind::kConstructorMatrixResize: {
335 const ConstructorMatrixResize& ctor = expression.as<ConstructorMatrixResize>();
336 return ConstructorMatrixResize::Make(*fContext, offset,
337 *ctor.type().clone(symbolTableForExpression),
338 expr(ctor.argument()));
339 }
John Stilesfd7252f2021-04-04 22:24:40 -0400340 case Expression::Kind::kConstructorScalarCast: {
341 const ConstructorScalarCast& ctor = expression.as<ConstructorScalarCast>();
342 return ConstructorScalarCast::Make(*fContext, offset,
343 *ctor.type().clone(symbolTableForExpression),
344 expr(ctor.argument()));
345 }
John Stiles2938eea2021-04-01 18:58:25 -0400346 case Expression::Kind::kConstructorSplat: {
347 const ConstructorSplat& ctor = expression.as<ConstructorSplat>();
348 return ConstructorSplat::Make(*fContext, offset,
349 *ctor.type().clone(symbolTableForExpression),
350 expr(ctor.argument()));
351 }
John Stilesd986f472021-04-06 15:54:43 -0400352 case Expression::Kind::kConstructorVector: {
353 const ConstructorVector& ctor = expression.as<ConstructorVector>();
354 return ConstructorVector::Make(*fContext, offset,
355 *ctor.type().clone(symbolTableForExpression),
356 argList(ctor.arguments()));
357 }
John Stilesb14a8192021-04-05 11:40:46 -0400358 case Expression::Kind::kConstructorVectorCast: {
359 const ConstructorVectorCast& ctor = expression.as<ConstructorVectorCast>();
360 return ConstructorVectorCast::Make(*fContext, offset,
361 *ctor.type().clone(symbolTableForExpression),
362 expr(ctor.argument()));
363 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400364 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400365 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400366 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400367 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400368 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500369 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400370 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400371 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400372 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500373 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400374 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400375 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400376 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilescd7ba502021-03-19 10:54:59 -0400377 return FunctionCall::Make(*fContext,
378 offset,
379 funcCall.type().clone(symbolTableForExpression),
380 funcCall.function(),
381 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400382 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400383 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400384 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400385 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400386 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500387 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400388 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400389 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400390 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500391 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400392 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400393 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400394 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500395 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400396 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400397 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400398 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400399 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400400 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500401 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400402 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400403 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400404 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500405 return TernaryExpression::Make(*fContext, expr(t.test()),
406 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400407 }
Brian Osman83ba9302020-09-11 13:33:46 -0400408 case Expression::Kind::kTypeReference:
409 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400410 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400411 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400412 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400413 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400414 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400415 }
416 return v.clone();
417 }
418 default:
419 SkASSERT(false);
420 return nullptr;
421 }
422}
423
424std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
425 VariableRewriteMap* varMap,
426 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500427 std::unique_ptr<Expression>* resultExpr,
428 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400429 const Statement& statement,
430 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400431 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
432 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400433 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500434 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400435 }
436 return nullptr;
437 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400438 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400439 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400440 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400441 for (const std::unique_ptr<Statement>& child : block.children()) {
442 result.push_back(stmt(child));
443 }
444 return result;
445 };
John Stiles44e96be2020-08-31 13:16:04 -0400446 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 Stilesbf16b6c2021-03-12 19:24:31 -0500458 return Block::Make(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>();
John Stilesea5822e2021-02-26 11:18:20 -0500470 return DoStatement::Make(*fContext, 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>();
John Stiles3e5871c2021-02-25 20:52:03 -0500474 return ExpressionStatement::Make(*fContext, 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());
John Stilesb321a072021-02-25 16:24:19 -0500481 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
482 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>();
John Stilescf3059e2021-02-25 14:27:02 -0500487 return IfStatement::Make(*fContext, 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();
John Stilesea5822e2021-02-26 11:18:20 -0500493
Ethan Nicholase6592142020-09-08 10:22:09 -0400494 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400495 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500496 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400497 // This function doesn't return a value. We won't inline functions with early
498 // returns, so a return statement is a no-op and can be treated as such.
499 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400500 }
John Stiles77702f12020-12-17 14:38:56 -0500501
John Stilesc5ff4862020-12-22 13:47:05 -0500502 // If a function only contains a single return, and it doesn't reference variables from
503 // inside an Block's scope, we don't need to store the result in a variable at all. Just
504 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500505 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500506 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500507 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500508 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500509 }
510
511 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500512 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500513 auto assignment = ExpressionStatement::Make(
514 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500515 BinaryExpression::Make(
516 *fContext,
517 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500518 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500519 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500520
John Stiles77702f12020-12-17 14:38:56 -0500521 // Functions without early returns aren't wrapped in a for loop and don't need to worry
522 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500523 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400524 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400525 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400526 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500527 StatementArray cases;
528 cases.reserve_back(ss.cases().size());
529 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
530 const SwitchCase& sc = statement->as<SwitchCase>();
531 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
532 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400533 }
John Stilese1d1b082021-02-23 13:44:36 -0500534 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
535 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400536 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400537 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400538 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000539 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500540 const Variable& variable = decl.var();
541
John Stiles35fee4c2020-12-16 18:25:14 +0000542 // We assign unique names to inlined variables--scopes hide most of the problems in this
543 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
544 // names are important.
John Stilesd51c9792021-03-18 11:40:14 -0400545 const String* name = symbolTableForStatement->takeOwnershipOfString(
546 fMangler.uniqueName(variable.name(), symbolTableForStatement));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500547 auto clonedVar = std::make_unique<Variable>(
548 offset,
549 &variable.modifiers(),
John Stilesd51c9792021-03-18 11:40:14 -0400550 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500551 variable.type().clone(symbolTableForStatement),
552 isBuiltinCode,
553 variable.storage());
554 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
John Stilese67bd132021-03-19 18:39:25 -0400555 auto result = VarDeclaration::Make(*fContext,
556 clonedVar.get(),
557 decl.baseType().clone(symbolTableForStatement),
558 decl.arraySize(),
559 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500560 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
John Stilese67bd132021-03-19 18:39:25 -0400561 return result;
John Stiles44e96be2020-08-31 13:16:04 -0400562 }
John Stiles44e96be2020-08-31 13:16:04 -0400563 default:
564 SkASSERT(false);
565 return nullptr;
566 }
567}
568
John Stiles7b920442020-12-17 10:43:41 -0500569Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
570 const Type* type,
571 SymbolTable* symbolTable,
572 Modifiers modifiers,
573 bool isBuiltinCode,
574 std::unique_ptr<Expression>* initialValue) {
575 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
576 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
577 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500578 if (type->isLiteral()) {
579 SkDEBUGFAIL("found a $literal type while inlining");
580 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500581 }
582
John Stilesbff24ab2021-03-17 13:20:10 -0400583 // Out parameters aren't supported.
584 SkASSERT(!(modifiers.fFlags & Modifiers::kOut_Flag));
585
John Stiles7b920442020-12-17 10:43:41 -0500586 // Provide our new variable with a unique name, and add it to our symbol table.
John Stilesd51c9792021-03-18 11:40:14 -0400587 const String* name =
588 symbolTable->takeOwnershipOfString(fMangler.uniqueName(baseName, symbolTable));
John Stiles7b920442020-12-17 10:43:41 -0500589
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()),
John Stilesd51c9792021-03-18 11:40:14 -0400594 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500595 type,
596 isBuiltinCode,
597 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500598
John Stilesbff24ab2021-03-17 13:20:10 -0400599 // Create our variable declaration.
John Stilese67bd132021-03-19 18:39:25 -0400600 result.fVarDecl = VarDeclaration::Make(*fContext, var.get(), type, /*arraySize=*/0,
601 std::move(*initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500602 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500603 return result;
604}
605
John Stiles6eadf132020-09-08 10:16:10 -0400606Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500607 std::shared_ptr<SymbolTable> symbolTable,
John Stiles30fce9c2021-03-18 09:24:06 -0400608 const ProgramUsage& usage,
Brian Osman3887a012020-09-30 13:22:27 -0400609 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400610 // Inlining is more complicated here than in a typical compiler, because we have to have a
611 // high-level IR and can't just drop statements into the middle of an expression or even use
612 // gotos.
613 //
614 // Since we can't insert statements into an expression, we run the inline function as extra
615 // statements before the statement we're currently processing, relying on a lack of execution
616 // order guarantees. Since we can't use gotos (which are normally used to replace return
617 // statements), we wrap the whole function in a loop and use break statements to jump to the
618 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400619 SkASSERT(fContext);
620 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400621 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400622
John Stiles8e3b6be2020-10-13 11:14:08 -0400623 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400624 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400625 const FunctionDefinition& function = *call->function().definition();
John Stiles28257db2021-03-17 15:18:09 -0400626 const Block& body = function.body()->as<Block>();
John Stiles77702f12020-12-17 14:38:56 -0500627 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400628
John Stiles28257db2021-03-17 15:18:09 -0400629 StatementArray inlineStatements;
630 int expectedStmtCount = 1 + // Inline marker
631 1 + // Result variable
632 arguments.size() + // Function argument temp-vars
633 body.children().size(); // Inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400634
John Stiles28257db2021-03-17 15:18:09 -0400635 inlineStatements.reserve_back(expectedStmtCount);
636 inlineStatements.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400637
John Stilese41b4ee2020-09-28 12:28:16 -0400638 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500639 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400640 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500641 // Create a variable to hold the result in the extra statements. We don't need to do this
642 // for void-return functions, or in cases that are simple enough that we can just replace
643 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400644 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500645 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
646 &function.declaration().returnType(),
647 symbolTable.get(), Modifiers{},
648 caller->isBuiltin(), &noInitialValue);
John Stiles28257db2021-03-17 15:18:09 -0400649 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500650 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500651 }
John Stiles44e96be2020-08-31 13:16:04 -0400652
653 // Create variables in the extra statements to hold the arguments, and assign the arguments to
654 // them.
655 VariableRewriteMap varMap;
John Stilesbff24ab2021-03-17 13:20:10 -0400656 for (int i = 0; i < arguments.count(); ++i) {
John Stiles049f0df2021-03-19 09:39:44 -0400657 // If the parameter isn't written to within the inline function ...
John Stilesbff24ab2021-03-17 13:20:10 -0400658 const Variable* param = function.declaration().parameters()[i];
John Stiles049f0df2021-03-19 09:39:44 -0400659 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
660 if (!paramUsage.fWrite) {
661 // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
662 // or any expression without side effects that is only accessed at most once...
663 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arguments[i])
664 : !arguments[i]->hasSideEffects()) {
John Stilesf201af82020-09-29 16:57:55 -0400665 // ... we don't need to copy it at all! We can just use the existing expression.
666 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400667 continue;
668 }
669 }
John Stiles7b920442020-12-17 10:43:41 -0500670 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
671 symbolTable.get(), param->modifiers(),
672 caller->isBuiltin(), &arguments[i]);
John Stiles28257db2021-03-17 15:18:09 -0400673 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500674 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400675 }
676
John Stiles7b920442020-12-17 10:43:41 -0500677 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles28257db2021-03-17 15:18:09 -0400678 inlineStatements.push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
679 &resultExpr, returnComplexity, *stmt,
680 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400681 }
682
John Stiles28257db2021-03-17 15:18:09 -0400683 SkASSERT(inlineStatements.count() <= expectedStmtCount);
684
John Stilesbf16b6c2021-03-12 19:24:31 -0500685 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
686 // MakeUnscoped. This is because we need to add another child statement to the Block later.
John Stiles28257db2021-03-17 15:18:09 -0400687 InlinedCall inlinedCall;
688 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlineStatements),
John Stilesbf16b6c2021-03-12 19:24:31 -0500689 /*symbols=*/nullptr, /*isScope=*/false);
690
John Stiles0c2d14a2021-03-01 10:08:08 -0500691 if (resultExpr) {
692 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400693 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400694 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400695 // It's a void function, so it doesn't actually result in anything, but we have to return
696 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500697 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500698 } else {
699 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500700 // returned anything on any path! This should have been detected in the function finalizer.
701 // Still, discard our output and generate an error.
702 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
703 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500704 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500705 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500706 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400707 }
708
John Stiles44e96be2020-08-31 13:16:04 -0400709 return inlinedCall;
710}
711
John Stiles2d7973a2020-10-02 15:01:03 -0400712bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400713 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500714 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400715 return false;
716 }
717
John Stiles031a7672020-11-13 16:13:18 -0500718 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
719 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
720 return false;
721 }
722
John Stiles2d7973a2020-10-02 15:01:03 -0400723 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400724 // Can't inline something if we don't actually have its definition.
725 return false;
726 }
John Stiles2d7973a2020-10-02 15:01:03 -0400727
John Stiles0dd1a772021-03-09 22:14:27 -0500728 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
729 // Refuse to inline functions decorated with `noinline`.
730 return false;
731 }
732
John Stilesbff24ab2021-03-17 13:20:10 -0400733 // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
734 for (const Variable* param : functionDef->declaration().parameters()) {
735 if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
736 return false;
737 }
738 }
739
John Stilesdc208472021-03-17 10:58:16 -0400740 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
741 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400742}
743
John Stiles2d7973a2020-10-02 15:01:03 -0400744// A candidate function for inlining, containing everything that `inlineCall` needs.
745struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500746 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400747 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
748 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
749 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
750 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400751};
John Stiles93442622020-09-11 12:11:27 -0400752
John Stiles2d7973a2020-10-02 15:01:03 -0400753struct InlineCandidateList {
754 std::vector<InlineCandidate> fCandidates;
755};
756
757class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400758public:
759 // A list of all the inlining candidates we found during analysis.
760 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400761
John Stiles70957c82020-10-02 16:42:10 -0400762 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
763 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500764 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400765 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
766 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
767 // inliner might replace a statement with a block containing the statement.
768 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
769 // The function that we're currently processing (i.e. inlining into).
770 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400771
Brian Osman0006ad02020-11-18 15:38:39 -0500772 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500773 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500774 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400775 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500776 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400777
Brian Osman0006ad02020-11-18 15:38:39 -0500778 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400779 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400780 }
781
John Stiles70957c82020-10-02 16:42:10 -0400782 fSymbolTableStack.pop_back();
783 fCandidateList = nullptr;
784 }
785
786 void visitProgramElement(ProgramElement* pe) {
787 switch (pe->kind()) {
788 case ProgramElement::Kind::kFunction: {
789 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500790 fEnclosingFunction = &funcDef;
791 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400792 break;
John Stiles93442622020-09-11 12:11:27 -0400793 }
John Stiles70957c82020-10-02 16:42:10 -0400794 default:
795 // The inliner can't operate outside of a function's scope.
796 break;
797 }
798 }
799
800 void visitStatement(std::unique_ptr<Statement>* stmt,
801 bool isViableAsEnclosingStatement = true) {
802 if (!*stmt) {
803 return;
John Stiles93442622020-09-11 12:11:27 -0400804 }
805
John Stiles70957c82020-10-02 16:42:10 -0400806 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
807 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400808
John Stiles70957c82020-10-02 16:42:10 -0400809 if (isViableAsEnclosingStatement) {
810 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400811 }
812
John Stiles70957c82020-10-02 16:42:10 -0400813 switch ((*stmt)->kind()) {
814 case Statement::Kind::kBreak:
815 case Statement::Kind::kContinue:
816 case Statement::Kind::kDiscard:
817 case Statement::Kind::kInlineMarker:
818 case Statement::Kind::kNop:
819 break;
820
821 case Statement::Kind::kBlock: {
822 Block& block = (*stmt)->as<Block>();
823 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500824 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400825 }
826
827 for (std::unique_ptr<Statement>& stmt : block.children()) {
828 this->visitStatement(&stmt);
829 }
830 break;
John Stiles93442622020-09-11 12:11:27 -0400831 }
John Stiles70957c82020-10-02 16:42:10 -0400832 case Statement::Kind::kDo: {
833 DoStatement& doStmt = (*stmt)->as<DoStatement>();
834 // The loop body is a candidate for inlining.
835 this->visitStatement(&doStmt.statement());
836 // The inliner isn't smart enough to inline the test-expression for a do-while
837 // loop at this time. There are two limitations:
838 // - We would need to insert the inlined-body block at the very end of the do-
839 // statement's inner fStatement. We don't support that today, but it's doable.
840 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
841 // would skip over the inlined block that evaluates the test expression. There
842 // isn't a good fix for this--any workaround would be more complex than the cost
843 // of a function call. However, loops that don't use `continue` would still be
844 // viable candidates for inlining.
845 break;
John Stiles93442622020-09-11 12:11:27 -0400846 }
John Stiles70957c82020-10-02 16:42:10 -0400847 case Statement::Kind::kExpression: {
848 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
849 this->visitExpression(&expr.expression());
850 break;
851 }
852 case Statement::Kind::kFor: {
853 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400854 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500855 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400856 }
857
858 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400859 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400860 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400861 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400862
863 // The inliner isn't smart enough to inline the test- or increment-expressions
864 // of a for loop loop at this time. There are a handful of limitations:
865 // - We would need to insert the test-expression block at the very beginning of the
866 // for-loop's inner fStatement, and the increment-expression block at the very
867 // end. We don't support that today, but it's doable.
868 // - The for-loop's built-in test-expression would need to be dropped entirely,
869 // and the loop would be halted via a break statement at the end of the inlined
870 // test-expression. This is again something we don't support today, but it could
871 // be implemented.
872 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
873 // that would skip over the inlined block that evaluates the increment expression.
874 // There isn't a good fix for this--any workaround would be more complex than the
875 // cost of a function call. However, loops that don't use `continue` would still
876 // be viable candidates for increment-expression inlining.
877 break;
878 }
879 case Statement::Kind::kIf: {
880 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400881 this->visitExpression(&ifStmt.test());
882 this->visitStatement(&ifStmt.ifTrue());
883 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400884 break;
885 }
886 case Statement::Kind::kReturn: {
887 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400888 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400889 break;
890 }
891 case Statement::Kind::kSwitch: {
892 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400893 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500894 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400895 }
896
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400897 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500898 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400899 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500900 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400901 }
902 break;
903 }
904 case Statement::Kind::kVarDeclaration: {
905 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
906 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400907 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400908 break;
909 }
John Stiles70957c82020-10-02 16:42:10 -0400910 default:
911 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400912 }
913
John Stiles70957c82020-10-02 16:42:10 -0400914 // Pop our symbol and enclosing-statement stacks.
915 fSymbolTableStack.resize(oldSymbolStackSize);
916 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
917 }
918
919 void visitExpression(std::unique_ptr<Expression>* expr) {
920 if (!*expr) {
921 return;
John Stiles93442622020-09-11 12:11:27 -0400922 }
John Stiles70957c82020-10-02 16:42:10 -0400923
924 switch ((*expr)->kind()) {
925 case Expression::Kind::kBoolLiteral:
926 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500927 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400928 case Expression::Kind::kFieldAccess:
929 case Expression::Kind::kFloatLiteral:
930 case Expression::Kind::kFunctionReference:
931 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400932 case Expression::Kind::kSetting:
933 case Expression::Kind::kTypeReference:
934 case Expression::Kind::kVariableReference:
935 // Nothing to scan here.
936 break;
937
938 case Expression::Kind::kBinary: {
939 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400940 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400941
942 // Logical-and and logical-or binary expressions do not inline the right side,
943 // because that would invalidate short-circuiting. That is, when evaluating
944 // expressions like these:
945 // (false && x()) // always false
946 // (true || y()) // always true
947 // It is illegal for side-effects from x() or y() to occur. The simplest way to
948 // enforce that rule is to avoid inlining the right side entirely. However, it is
949 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500950 Operator op = binaryExpr.getOperator();
951 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
952 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400953 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400954 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400955 }
956 break;
957 }
John Stiles7384b372021-04-01 13:48:15 -0400958 case Expression::Kind::kConstructor:
959 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -0400960 case Expression::Kind::kConstructorDiagonalMatrix:
John Stiles5abb9e12021-04-06 13:47:19 -0400961 case Expression::Kind::kConstructorMatrixResize:
John Stilesfd7252f2021-04-04 22:24:40 -0400962 case Expression::Kind::kConstructorScalarCast:
John Stilesb14a8192021-04-05 11:40:46 -0400963 case Expression::Kind::kConstructorSplat:
John Stilesd986f472021-04-06 15:54:43 -0400964 case Expression::Kind::kConstructorVector:
John Stilesb14a8192021-04-05 11:40:46 -0400965 case Expression::Kind::kConstructorVectorCast: {
John Stiles7384b372021-04-01 13:48:15 -0400966 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
967 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
John Stiles70957c82020-10-02 16:42:10 -0400968 this->visitExpression(&arg);
969 }
970 break;
971 }
972 case Expression::Kind::kExternalFunctionCall: {
973 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
974 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
975 this->visitExpression(&arg);
976 }
977 break;
978 }
979 case Expression::Kind::kFunctionCall: {
980 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400981 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -0400982 this->visitExpression(&arg);
983 }
984 this->addInlineCandidate(expr);
985 break;
986 }
John Stiles708faba2021-03-19 09:43:23 -0400987 case Expression::Kind::kIndex: {
John Stiles70957c82020-10-02 16:42:10 -0400988 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400989 this->visitExpression(&indexExpr.base());
990 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -0400991 break;
992 }
993 case Expression::Kind::kPostfix: {
994 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400995 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400996 break;
997 }
998 case Expression::Kind::kPrefix: {
999 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001000 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001001 break;
1002 }
1003 case Expression::Kind::kSwizzle: {
1004 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001005 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001006 break;
1007 }
1008 case Expression::Kind::kTernary: {
1009 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1010 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001011 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001012 // The true- and false-expressions cannot be inlined, because we are only allowed to
1013 // evaluate one side.
1014 break;
1015 }
1016 default:
1017 SkUNREACHABLE;
1018 }
1019 }
1020
1021 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1022 fCandidateList->fCandidates.push_back(
1023 InlineCandidate{fSymbolTableStack.back(),
1024 find_parent_statement(fEnclosingStmtStack),
1025 fEnclosingStmtStack.back(),
1026 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001027 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001028 }
John Stiles2d7973a2020-10-02 15:01:03 -04001029};
John Stiles93442622020-09-11 12:11:27 -04001030
John Stiles9b9415e2020-11-23 14:48:06 -05001031static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1032 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1033}
John Stiles915a38c2020-09-14 09:38:13 -04001034
John Stiles9b9415e2020-11-23 14:48:06 -05001035bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1036 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001037 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001038 if (wasInserted) {
1039 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +00001040 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1041 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001042 }
1043
John Stiles2d7973a2020-10-02 15:01:03 -04001044 return iter->second;
1045}
1046
John Stiles9b9415e2020-11-23 14:48:06 -05001047int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1048 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001049 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001050 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001051 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001052 }
John Stiles2d7973a2020-10-02 15:01:03 -04001053 return iter->second;
1054}
1055
Brian Osman0006ad02020-11-18 15:38:39 -05001056void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001057 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001058 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001059 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1060 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1061 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1062 // `const T&`.
1063 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001064 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001065
John Stiles0ad233f2020-11-25 11:02:05 -05001066 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001067 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001068 if (candidates.empty()) {
1069 return;
1070 }
1071
1072 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001073 InlinabilityCache cache;
1074 candidates.erase(std::remove_if(candidates.begin(),
1075 candidates.end(),
1076 [&](const InlineCandidate& candidate) {
1077 return !this->candidateCanBeInlined(candidate, &cache);
1078 }),
1079 candidates.end());
1080
John Stiles0ad233f2020-11-25 11:02:05 -05001081 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1082 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001083 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001084 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001085 }
John Stiles0ad233f2020-11-25 11:02:05 -05001086
1087 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1088 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1089 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1090 FunctionSizeCache functionSizeCache;
1091 FunctionSizeCache candidateTotalCost;
1092 for (InlineCandidate& candidate : candidates) {
1093 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1094 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1095 }
1096
John Stilesd1204642021-02-17 16:30:02 -05001097 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1098 [&](const InlineCandidate& candidate) {
1099 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1100 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1101 // Functions marked `inline` ignore size limitations.
1102 return false;
1103 }
1104 if (usage->get(fnDecl) == 1) {
1105 // If a function is only used once, it's cost-free to inline.
1106 return false;
1107 }
1108 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1109 // We won't exceed the inline threshold by inlining this.
1110 return false;
1111 }
1112 // Inlining this function will add too many IRNodes.
1113 return true;
1114 }),
1115 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001116}
1117
Brian Osman0006ad02020-11-18 15:38:39 -05001118bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001119 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001120 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001121 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001122 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001123 return false;
1124 }
1125
John Stiles031a7672020-11-13 16:13:18 -05001126 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1127 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1128 return false;
1129 }
1130
John Stiles2d7973a2020-10-02 15:01:03 -04001131 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001132 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001133
John Stiles915a38c2020-09-14 09:38:13 -04001134 // Inline the candidates where we've determined that it's safe to do so.
John Stiles708faba2021-03-19 09:43:23 -04001135 using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1136 std::unique_ptr<Statement>*>;
1137 StatementRemappingTable statementRemappingTable;
1138
John Stiles915a38c2020-09-14 09:38:13 -04001139 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001140 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001141 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001142
John Stiles915a38c2020-09-14 09:38:13 -04001143 // Convert the function call to its inlined equivalent.
John Stiles30fce9c2021-03-18 09:24:06 -04001144 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001145 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001146
John Stiles0c2d14a2021-03-01 10:08:08 -05001147 // Stop if an error was detected during the inlining process.
1148 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1149 break;
John Stiles915a38c2020-09-14 09:38:13 -04001150 }
1151
John Stiles0c2d14a2021-03-01 10:08:08 -05001152 // Ensure that the inlined body has a scope if it needs one.
1153 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1154
1155 // Add references within the inlined body
1156 usage->add(inlinedCall.fInlinedBody.get());
1157
John Stiles708faba2021-03-19 09:43:23 -04001158 // Look up the enclosing statement; remap it if necessary.
1159 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1160 for (;;) {
1161 auto iter = statementRemappingTable.find(enclosingStmt);
1162 if (iter == statementRemappingTable.end()) {
1163 break;
1164 }
1165 enclosingStmt = iter->second;
1166 }
1167
John Stiles0c2d14a2021-03-01 10:08:08 -05001168 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1169 // function, then replace the enclosing statement with that Block.
1170 // Before:
1171 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1172 // fEnclosingStmt = stmt4
1173 // After:
1174 // fInlinedBody = null
1175 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
John Stiles708faba2021-03-19 09:43:23 -04001176 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1177 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
John Stiles0c2d14a2021-03-01 10:08:08 -05001178
John Stiles915a38c2020-09-14 09:38:13 -04001179 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001180 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001181 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1182 madeChanges = true;
1183
John Stiles708faba2021-03-19 09:43:23 -04001184 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1185 // containing many other statements as well. Maintain a fix-up table to account for this.
1186 statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1187
John Stiles031a7672020-11-13 16:13:18 -05001188 // Stop inlining if we've reached our hard cap on new statements.
1189 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1190 break;
1191 }
1192
John Stiles915a38c2020-09-14 09:38:13 -04001193 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1194 // remain valid.
1195 }
1196
1197 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001198}
1199
John Stiles44e96be2020-08-31 13:16:04 -04001200} // namespace SkSL