blob: b5f9c5e70a6bed0739a4610b80262522fbe7f8d1 [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
John Stiles5b408a32021-03-17 09:53:32 -040066 bool visitExpression(const Expression& expr) override {
67 // Do not recurse into expressions.
68 return false;
69 }
70
John Stiles44e96be2020-08-31 13:16:04 -040071 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040072 switch (stmt.kind()) {
73 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040074 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040075 const auto& block = stmt.as<Block>();
76 return block.children().size() &&
77 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040078 }
Ethan Nicholase6592142020-09-08 10:22:09 -040079 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040080 case Statement::Kind::kDo:
81 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040082 // Don't introspect switches or loop structures at all.
83 return false;
84
Ethan Nicholase6592142020-09-08 10:22:09 -040085 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040086 ++fNumReturns;
87 [[fallthrough]];
88
89 default:
John Stiles93442622020-09-11 12:11:27 -040090 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040091 }
92 }
93
94 int fNumReturns = 0;
95 using INHERITED = ProgramVisitor;
96 };
97
98 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
99}
100
John Stiles991b09d2020-09-10 13:33:40 -0400101static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
102 class ContainsRecursiveCall : public ProgramVisitor {
103 public:
104 bool visit(const FunctionDeclaration& funcDecl) {
105 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400106 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
107 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400108 }
109
110 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400111 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400112 return true;
113 }
114 return INHERITED::visitExpression(expr);
115 }
116
117 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400118 if (stmt.is<InlineMarker>() &&
119 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400120 return true;
121 }
122 return INHERITED::visitStatement(stmt);
123 }
124
125 const FunctionDeclaration* fFuncDecl;
126 using INHERITED = ProgramVisitor;
127 };
128
129 return ContainsRecursiveCall{}.visit(funcDecl);
130}
131
John Stiles6d696082020-10-01 10:18:54 -0400132static std::unique_ptr<Statement>* find_parent_statement(
133 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400134 SkASSERT(!stmtStack.empty());
135
136 // Walk the statement stack from back to front, ignoring the last element (which is the
137 // enclosing statement).
138 auto iter = stmtStack.rbegin();
139 ++iter;
140
141 // Anything counts as a parent statement other than a scopeless Block.
142 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400143 std::unique_ptr<Statement>* stmt = *iter;
144 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400145 return stmt;
146 }
147 }
148
149 // There wasn't any parent statement to be found.
150 return nullptr;
151}
152
John Stilese41b4ee2020-09-28 12:28:16 -0400153std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
154 VariableReference::RefKind refKind) {
155 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500156 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400157 return clone;
158}
159
John Stiles77702f12020-12-17 14:38:56 -0500160class CountReturnsWithLimit : public ProgramVisitor {
161public:
162 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
163 this->visitProgramElement(funcDef);
164 }
165
John Stiles5b408a32021-03-17 09:53:32 -0400166 bool visitExpression(const Expression& expr) override {
167 // Do not recurse into expressions.
168 return false;
169 }
170
John Stiles77702f12020-12-17 14:38:56 -0500171 bool visitStatement(const Statement& stmt) override {
172 switch (stmt.kind()) {
173 case Statement::Kind::kReturn: {
174 ++fNumReturns;
175 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
176 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
177 }
John Stilesc5ff4862020-12-22 13:47:05 -0500178 case Statement::Kind::kVarDeclaration: {
179 if (fScopedBlockDepth > 1) {
180 fVariablesInBlocks = true;
181 }
182 return INHERITED::visitStatement(stmt);
183 }
John Stiles77702f12020-12-17 14:38:56 -0500184 case Statement::Kind::kBlock: {
185 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
186 fScopedBlockDepth += depthIncrement;
187 bool result = INHERITED::visitStatement(stmt);
188 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500189 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
190 // If closing this block puts us back at the top level, and we haven't
191 // encountered any return statements yet, any vardecls we may have encountered
192 // up until this point can be ignored. They are out of scope now, and they were
193 // never used in a return statement.
194 fVariablesInBlocks = false;
195 }
John Stiles77702f12020-12-17 14:38:56 -0500196 return result;
197 }
198 default:
199 return INHERITED::visitStatement(stmt);
200 }
201 }
202
203 int fNumReturns = 0;
204 int fDeepestReturn = 0;
205 int fLimit = 0;
206 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500207 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500208 using INHERITED = ProgramVisitor;
209};
210
John Stiles44e96be2020-08-31 13:16:04 -0400211} // namespace
212
John Stiles77702f12020-12-17 14:38:56 -0500213Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
214 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
215 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500216 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
217 return ReturnComplexity::kEarlyReturns;
218 }
John Stilesc5ff4862020-12-22 13:47:05 -0500219 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500220 return ReturnComplexity::kScopedReturns;
221 }
John Stilesc5ff4862020-12-22 13:47:05 -0500222 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
223 return ReturnComplexity::kScopedReturns;
224 }
John Stiles8937cd42021-03-17 19:32:59 +0000225 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500226}
227
John Stilesb61ee902020-09-21 12:26:59 -0400228void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
229 // No changes necessary if this statement isn't actually a block.
230 if (!inlinedBody || !inlinedBody->is<Block>()) {
231 return;
232 }
233
234 // No changes necessary if the parent statement doesn't require a scope.
235 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500236 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400237 return;
238 }
239
240 Block& block = inlinedBody->as<Block>();
241
242 // The inliner will create inlined function bodies as a Block containing multiple statements,
243 // but no scope. Normally, this is fine, but if this block is used as the statement for a
244 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
245 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
246 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
247 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
248 // absorbing the following statement into our loop--so we also add a scope to these.
249 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400250 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400251 // We found an explicit scope; all is well.
252 return;
253 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400254 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400255 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
256 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400257 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400258 return;
259 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400260 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400261 // This block has exactly one thing inside, and it's not another block. No need to scope
262 // it.
263 return;
264 }
265 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400266 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400267 }
268}
269
John Stilesd1204642021-02-17 16:30:02 -0500270void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400271 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500272 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500273 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400274}
275
276std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
277 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500278 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400279 const Expression& expression) {
280 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
281 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500282 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400283 }
284 return nullptr;
285 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400286 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
287 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400288 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400289 for (const std::unique_ptr<Expression>& arg : originalArgs) {
290 args.push_back(expr(arg));
291 }
292 return args;
293 };
294
Ethan Nicholase6592142020-09-08 10:22:09 -0400295 switch (expression.kind()) {
296 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500297 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500298 return BinaryExpression::Make(*fContext,
299 expr(binaryExpr.left()),
300 binaryExpr.getOperator(),
301 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400302 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400303 case Expression::Kind::kBoolLiteral:
304 case Expression::Kind::kIntLiteral:
305 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400306 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400307 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400308 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500309 auto inlinedCtor = Constructor::Convert(
310 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
311 argList(constructor.arguments()));
312 SkASSERT(inlinedCtor);
313 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400314 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400315 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400316 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400317 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400318 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400319 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500320 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400321 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400322 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400323 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500324 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400325 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400326 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400327 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilescd7ba502021-03-19 10:54:59 -0400328 return FunctionCall::Make(*fContext,
329 offset,
330 funcCall.type().clone(symbolTableForExpression),
331 funcCall.function(),
332 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400333 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400334 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400335 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400336 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400337 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500338 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400339 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400340 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400341 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500342 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400343 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400344 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400345 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500346 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400347 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400348 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400349 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400350 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400351 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500352 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400353 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400354 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400355 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500356 return TernaryExpression::Make(*fContext, expr(t.test()),
357 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400358 }
Brian Osman83ba9302020-09-11 13:33:46 -0400359 case Expression::Kind::kTypeReference:
360 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400361 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400362 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400363 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400364 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400365 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400366 }
367 return v.clone();
368 }
369 default:
370 SkASSERT(false);
371 return nullptr;
372 }
373}
374
375std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
376 VariableRewriteMap* varMap,
377 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500378 std::unique_ptr<Expression>* resultExpr,
379 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400380 const Statement& statement,
381 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400382 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
383 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400384 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500385 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400386 }
387 return nullptr;
388 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400389 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400390 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400391 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400392 for (const std::unique_ptr<Statement>& child : block.children()) {
393 result.push_back(stmt(child));
394 }
395 return result;
396 };
John Stiles44e96be2020-08-31 13:16:04 -0400397 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
398 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500399 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400400 }
401 return nullptr;
402 };
John Stiles031a7672020-11-13 16:13:18 -0500403
404 ++fInlinedStatementCounter;
405
Ethan Nicholase6592142020-09-08 10:22:09 -0400406 switch (statement.kind()) {
407 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400408 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500409 return Block::Make(offset, blockStmts(b),
410 SymbolTable::WrapIfBuiltin(b.symbolTable()),
411 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400412 }
413
Ethan Nicholase6592142020-09-08 10:22:09 -0400414 case Statement::Kind::kBreak:
415 case Statement::Kind::kContinue:
416 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400417 return statement.clone();
418
Ethan Nicholase6592142020-09-08 10:22:09 -0400419 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400420 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500421 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400422 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400423 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400424 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500425 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400426 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400427 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400428 const ForStatement& f = statement.as<ForStatement>();
429 // need to ensure initializer is evaluated first so that we've already remapped its
430 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400431 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500432 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
433 expr(f.next()), stmt(f.statement()),
434 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400435 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400436 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400437 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500438 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
439 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400440 }
John Stiles98c1f822020-09-09 14:18:53 -0400441 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400442 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400443 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500444
Ethan Nicholase6592142020-09-08 10:22:09 -0400445 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400446 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500447 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400448 // This function doesn't return a value. We won't inline functions with early
449 // returns, so a return statement is a no-op and can be treated as such.
450 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400451 }
John Stiles77702f12020-12-17 14:38:56 -0500452
John Stilesc5ff4862020-12-22 13:47:05 -0500453 // If a function only contains a single return, and it doesn't reference variables from
454 // inside an Block's scope, we don't need to store the result in a variable at all. Just
455 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500456 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500457 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500458 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500459 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500460 }
461
462 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500463 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500464 auto assignment = ExpressionStatement::Make(
465 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500466 BinaryExpression::Make(
467 *fContext,
468 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500469 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500470 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500471
John Stiles77702f12020-12-17 14:38:56 -0500472 // Functions without early returns aren't wrapped in a for loop and don't need to worry
473 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500474 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400475 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400476 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400477 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500478 StatementArray cases;
479 cases.reserve_back(ss.cases().size());
480 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
481 const SwitchCase& sc = statement->as<SwitchCase>();
482 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
483 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400484 }
John Stilese1d1b082021-02-23 13:44:36 -0500485 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
486 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400487 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400488 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400489 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000490 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500491 const Variable& variable = decl.var();
492
John Stiles35fee4c2020-12-16 18:25:14 +0000493 // We assign unique names to inlined variables--scopes hide most of the problems in this
494 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
495 // names are important.
John Stilesd51c9792021-03-18 11:40:14 -0400496 const String* name = symbolTableForStatement->takeOwnershipOfString(
497 fMangler.uniqueName(variable.name(), symbolTableForStatement));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500498 auto clonedVar = std::make_unique<Variable>(
499 offset,
500 &variable.modifiers(),
John Stilesd51c9792021-03-18 11:40:14 -0400501 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500502 variable.type().clone(symbolTableForStatement),
503 isBuiltinCode,
504 variable.storage());
505 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
506 auto result = std::make_unique<VarDeclaration>(clonedVar.get(),
John Stilesddcc8432021-01-15 15:32:32 -0500507 decl.baseType().clone(symbolTableForStatement),
508 decl.arraySize(),
John Stiles35fee4c2020-12-16 18:25:14 +0000509 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500510 clonedVar->setDeclaration(result.get());
511 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
512 return std::move(result);
John Stiles44e96be2020-08-31 13:16:04 -0400513 }
John Stiles44e96be2020-08-31 13:16:04 -0400514 default:
515 SkASSERT(false);
516 return nullptr;
517 }
518}
519
John Stiles7b920442020-12-17 10:43:41 -0500520Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
521 const Type* type,
522 SymbolTable* symbolTable,
523 Modifiers modifiers,
524 bool isBuiltinCode,
525 std::unique_ptr<Expression>* initialValue) {
526 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
527 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
528 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500529 if (type->isLiteral()) {
530 SkDEBUGFAIL("found a $literal type while inlining");
531 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500532 }
533
John Stilesbff24ab2021-03-17 13:20:10 -0400534 // Out parameters aren't supported.
535 SkASSERT(!(modifiers.fFlags & Modifiers::kOut_Flag));
536
John Stiles7b920442020-12-17 10:43:41 -0500537 // Provide our new variable with a unique name, and add it to our symbol table.
John Stilesd51c9792021-03-18 11:40:14 -0400538 const String* name =
539 symbolTable->takeOwnershipOfString(fMangler.uniqueName(baseName, symbolTable));
John Stiles7b920442020-12-17 10:43:41 -0500540
541 // Create our new variable and add it to the symbol table.
542 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500543 auto var = std::make_unique<Variable>(/*offset=*/-1,
544 fModifiers->addToPool(Modifiers()),
John Stilesd51c9792021-03-18 11:40:14 -0400545 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500546 type,
547 isBuiltinCode,
548 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500549
John Stilesbff24ab2021-03-17 13:20:10 -0400550 // Create our variable declaration.
551 result.fVarDecl = std::make_unique<VarDeclaration>(var.get(), type, /*arraySize=*/0,
552 std::move(*initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500553 var->setDeclaration(&result.fVarDecl->as<VarDeclaration>());
554 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500555 return result;
556}
557
John Stiles6eadf132020-09-08 10:16:10 -0400558Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500559 std::shared_ptr<SymbolTable> symbolTable,
John Stiles30fce9c2021-03-18 09:24:06 -0400560 const ProgramUsage& usage,
Brian Osman3887a012020-09-30 13:22:27 -0400561 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400562 // Inlining is more complicated here than in a typical compiler, because we have to have a
563 // high-level IR and can't just drop statements into the middle of an expression or even use
564 // gotos.
565 //
566 // Since we can't insert statements into an expression, we run the inline function as extra
567 // statements before the statement we're currently processing, relying on a lack of execution
568 // order guarantees. Since we can't use gotos (which are normally used to replace return
569 // statements), we wrap the whole function in a loop and use break statements to jump to the
570 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400571 SkASSERT(fContext);
572 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400573 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400574
John Stiles8e3b6be2020-10-13 11:14:08 -0400575 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400576 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400577 const FunctionDefinition& function = *call->function().definition();
John Stiles28257db2021-03-17 15:18:09 -0400578 const Block& body = function.body()->as<Block>();
John Stiles77702f12020-12-17 14:38:56 -0500579 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400580
John Stiles28257db2021-03-17 15:18:09 -0400581 StatementArray inlineStatements;
582 int expectedStmtCount = 1 + // Inline marker
583 1 + // Result variable
584 arguments.size() + // Function argument temp-vars
585 body.children().size(); // Inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400586
John Stiles28257db2021-03-17 15:18:09 -0400587 inlineStatements.reserve_back(expectedStmtCount);
588 inlineStatements.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400589
John Stilese41b4ee2020-09-28 12:28:16 -0400590 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500591 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400592 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500593 // Create a variable to hold the result in the extra statements. We don't need to do this
594 // for void-return functions, or in cases that are simple enough that we can just replace
595 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400596 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500597 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
598 &function.declaration().returnType(),
599 symbolTable.get(), Modifiers{},
600 caller->isBuiltin(), &noInitialValue);
John Stiles28257db2021-03-17 15:18:09 -0400601 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500602 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500603 }
John Stiles44e96be2020-08-31 13:16:04 -0400604
605 // Create variables in the extra statements to hold the arguments, and assign the arguments to
606 // them.
607 VariableRewriteMap varMap;
John Stilesbff24ab2021-03-17 13:20:10 -0400608 for (int i = 0; i < arguments.count(); ++i) {
John Stiles049f0df2021-03-19 09:39:44 -0400609 // If the parameter isn't written to within the inline function ...
John Stilesbff24ab2021-03-17 13:20:10 -0400610 const Variable* param = function.declaration().parameters()[i];
John Stiles049f0df2021-03-19 09:39:44 -0400611 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
612 if (!paramUsage.fWrite) {
613 // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
614 // or any expression without side effects that is only accessed at most once...
615 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arguments[i])
616 : !arguments[i]->hasSideEffects()) {
John Stilesf201af82020-09-29 16:57:55 -0400617 // ... we don't need to copy it at all! We can just use the existing expression.
618 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400619 continue;
620 }
621 }
John Stiles7b920442020-12-17 10:43:41 -0500622 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
623 symbolTable.get(), param->modifiers(),
624 caller->isBuiltin(), &arguments[i]);
John Stiles28257db2021-03-17 15:18:09 -0400625 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500626 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400627 }
628
John Stiles7b920442020-12-17 10:43:41 -0500629 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles28257db2021-03-17 15:18:09 -0400630 inlineStatements.push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
631 &resultExpr, returnComplexity, *stmt,
632 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400633 }
634
John Stiles28257db2021-03-17 15:18:09 -0400635 SkASSERT(inlineStatements.count() <= expectedStmtCount);
636
John Stilesbf16b6c2021-03-12 19:24:31 -0500637 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
638 // MakeUnscoped. This is because we need to add another child statement to the Block later.
John Stiles28257db2021-03-17 15:18:09 -0400639 InlinedCall inlinedCall;
640 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlineStatements),
John Stilesbf16b6c2021-03-12 19:24:31 -0500641 /*symbols=*/nullptr, /*isScope=*/false);
642
John Stiles0c2d14a2021-03-01 10:08:08 -0500643 if (resultExpr) {
644 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400645 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400646 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400647 // It's a void function, so it doesn't actually result in anything, but we have to return
648 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500649 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500650 } else {
651 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500652 // returned anything on any path! This should have been detected in the function finalizer.
653 // Still, discard our output and generate an error.
654 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
655 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500656 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500657 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500658 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400659 }
660
John Stiles44e96be2020-08-31 13:16:04 -0400661 return inlinedCall;
662}
663
John Stiles2d7973a2020-10-02 15:01:03 -0400664bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400665 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500666 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400667 return false;
668 }
669
John Stiles031a7672020-11-13 16:13:18 -0500670 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
671 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
672 return false;
673 }
674
John Stiles2d7973a2020-10-02 15:01:03 -0400675 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400676 // Can't inline something if we don't actually have its definition.
677 return false;
678 }
John Stiles2d7973a2020-10-02 15:01:03 -0400679
John Stiles0dd1a772021-03-09 22:14:27 -0500680 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
681 // Refuse to inline functions decorated with `noinline`.
682 return false;
683 }
684
John Stilesbff24ab2021-03-17 13:20:10 -0400685 // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
686 for (const Variable* param : functionDef->declaration().parameters()) {
687 if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
688 return false;
689 }
690 }
691
John Stilesdc208472021-03-17 10:58:16 -0400692 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
693 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400694}
695
John Stiles2d7973a2020-10-02 15:01:03 -0400696// A candidate function for inlining, containing everything that `inlineCall` needs.
697struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500698 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400699 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
700 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
701 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
702 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400703};
John Stiles93442622020-09-11 12:11:27 -0400704
John Stiles2d7973a2020-10-02 15:01:03 -0400705struct InlineCandidateList {
706 std::vector<InlineCandidate> fCandidates;
707};
708
709class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400710public:
711 // A list of all the inlining candidates we found during analysis.
712 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400713
John Stiles70957c82020-10-02 16:42:10 -0400714 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
715 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500716 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400717 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
718 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
719 // inliner might replace a statement with a block containing the statement.
720 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
721 // The function that we're currently processing (i.e. inlining into).
722 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400723
Brian Osman0006ad02020-11-18 15:38:39 -0500724 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500725 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500726 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400727 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500728 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400729
Brian Osman0006ad02020-11-18 15:38:39 -0500730 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400731 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400732 }
733
John Stiles70957c82020-10-02 16:42:10 -0400734 fSymbolTableStack.pop_back();
735 fCandidateList = nullptr;
736 }
737
738 void visitProgramElement(ProgramElement* pe) {
739 switch (pe->kind()) {
740 case ProgramElement::Kind::kFunction: {
741 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500742 fEnclosingFunction = &funcDef;
743 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400744 break;
John Stiles93442622020-09-11 12:11:27 -0400745 }
John Stiles70957c82020-10-02 16:42:10 -0400746 default:
747 // The inliner can't operate outside of a function's scope.
748 break;
749 }
750 }
751
752 void visitStatement(std::unique_ptr<Statement>* stmt,
753 bool isViableAsEnclosingStatement = true) {
754 if (!*stmt) {
755 return;
John Stiles93442622020-09-11 12:11:27 -0400756 }
757
John Stiles70957c82020-10-02 16:42:10 -0400758 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
759 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400760
John Stiles70957c82020-10-02 16:42:10 -0400761 if (isViableAsEnclosingStatement) {
762 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400763 }
764
John Stiles70957c82020-10-02 16:42:10 -0400765 switch ((*stmt)->kind()) {
766 case Statement::Kind::kBreak:
767 case Statement::Kind::kContinue:
768 case Statement::Kind::kDiscard:
769 case Statement::Kind::kInlineMarker:
770 case Statement::Kind::kNop:
771 break;
772
773 case Statement::Kind::kBlock: {
774 Block& block = (*stmt)->as<Block>();
775 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500776 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400777 }
778
779 for (std::unique_ptr<Statement>& stmt : block.children()) {
780 this->visitStatement(&stmt);
781 }
782 break;
John Stiles93442622020-09-11 12:11:27 -0400783 }
John Stiles70957c82020-10-02 16:42:10 -0400784 case Statement::Kind::kDo: {
785 DoStatement& doStmt = (*stmt)->as<DoStatement>();
786 // The loop body is a candidate for inlining.
787 this->visitStatement(&doStmt.statement());
788 // The inliner isn't smart enough to inline the test-expression for a do-while
789 // loop at this time. There are two limitations:
790 // - We would need to insert the inlined-body block at the very end of the do-
791 // statement's inner fStatement. We don't support that today, but it's doable.
792 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
793 // would skip over the inlined block that evaluates the test expression. There
794 // isn't a good fix for this--any workaround would be more complex than the cost
795 // of a function call. However, loops that don't use `continue` would still be
796 // viable candidates for inlining.
797 break;
John Stiles93442622020-09-11 12:11:27 -0400798 }
John Stiles70957c82020-10-02 16:42:10 -0400799 case Statement::Kind::kExpression: {
800 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
801 this->visitExpression(&expr.expression());
802 break;
803 }
804 case Statement::Kind::kFor: {
805 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400806 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500807 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400808 }
809
810 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400811 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400812 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400813 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400814
815 // The inliner isn't smart enough to inline the test- or increment-expressions
816 // of a for loop loop at this time. There are a handful of limitations:
817 // - We would need to insert the test-expression block at the very beginning of the
818 // for-loop's inner fStatement, and the increment-expression block at the very
819 // end. We don't support that today, but it's doable.
820 // - The for-loop's built-in test-expression would need to be dropped entirely,
821 // and the loop would be halted via a break statement at the end of the inlined
822 // test-expression. This is again something we don't support today, but it could
823 // be implemented.
824 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
825 // that would skip over the inlined block that evaluates the increment expression.
826 // There isn't a good fix for this--any workaround would be more complex than the
827 // cost of a function call. However, loops that don't use `continue` would still
828 // be viable candidates for increment-expression inlining.
829 break;
830 }
831 case Statement::Kind::kIf: {
832 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400833 this->visitExpression(&ifStmt.test());
834 this->visitStatement(&ifStmt.ifTrue());
835 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400836 break;
837 }
838 case Statement::Kind::kReturn: {
839 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400840 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400841 break;
842 }
843 case Statement::Kind::kSwitch: {
844 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400845 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500846 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400847 }
848
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400849 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500850 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400851 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500852 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400853 }
854 break;
855 }
856 case Statement::Kind::kVarDeclaration: {
857 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
858 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400859 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400860 break;
861 }
John Stiles70957c82020-10-02 16:42:10 -0400862 default:
863 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400864 }
865
John Stiles70957c82020-10-02 16:42:10 -0400866 // Pop our symbol and enclosing-statement stacks.
867 fSymbolTableStack.resize(oldSymbolStackSize);
868 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
869 }
870
871 void visitExpression(std::unique_ptr<Expression>* expr) {
872 if (!*expr) {
873 return;
John Stiles93442622020-09-11 12:11:27 -0400874 }
John Stiles70957c82020-10-02 16:42:10 -0400875
876 switch ((*expr)->kind()) {
877 case Expression::Kind::kBoolLiteral:
878 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500879 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400880 case Expression::Kind::kFieldAccess:
881 case Expression::Kind::kFloatLiteral:
882 case Expression::Kind::kFunctionReference:
883 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400884 case Expression::Kind::kSetting:
885 case Expression::Kind::kTypeReference:
886 case Expression::Kind::kVariableReference:
887 // Nothing to scan here.
888 break;
889
890 case Expression::Kind::kBinary: {
891 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400892 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400893
894 // Logical-and and logical-or binary expressions do not inline the right side,
895 // because that would invalidate short-circuiting. That is, when evaluating
896 // expressions like these:
897 // (false && x()) // always false
898 // (true || y()) // always true
899 // It is illegal for side-effects from x() or y() to occur. The simplest way to
900 // enforce that rule is to avoid inlining the right side entirely. However, it is
901 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500902 Operator op = binaryExpr.getOperator();
903 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
904 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400905 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400906 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400907 }
908 break;
909 }
910 case Expression::Kind::kConstructor: {
911 Constructor& constructorExpr = (*expr)->as<Constructor>();
912 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
913 this->visitExpression(&arg);
914 }
915 break;
916 }
917 case Expression::Kind::kExternalFunctionCall: {
918 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
919 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
920 this->visitExpression(&arg);
921 }
922 break;
923 }
924 case Expression::Kind::kFunctionCall: {
925 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400926 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -0400927 this->visitExpression(&arg);
928 }
929 this->addInlineCandidate(expr);
930 break;
931 }
John Stiles708faba2021-03-19 09:43:23 -0400932 case Expression::Kind::kIndex: {
John Stiles70957c82020-10-02 16:42:10 -0400933 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400934 this->visitExpression(&indexExpr.base());
935 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -0400936 break;
937 }
938 case Expression::Kind::kPostfix: {
939 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400940 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400941 break;
942 }
943 case Expression::Kind::kPrefix: {
944 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400945 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400946 break;
947 }
948 case Expression::Kind::kSwizzle: {
949 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400950 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -0400951 break;
952 }
953 case Expression::Kind::kTernary: {
954 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
955 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -0400956 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -0400957 // The true- and false-expressions cannot be inlined, because we are only allowed to
958 // evaluate one side.
959 break;
960 }
961 default:
962 SkUNREACHABLE;
963 }
964 }
965
966 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
967 fCandidateList->fCandidates.push_back(
968 InlineCandidate{fSymbolTableStack.back(),
969 find_parent_statement(fEnclosingStmtStack),
970 fEnclosingStmtStack.back(),
971 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -0500972 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -0400973 }
John Stiles2d7973a2020-10-02 15:01:03 -0400974};
John Stiles93442622020-09-11 12:11:27 -0400975
John Stiles9b9415e2020-11-23 14:48:06 -0500976static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
977 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
978}
John Stiles915a38c2020-09-14 09:38:13 -0400979
John Stiles9b9415e2020-11-23 14:48:06 -0500980bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
981 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -0400982 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -0400983 if (wasInserted) {
984 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +0000985 iter->second = this->isSafeToInline(funcDecl.definition()) &&
986 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -0400987 }
988
John Stiles2d7973a2020-10-02 15:01:03 -0400989 return iter->second;
990}
991
John Stiles9b9415e2020-11-23 14:48:06 -0500992int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
993 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -0400994 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -0500995 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -0500996 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -0400997 }
John Stiles2d7973a2020-10-02 15:01:03 -0400998 return iter->second;
999}
1000
Brian Osman0006ad02020-11-18 15:38:39 -05001001void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001002 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001003 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001004 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1005 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1006 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1007 // `const T&`.
1008 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001009 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001010
John Stiles0ad233f2020-11-25 11:02:05 -05001011 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001012 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001013 if (candidates.empty()) {
1014 return;
1015 }
1016
1017 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001018 InlinabilityCache cache;
1019 candidates.erase(std::remove_if(candidates.begin(),
1020 candidates.end(),
1021 [&](const InlineCandidate& candidate) {
1022 return !this->candidateCanBeInlined(candidate, &cache);
1023 }),
1024 candidates.end());
1025
John Stiles0ad233f2020-11-25 11:02:05 -05001026 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1027 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001028 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001029 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001030 }
John Stiles0ad233f2020-11-25 11:02:05 -05001031
1032 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1033 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1034 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1035 FunctionSizeCache functionSizeCache;
1036 FunctionSizeCache candidateTotalCost;
1037 for (InlineCandidate& candidate : candidates) {
1038 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1039 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1040 }
1041
John Stilesd1204642021-02-17 16:30:02 -05001042 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1043 [&](const InlineCandidate& candidate) {
1044 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1045 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1046 // Functions marked `inline` ignore size limitations.
1047 return false;
1048 }
1049 if (usage->get(fnDecl) == 1) {
1050 // If a function is only used once, it's cost-free to inline.
1051 return false;
1052 }
1053 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1054 // We won't exceed the inline threshold by inlining this.
1055 return false;
1056 }
1057 // Inlining this function will add too many IRNodes.
1058 return true;
1059 }),
1060 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001061}
1062
Brian Osman0006ad02020-11-18 15:38:39 -05001063bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001064 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001065 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001066 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001067 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001068 return false;
1069 }
1070
John Stiles031a7672020-11-13 16:13:18 -05001071 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1072 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1073 return false;
1074 }
1075
John Stiles2d7973a2020-10-02 15:01:03 -04001076 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001077 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001078
John Stiles915a38c2020-09-14 09:38:13 -04001079 // Inline the candidates where we've determined that it's safe to do so.
John Stiles708faba2021-03-19 09:43:23 -04001080 using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1081 std::unique_ptr<Statement>*>;
1082 StatementRemappingTable statementRemappingTable;
1083
John Stiles915a38c2020-09-14 09:38:13 -04001084 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001085 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001086 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001087
John Stiles915a38c2020-09-14 09:38:13 -04001088 // Convert the function call to its inlined equivalent.
John Stiles30fce9c2021-03-18 09:24:06 -04001089 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001090 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001091
John Stiles0c2d14a2021-03-01 10:08:08 -05001092 // Stop if an error was detected during the inlining process.
1093 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1094 break;
John Stiles915a38c2020-09-14 09:38:13 -04001095 }
1096
John Stiles0c2d14a2021-03-01 10:08:08 -05001097 // Ensure that the inlined body has a scope if it needs one.
1098 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1099
1100 // Add references within the inlined body
1101 usage->add(inlinedCall.fInlinedBody.get());
1102
John Stiles708faba2021-03-19 09:43:23 -04001103 // Look up the enclosing statement; remap it if necessary.
1104 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1105 for (;;) {
1106 auto iter = statementRemappingTable.find(enclosingStmt);
1107 if (iter == statementRemappingTable.end()) {
1108 break;
1109 }
1110 enclosingStmt = iter->second;
1111 }
1112
John Stiles0c2d14a2021-03-01 10:08:08 -05001113 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1114 // function, then replace the enclosing statement with that Block.
1115 // Before:
1116 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1117 // fEnclosingStmt = stmt4
1118 // After:
1119 // fInlinedBody = null
1120 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
John Stiles708faba2021-03-19 09:43:23 -04001121 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1122 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
John Stiles0c2d14a2021-03-01 10:08:08 -05001123
John Stiles915a38c2020-09-14 09:38:13 -04001124 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001125 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001126 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1127 madeChanges = true;
1128
John Stiles708faba2021-03-19 09:43:23 -04001129 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1130 // containing many other statements as well. Maintain a fix-up table to account for this.
1131 statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1132
John Stiles031a7672020-11-13 16:13:18 -05001133 // Stop inlining if we've reached our hard cap on new statements.
1134 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1135 break;
1136 }
1137
John Stiles915a38c2020-09-14 09:38:13 -04001138 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1139 // remain valid.
1140 }
1141
1142 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001143}
1144
John Stiles44e96be2020-08-31 13:16:04 -04001145} // namespace SkSL