blob: 422013b0c0296f0f947698267b66f2f7b0e878b2 [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 Stiles44e96be2020-08-31 13:16:04 -040022#include "src/sksl/ir/SkSLContinueStatement.h"
23#include "src/sksl/ir/SkSLDiscardStatement.h"
24#include "src/sksl/ir/SkSLDoStatement.h"
25#include "src/sksl/ir/SkSLEnum.h"
26#include "src/sksl/ir/SkSLExpressionStatement.h"
27#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050028#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040029#include "src/sksl/ir/SkSLField.h"
30#include "src/sksl/ir/SkSLFieldAccess.h"
31#include "src/sksl/ir/SkSLFloatLiteral.h"
32#include "src/sksl/ir/SkSLForStatement.h"
33#include "src/sksl/ir/SkSLFunctionCall.h"
34#include "src/sksl/ir/SkSLFunctionDeclaration.h"
35#include "src/sksl/ir/SkSLFunctionDefinition.h"
36#include "src/sksl/ir/SkSLFunctionReference.h"
37#include "src/sksl/ir/SkSLIfStatement.h"
38#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040039#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040040#include "src/sksl/ir/SkSLIntLiteral.h"
41#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040042#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040043#include "src/sksl/ir/SkSLPostfixExpression.h"
44#include "src/sksl/ir/SkSLPrefixExpression.h"
45#include "src/sksl/ir/SkSLReturnStatement.h"
46#include "src/sksl/ir/SkSLSetting.h"
47#include "src/sksl/ir/SkSLSwitchCase.h"
48#include "src/sksl/ir/SkSLSwitchStatement.h"
49#include "src/sksl/ir/SkSLSwizzle.h"
50#include "src/sksl/ir/SkSLTernaryExpression.h"
51#include "src/sksl/ir/SkSLUnresolvedFunction.h"
52#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040053#include "src/sksl/ir/SkSLVariable.h"
54#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040055
56namespace SkSL {
57namespace {
58
John Stiles031a7672020-11-13 16:13:18 -050059static constexpr int kInlinedStatementLimit = 2500;
60
John Stiles44e96be2020-08-31 13:16:04 -040061static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
62 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
63 public:
64 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
65 this->visitProgramElement(funcDef);
66 }
67
John Stiles5b408a32021-03-17 09:53:32 -040068 bool visitExpression(const Expression& expr) override {
69 // Do not recurse into expressions.
70 return false;
71 }
72
John Stiles44e96be2020-08-31 13:16:04 -040073 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040074 switch (stmt.kind()) {
75 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040076 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040077 const auto& block = stmt.as<Block>();
78 return block.children().size() &&
79 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040080 }
Ethan Nicholase6592142020-09-08 10:22:09 -040081 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040082 case Statement::Kind::kDo:
83 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040084 // Don't introspect switches or loop structures at all.
85 return false;
86
Ethan Nicholase6592142020-09-08 10:22:09 -040087 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040088 ++fNumReturns;
89 [[fallthrough]];
90
91 default:
John Stiles93442622020-09-11 12:11:27 -040092 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040093 }
94 }
95
96 int fNumReturns = 0;
97 using INHERITED = ProgramVisitor;
98 };
99
100 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
101}
102
John Stiles991b09d2020-09-10 13:33:40 -0400103static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
104 class ContainsRecursiveCall : public ProgramVisitor {
105 public:
106 bool visit(const FunctionDeclaration& funcDecl) {
107 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400108 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
109 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400110 }
111
112 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400113 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400114 return true;
115 }
116 return INHERITED::visitExpression(expr);
117 }
118
119 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400120 if (stmt.is<InlineMarker>() &&
121 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400122 return true;
123 }
124 return INHERITED::visitStatement(stmt);
125 }
126
127 const FunctionDeclaration* fFuncDecl;
128 using INHERITED = ProgramVisitor;
129 };
130
131 return ContainsRecursiveCall{}.visit(funcDecl);
132}
133
John Stiles6d696082020-10-01 10:18:54 -0400134static std::unique_ptr<Statement>* find_parent_statement(
135 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400136 SkASSERT(!stmtStack.empty());
137
138 // Walk the statement stack from back to front, ignoring the last element (which is the
139 // enclosing statement).
140 auto iter = stmtStack.rbegin();
141 ++iter;
142
143 // Anything counts as a parent statement other than a scopeless Block.
144 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400145 std::unique_ptr<Statement>* stmt = *iter;
146 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400147 return stmt;
148 }
149 }
150
151 // There wasn't any parent statement to be found.
152 return nullptr;
153}
154
John Stilese41b4ee2020-09-28 12:28:16 -0400155std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
156 VariableReference::RefKind refKind) {
157 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500158 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400159 return clone;
160}
161
John Stiles77702f12020-12-17 14:38:56 -0500162class CountReturnsWithLimit : public ProgramVisitor {
163public:
164 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
165 this->visitProgramElement(funcDef);
166 }
167
John Stiles5b408a32021-03-17 09:53:32 -0400168 bool visitExpression(const Expression& expr) override {
169 // Do not recurse into expressions.
170 return false;
171 }
172
John Stiles77702f12020-12-17 14:38:56 -0500173 bool visitStatement(const Statement& stmt) override {
174 switch (stmt.kind()) {
175 case Statement::Kind::kReturn: {
176 ++fNumReturns;
177 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
178 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
179 }
John Stilesc5ff4862020-12-22 13:47:05 -0500180 case Statement::Kind::kVarDeclaration: {
181 if (fScopedBlockDepth > 1) {
182 fVariablesInBlocks = true;
183 }
184 return INHERITED::visitStatement(stmt);
185 }
John Stiles77702f12020-12-17 14:38:56 -0500186 case Statement::Kind::kBlock: {
187 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
188 fScopedBlockDepth += depthIncrement;
189 bool result = INHERITED::visitStatement(stmt);
190 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500191 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
192 // If closing this block puts us back at the top level, and we haven't
193 // encountered any return statements yet, any vardecls we may have encountered
194 // up until this point can be ignored. They are out of scope now, and they were
195 // never used in a return statement.
196 fVariablesInBlocks = false;
197 }
John Stiles77702f12020-12-17 14:38:56 -0500198 return result;
199 }
200 default:
201 return INHERITED::visitStatement(stmt);
202 }
203 }
204
205 int fNumReturns = 0;
206 int fDeepestReturn = 0;
207 int fLimit = 0;
208 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500209 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500210 using INHERITED = ProgramVisitor;
211};
212
John Stiles44e96be2020-08-31 13:16:04 -0400213} // namespace
214
John Stiles77702f12020-12-17 14:38:56 -0500215Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
216 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
217 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500218 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
219 return ReturnComplexity::kEarlyReturns;
220 }
John Stilesc5ff4862020-12-22 13:47:05 -0500221 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500222 return ReturnComplexity::kScopedReturns;
223 }
John Stilesc5ff4862020-12-22 13:47:05 -0500224 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
225 return ReturnComplexity::kScopedReturns;
226 }
John Stiles8937cd42021-03-17 19:32:59 +0000227 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500228}
229
John Stilesb61ee902020-09-21 12:26:59 -0400230void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
231 // No changes necessary if this statement isn't actually a block.
232 if (!inlinedBody || !inlinedBody->is<Block>()) {
233 return;
234 }
235
236 // No changes necessary if the parent statement doesn't require a scope.
237 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500238 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400239 return;
240 }
241
242 Block& block = inlinedBody->as<Block>();
243
244 // The inliner will create inlined function bodies as a Block containing multiple statements,
245 // but no scope. Normally, this is fine, but if this block is used as the statement for a
246 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
247 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
248 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
249 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
250 // absorbing the following statement into our loop--so we also add a scope to these.
251 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400252 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400253 // We found an explicit scope; all is well.
254 return;
255 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400256 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400257 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
258 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400259 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400260 return;
261 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400262 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400263 // This block has exactly one thing inside, and it's not another block. No need to scope
264 // it.
265 return;
266 }
267 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400268 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400269 }
270}
271
John Stilesd1204642021-02-17 16:30:02 -0500272void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400273 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500274 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500275 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400276}
277
278std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
279 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500280 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400281 const Expression& expression) {
282 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
283 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500284 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400285 }
286 return nullptr;
287 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400288 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
289 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400290 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400291 for (const std::unique_ptr<Expression>& arg : originalArgs) {
292 args.push_back(expr(arg));
293 }
294 return args;
295 };
296
Ethan Nicholase6592142020-09-08 10:22:09 -0400297 switch (expression.kind()) {
298 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500299 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500300 return BinaryExpression::Make(*fContext,
301 expr(binaryExpr.left()),
302 binaryExpr.getOperator(),
303 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400304 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400305 case Expression::Kind::kBoolLiteral:
306 case Expression::Kind::kIntLiteral:
307 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400308 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400309 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400310 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500311 auto inlinedCtor = Constructor::Convert(
312 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
313 argList(constructor.arguments()));
314 SkASSERT(inlinedCtor);
315 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400316 }
John Stiles7384b372021-04-01 13:48:15 -0400317 case Expression::Kind::kConstructorArray: {
318 const ConstructorArray& ctor = expression.as<ConstructorArray>();
319 return ConstructorArray::Make(*fContext, offset,
320 *ctor.type().clone(symbolTableForExpression),
321 argList(ctor.arguments()));
322 }
John Stilese1182782021-03-30 22:09:37 -0400323 case Expression::Kind::kConstructorDiagonalMatrix: {
324 const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
325 return ConstructorDiagonalMatrix::Make(*fContext, offset,
326 *ctor.type().clone(symbolTableForExpression),
327 expr(ctor.argument()));
328 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400329 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400330 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400331 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400332 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400333 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500334 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400335 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400336 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400337 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500338 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400339 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400340 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400341 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilescd7ba502021-03-19 10:54:59 -0400342 return FunctionCall::Make(*fContext,
343 offset,
344 funcCall.type().clone(symbolTableForExpression),
345 funcCall.function(),
346 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400347 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400348 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400349 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400350 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400351 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500352 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400353 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400354 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400355 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500356 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400357 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400358 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400359 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500360 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400361 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400362 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400363 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400364 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400365 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500366 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400367 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400368 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400369 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500370 return TernaryExpression::Make(*fContext, expr(t.test()),
371 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400372 }
Brian Osman83ba9302020-09-11 13:33:46 -0400373 case Expression::Kind::kTypeReference:
374 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400375 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400376 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400377 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400378 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400379 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400380 }
381 return v.clone();
382 }
383 default:
384 SkASSERT(false);
385 return nullptr;
386 }
387}
388
389std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
390 VariableRewriteMap* varMap,
391 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500392 std::unique_ptr<Expression>* resultExpr,
393 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400394 const Statement& statement,
395 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400396 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
397 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400398 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500399 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400400 }
401 return nullptr;
402 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400403 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400404 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400405 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400406 for (const std::unique_ptr<Statement>& child : block.children()) {
407 result.push_back(stmt(child));
408 }
409 return result;
410 };
John Stiles44e96be2020-08-31 13:16:04 -0400411 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
412 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500413 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400414 }
415 return nullptr;
416 };
John Stiles031a7672020-11-13 16:13:18 -0500417
418 ++fInlinedStatementCounter;
419
Ethan Nicholase6592142020-09-08 10:22:09 -0400420 switch (statement.kind()) {
421 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400422 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500423 return Block::Make(offset, blockStmts(b),
424 SymbolTable::WrapIfBuiltin(b.symbolTable()),
425 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400426 }
427
Ethan Nicholase6592142020-09-08 10:22:09 -0400428 case Statement::Kind::kBreak:
429 case Statement::Kind::kContinue:
430 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400431 return statement.clone();
432
Ethan Nicholase6592142020-09-08 10:22:09 -0400433 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400434 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500435 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400436 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400437 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400438 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500439 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400440 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400441 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400442 const ForStatement& f = statement.as<ForStatement>();
443 // need to ensure initializer is evaluated first so that we've already remapped its
444 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400445 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500446 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
447 expr(f.next()), stmt(f.statement()),
448 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400449 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400450 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400451 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500452 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
453 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400454 }
John Stiles98c1f822020-09-09 14:18:53 -0400455 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400456 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400457 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500458
Ethan Nicholase6592142020-09-08 10:22:09 -0400459 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400460 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500461 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400462 // This function doesn't return a value. We won't inline functions with early
463 // returns, so a return statement is a no-op and can be treated as such.
464 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400465 }
John Stiles77702f12020-12-17 14:38:56 -0500466
John Stilesc5ff4862020-12-22 13:47:05 -0500467 // If a function only contains a single return, and it doesn't reference variables from
468 // inside an Block's scope, we don't need to store the result in a variable at all. Just
469 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500470 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500471 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500472 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500473 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500474 }
475
476 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500477 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500478 auto assignment = ExpressionStatement::Make(
479 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500480 BinaryExpression::Make(
481 *fContext,
482 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500483 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500484 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500485
John Stiles77702f12020-12-17 14:38:56 -0500486 // Functions without early returns aren't wrapped in a for loop and don't need to worry
487 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500488 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400489 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400490 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400491 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500492 StatementArray cases;
493 cases.reserve_back(ss.cases().size());
494 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
495 const SwitchCase& sc = statement->as<SwitchCase>();
496 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
497 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400498 }
John Stilese1d1b082021-02-23 13:44:36 -0500499 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
500 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400501 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400502 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400503 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000504 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500505 const Variable& variable = decl.var();
506
John Stiles35fee4c2020-12-16 18:25:14 +0000507 // We assign unique names to inlined variables--scopes hide most of the problems in this
508 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
509 // names are important.
John Stilesd51c9792021-03-18 11:40:14 -0400510 const String* name = symbolTableForStatement->takeOwnershipOfString(
511 fMangler.uniqueName(variable.name(), symbolTableForStatement));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500512 auto clonedVar = std::make_unique<Variable>(
513 offset,
514 &variable.modifiers(),
John Stilesd51c9792021-03-18 11:40:14 -0400515 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500516 variable.type().clone(symbolTableForStatement),
517 isBuiltinCode,
518 variable.storage());
519 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
John Stilese67bd132021-03-19 18:39:25 -0400520 auto result = VarDeclaration::Make(*fContext,
521 clonedVar.get(),
522 decl.baseType().clone(symbolTableForStatement),
523 decl.arraySize(),
524 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500525 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
John Stilese67bd132021-03-19 18:39:25 -0400526 return result;
John Stiles44e96be2020-08-31 13:16:04 -0400527 }
John Stiles44e96be2020-08-31 13:16:04 -0400528 default:
529 SkASSERT(false);
530 return nullptr;
531 }
532}
533
John Stiles7b920442020-12-17 10:43:41 -0500534Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
535 const Type* type,
536 SymbolTable* symbolTable,
537 Modifiers modifiers,
538 bool isBuiltinCode,
539 std::unique_ptr<Expression>* initialValue) {
540 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
541 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
542 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500543 if (type->isLiteral()) {
544 SkDEBUGFAIL("found a $literal type while inlining");
545 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500546 }
547
John Stilesbff24ab2021-03-17 13:20:10 -0400548 // Out parameters aren't supported.
549 SkASSERT(!(modifiers.fFlags & Modifiers::kOut_Flag));
550
John Stiles7b920442020-12-17 10:43:41 -0500551 // Provide our new variable with a unique name, and add it to our symbol table.
John Stilesd51c9792021-03-18 11:40:14 -0400552 const String* name =
553 symbolTable->takeOwnershipOfString(fMangler.uniqueName(baseName, symbolTable));
John Stiles7b920442020-12-17 10:43:41 -0500554
555 // Create our new variable and add it to the symbol table.
556 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500557 auto var = std::make_unique<Variable>(/*offset=*/-1,
558 fModifiers->addToPool(Modifiers()),
John Stilesd51c9792021-03-18 11:40:14 -0400559 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500560 type,
561 isBuiltinCode,
562 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500563
John Stilesbff24ab2021-03-17 13:20:10 -0400564 // Create our variable declaration.
John Stilese67bd132021-03-19 18:39:25 -0400565 result.fVarDecl = VarDeclaration::Make(*fContext, var.get(), type, /*arraySize=*/0,
566 std::move(*initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500567 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500568 return result;
569}
570
John Stiles6eadf132020-09-08 10:16:10 -0400571Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500572 std::shared_ptr<SymbolTable> symbolTable,
John Stiles30fce9c2021-03-18 09:24:06 -0400573 const ProgramUsage& usage,
Brian Osman3887a012020-09-30 13:22:27 -0400574 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400575 // Inlining is more complicated here than in a typical compiler, because we have to have a
576 // high-level IR and can't just drop statements into the middle of an expression or even use
577 // gotos.
578 //
579 // Since we can't insert statements into an expression, we run the inline function as extra
580 // statements before the statement we're currently processing, relying on a lack of execution
581 // order guarantees. Since we can't use gotos (which are normally used to replace return
582 // statements), we wrap the whole function in a loop and use break statements to jump to the
583 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400584 SkASSERT(fContext);
585 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400586 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400587
John Stiles8e3b6be2020-10-13 11:14:08 -0400588 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400589 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400590 const FunctionDefinition& function = *call->function().definition();
John Stiles28257db2021-03-17 15:18:09 -0400591 const Block& body = function.body()->as<Block>();
John Stiles77702f12020-12-17 14:38:56 -0500592 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400593
John Stiles28257db2021-03-17 15:18:09 -0400594 StatementArray inlineStatements;
595 int expectedStmtCount = 1 + // Inline marker
596 1 + // Result variable
597 arguments.size() + // Function argument temp-vars
598 body.children().size(); // Inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400599
John Stiles28257db2021-03-17 15:18:09 -0400600 inlineStatements.reserve_back(expectedStmtCount);
601 inlineStatements.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400602
John Stilese41b4ee2020-09-28 12:28:16 -0400603 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500604 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400605 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500606 // Create a variable to hold the result in the extra statements. We don't need to do this
607 // for void-return functions, or in cases that are simple enough that we can just replace
608 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400609 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500610 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
611 &function.declaration().returnType(),
612 symbolTable.get(), Modifiers{},
613 caller->isBuiltin(), &noInitialValue);
John Stiles28257db2021-03-17 15:18:09 -0400614 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500615 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500616 }
John Stiles44e96be2020-08-31 13:16:04 -0400617
618 // Create variables in the extra statements to hold the arguments, and assign the arguments to
619 // them.
620 VariableRewriteMap varMap;
John Stilesbff24ab2021-03-17 13:20:10 -0400621 for (int i = 0; i < arguments.count(); ++i) {
John Stiles049f0df2021-03-19 09:39:44 -0400622 // If the parameter isn't written to within the inline function ...
John Stilesbff24ab2021-03-17 13:20:10 -0400623 const Variable* param = function.declaration().parameters()[i];
John Stiles049f0df2021-03-19 09:39:44 -0400624 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
625 if (!paramUsage.fWrite) {
626 // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
627 // or any expression without side effects that is only accessed at most once...
628 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arguments[i])
629 : !arguments[i]->hasSideEffects()) {
John Stilesf201af82020-09-29 16:57:55 -0400630 // ... we don't need to copy it at all! We can just use the existing expression.
631 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400632 continue;
633 }
634 }
John Stiles7b920442020-12-17 10:43:41 -0500635 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
636 symbolTable.get(), param->modifiers(),
637 caller->isBuiltin(), &arguments[i]);
John Stiles28257db2021-03-17 15:18:09 -0400638 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500639 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400640 }
641
John Stiles7b920442020-12-17 10:43:41 -0500642 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles28257db2021-03-17 15:18:09 -0400643 inlineStatements.push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
644 &resultExpr, returnComplexity, *stmt,
645 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400646 }
647
John Stiles28257db2021-03-17 15:18:09 -0400648 SkASSERT(inlineStatements.count() <= expectedStmtCount);
649
John Stilesbf16b6c2021-03-12 19:24:31 -0500650 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
651 // MakeUnscoped. This is because we need to add another child statement to the Block later.
John Stiles28257db2021-03-17 15:18:09 -0400652 InlinedCall inlinedCall;
653 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlineStatements),
John Stilesbf16b6c2021-03-12 19:24:31 -0500654 /*symbols=*/nullptr, /*isScope=*/false);
655
John Stiles0c2d14a2021-03-01 10:08:08 -0500656 if (resultExpr) {
657 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400658 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400659 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400660 // It's a void function, so it doesn't actually result in anything, but we have to return
661 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500662 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500663 } else {
664 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500665 // returned anything on any path! This should have been detected in the function finalizer.
666 // Still, discard our output and generate an error.
667 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
668 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500669 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500670 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500671 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400672 }
673
John Stiles44e96be2020-08-31 13:16:04 -0400674 return inlinedCall;
675}
676
John Stiles2d7973a2020-10-02 15:01:03 -0400677bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400678 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500679 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400680 return false;
681 }
682
John Stiles031a7672020-11-13 16:13:18 -0500683 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
684 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
685 return false;
686 }
687
John Stiles2d7973a2020-10-02 15:01:03 -0400688 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400689 // Can't inline something if we don't actually have its definition.
690 return false;
691 }
John Stiles2d7973a2020-10-02 15:01:03 -0400692
John Stiles0dd1a772021-03-09 22:14:27 -0500693 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
694 // Refuse to inline functions decorated with `noinline`.
695 return false;
696 }
697
John Stilesbff24ab2021-03-17 13:20:10 -0400698 // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
699 for (const Variable* param : functionDef->declaration().parameters()) {
700 if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
701 return false;
702 }
703 }
704
John Stilesdc208472021-03-17 10:58:16 -0400705 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
706 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400707}
708
John Stiles2d7973a2020-10-02 15:01:03 -0400709// A candidate function for inlining, containing everything that `inlineCall` needs.
710struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500711 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400712 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
713 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
714 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
715 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400716};
John Stiles93442622020-09-11 12:11:27 -0400717
John Stiles2d7973a2020-10-02 15:01:03 -0400718struct InlineCandidateList {
719 std::vector<InlineCandidate> fCandidates;
720};
721
722class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400723public:
724 // A list of all the inlining candidates we found during analysis.
725 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400726
John Stiles70957c82020-10-02 16:42:10 -0400727 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
728 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500729 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400730 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
731 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
732 // inliner might replace a statement with a block containing the statement.
733 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
734 // The function that we're currently processing (i.e. inlining into).
735 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400736
Brian Osman0006ad02020-11-18 15:38:39 -0500737 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500738 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500739 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400740 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500741 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400742
Brian Osman0006ad02020-11-18 15:38:39 -0500743 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400744 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400745 }
746
John Stiles70957c82020-10-02 16:42:10 -0400747 fSymbolTableStack.pop_back();
748 fCandidateList = nullptr;
749 }
750
751 void visitProgramElement(ProgramElement* pe) {
752 switch (pe->kind()) {
753 case ProgramElement::Kind::kFunction: {
754 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500755 fEnclosingFunction = &funcDef;
756 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400757 break;
John Stiles93442622020-09-11 12:11:27 -0400758 }
John Stiles70957c82020-10-02 16:42:10 -0400759 default:
760 // The inliner can't operate outside of a function's scope.
761 break;
762 }
763 }
764
765 void visitStatement(std::unique_ptr<Statement>* stmt,
766 bool isViableAsEnclosingStatement = true) {
767 if (!*stmt) {
768 return;
John Stiles93442622020-09-11 12:11:27 -0400769 }
770
John Stiles70957c82020-10-02 16:42:10 -0400771 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
772 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400773
John Stiles70957c82020-10-02 16:42:10 -0400774 if (isViableAsEnclosingStatement) {
775 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400776 }
777
John Stiles70957c82020-10-02 16:42:10 -0400778 switch ((*stmt)->kind()) {
779 case Statement::Kind::kBreak:
780 case Statement::Kind::kContinue:
781 case Statement::Kind::kDiscard:
782 case Statement::Kind::kInlineMarker:
783 case Statement::Kind::kNop:
784 break;
785
786 case Statement::Kind::kBlock: {
787 Block& block = (*stmt)->as<Block>();
788 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500789 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400790 }
791
792 for (std::unique_ptr<Statement>& stmt : block.children()) {
793 this->visitStatement(&stmt);
794 }
795 break;
John Stiles93442622020-09-11 12:11:27 -0400796 }
John Stiles70957c82020-10-02 16:42:10 -0400797 case Statement::Kind::kDo: {
798 DoStatement& doStmt = (*stmt)->as<DoStatement>();
799 // The loop body is a candidate for inlining.
800 this->visitStatement(&doStmt.statement());
801 // The inliner isn't smart enough to inline the test-expression for a do-while
802 // loop at this time. There are two limitations:
803 // - We would need to insert the inlined-body block at the very end of the do-
804 // statement's inner fStatement. We don't support that today, but it's doable.
805 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
806 // would skip over the inlined block that evaluates the test expression. There
807 // isn't a good fix for this--any workaround would be more complex than the cost
808 // of a function call. However, loops that don't use `continue` would still be
809 // viable candidates for inlining.
810 break;
John Stiles93442622020-09-11 12:11:27 -0400811 }
John Stiles70957c82020-10-02 16:42:10 -0400812 case Statement::Kind::kExpression: {
813 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
814 this->visitExpression(&expr.expression());
815 break;
816 }
817 case Statement::Kind::kFor: {
818 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400819 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500820 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400821 }
822
823 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400824 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400825 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400826 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400827
828 // The inliner isn't smart enough to inline the test- or increment-expressions
829 // of a for loop loop at this time. There are a handful of limitations:
830 // - We would need to insert the test-expression block at the very beginning of the
831 // for-loop's inner fStatement, and the increment-expression block at the very
832 // end. We don't support that today, but it's doable.
833 // - The for-loop's built-in test-expression would need to be dropped entirely,
834 // and the loop would be halted via a break statement at the end of the inlined
835 // test-expression. This is again something we don't support today, but it could
836 // be implemented.
837 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
838 // that would skip over the inlined block that evaluates the increment expression.
839 // There isn't a good fix for this--any workaround would be more complex than the
840 // cost of a function call. However, loops that don't use `continue` would still
841 // be viable candidates for increment-expression inlining.
842 break;
843 }
844 case Statement::Kind::kIf: {
845 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400846 this->visitExpression(&ifStmt.test());
847 this->visitStatement(&ifStmt.ifTrue());
848 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400849 break;
850 }
851 case Statement::Kind::kReturn: {
852 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400853 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400854 break;
855 }
856 case Statement::Kind::kSwitch: {
857 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400858 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500859 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400860 }
861
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400862 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500863 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400864 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500865 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400866 }
867 break;
868 }
869 case Statement::Kind::kVarDeclaration: {
870 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
871 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400872 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400873 break;
874 }
John Stiles70957c82020-10-02 16:42:10 -0400875 default:
876 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400877 }
878
John Stiles70957c82020-10-02 16:42:10 -0400879 // Pop our symbol and enclosing-statement stacks.
880 fSymbolTableStack.resize(oldSymbolStackSize);
881 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
882 }
883
884 void visitExpression(std::unique_ptr<Expression>* expr) {
885 if (!*expr) {
886 return;
John Stiles93442622020-09-11 12:11:27 -0400887 }
John Stiles70957c82020-10-02 16:42:10 -0400888
889 switch ((*expr)->kind()) {
890 case Expression::Kind::kBoolLiteral:
891 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500892 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400893 case Expression::Kind::kFieldAccess:
894 case Expression::Kind::kFloatLiteral:
895 case Expression::Kind::kFunctionReference:
896 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400897 case Expression::Kind::kSetting:
898 case Expression::Kind::kTypeReference:
899 case Expression::Kind::kVariableReference:
900 // Nothing to scan here.
901 break;
902
903 case Expression::Kind::kBinary: {
904 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400905 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400906
907 // Logical-and and logical-or binary expressions do not inline the right side,
908 // because that would invalidate short-circuiting. That is, when evaluating
909 // expressions like these:
910 // (false && x()) // always false
911 // (true || y()) // always true
912 // It is illegal for side-effects from x() or y() to occur. The simplest way to
913 // enforce that rule is to avoid inlining the right side entirely. However, it is
914 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500915 Operator op = binaryExpr.getOperator();
916 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
917 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400918 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400919 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400920 }
921 break;
922 }
John Stiles7384b372021-04-01 13:48:15 -0400923 case Expression::Kind::kConstructor:
924 case Expression::Kind::kConstructorArray:
925 case Expression::Kind::kConstructorDiagonalMatrix: {
926 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
927 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
John Stiles70957c82020-10-02 16:42:10 -0400928 this->visitExpression(&arg);
929 }
930 break;
931 }
932 case Expression::Kind::kExternalFunctionCall: {
933 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
934 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
935 this->visitExpression(&arg);
936 }
937 break;
938 }
939 case Expression::Kind::kFunctionCall: {
940 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400941 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -0400942 this->visitExpression(&arg);
943 }
944 this->addInlineCandidate(expr);
945 break;
946 }
John Stiles708faba2021-03-19 09:43:23 -0400947 case Expression::Kind::kIndex: {
John Stiles70957c82020-10-02 16:42:10 -0400948 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400949 this->visitExpression(&indexExpr.base());
950 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -0400951 break;
952 }
953 case Expression::Kind::kPostfix: {
954 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400955 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400956 break;
957 }
958 case Expression::Kind::kPrefix: {
959 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400960 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400961 break;
962 }
963 case Expression::Kind::kSwizzle: {
964 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400965 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -0400966 break;
967 }
968 case Expression::Kind::kTernary: {
969 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
970 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -0400971 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -0400972 // The true- and false-expressions cannot be inlined, because we are only allowed to
973 // evaluate one side.
974 break;
975 }
976 default:
977 SkUNREACHABLE;
978 }
979 }
980
981 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
982 fCandidateList->fCandidates.push_back(
983 InlineCandidate{fSymbolTableStack.back(),
984 find_parent_statement(fEnclosingStmtStack),
985 fEnclosingStmtStack.back(),
986 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -0500987 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -0400988 }
John Stiles2d7973a2020-10-02 15:01:03 -0400989};
John Stiles93442622020-09-11 12:11:27 -0400990
John Stiles9b9415e2020-11-23 14:48:06 -0500991static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
992 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
993}
John Stiles915a38c2020-09-14 09:38:13 -0400994
John Stiles9b9415e2020-11-23 14:48:06 -0500995bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
996 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -0400997 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -0400998 if (wasInserted) {
999 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +00001000 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1001 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001002 }
1003
John Stiles2d7973a2020-10-02 15:01:03 -04001004 return iter->second;
1005}
1006
John Stiles9b9415e2020-11-23 14:48:06 -05001007int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1008 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001009 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001010 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001011 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001012 }
John Stiles2d7973a2020-10-02 15:01:03 -04001013 return iter->second;
1014}
1015
Brian Osman0006ad02020-11-18 15:38:39 -05001016void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001017 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001018 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001019 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1020 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1021 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1022 // `const T&`.
1023 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001024 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001025
John Stiles0ad233f2020-11-25 11:02:05 -05001026 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001027 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001028 if (candidates.empty()) {
1029 return;
1030 }
1031
1032 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001033 InlinabilityCache cache;
1034 candidates.erase(std::remove_if(candidates.begin(),
1035 candidates.end(),
1036 [&](const InlineCandidate& candidate) {
1037 return !this->candidateCanBeInlined(candidate, &cache);
1038 }),
1039 candidates.end());
1040
John Stiles0ad233f2020-11-25 11:02:05 -05001041 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1042 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001043 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001044 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001045 }
John Stiles0ad233f2020-11-25 11:02:05 -05001046
1047 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1048 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1049 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1050 FunctionSizeCache functionSizeCache;
1051 FunctionSizeCache candidateTotalCost;
1052 for (InlineCandidate& candidate : candidates) {
1053 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1054 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1055 }
1056
John Stilesd1204642021-02-17 16:30:02 -05001057 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1058 [&](const InlineCandidate& candidate) {
1059 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1060 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1061 // Functions marked `inline` ignore size limitations.
1062 return false;
1063 }
1064 if (usage->get(fnDecl) == 1) {
1065 // If a function is only used once, it's cost-free to inline.
1066 return false;
1067 }
1068 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1069 // We won't exceed the inline threshold by inlining this.
1070 return false;
1071 }
1072 // Inlining this function will add too many IRNodes.
1073 return true;
1074 }),
1075 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001076}
1077
Brian Osman0006ad02020-11-18 15:38:39 -05001078bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001079 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001080 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001081 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001082 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001083 return false;
1084 }
1085
John Stiles031a7672020-11-13 16:13:18 -05001086 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1087 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1088 return false;
1089 }
1090
John Stiles2d7973a2020-10-02 15:01:03 -04001091 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001092 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001093
John Stiles915a38c2020-09-14 09:38:13 -04001094 // Inline the candidates where we've determined that it's safe to do so.
John Stiles708faba2021-03-19 09:43:23 -04001095 using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1096 std::unique_ptr<Statement>*>;
1097 StatementRemappingTable statementRemappingTable;
1098
John Stiles915a38c2020-09-14 09:38:13 -04001099 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001100 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001101 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001102
John Stiles915a38c2020-09-14 09:38:13 -04001103 // Convert the function call to its inlined equivalent.
John Stiles30fce9c2021-03-18 09:24:06 -04001104 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001105 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001106
John Stiles0c2d14a2021-03-01 10:08:08 -05001107 // Stop if an error was detected during the inlining process.
1108 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1109 break;
John Stiles915a38c2020-09-14 09:38:13 -04001110 }
1111
John Stiles0c2d14a2021-03-01 10:08:08 -05001112 // Ensure that the inlined body has a scope if it needs one.
1113 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1114
1115 // Add references within the inlined body
1116 usage->add(inlinedCall.fInlinedBody.get());
1117
John Stiles708faba2021-03-19 09:43:23 -04001118 // Look up the enclosing statement; remap it if necessary.
1119 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1120 for (;;) {
1121 auto iter = statementRemappingTable.find(enclosingStmt);
1122 if (iter == statementRemappingTable.end()) {
1123 break;
1124 }
1125 enclosingStmt = iter->second;
1126 }
1127
John Stiles0c2d14a2021-03-01 10:08:08 -05001128 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1129 // function, then replace the enclosing statement with that Block.
1130 // Before:
1131 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1132 // fEnclosingStmt = stmt4
1133 // After:
1134 // fInlinedBody = null
1135 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
John Stiles708faba2021-03-19 09:43:23 -04001136 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1137 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
John Stiles0c2d14a2021-03-01 10:08:08 -05001138
John Stiles915a38c2020-09-14 09:38:13 -04001139 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001140 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001141 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1142 madeChanges = true;
1143
John Stiles708faba2021-03-19 09:43:23 -04001144 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1145 // containing many other statements as well. Maintain a fix-up table to account for this.
1146 statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1147
John Stiles031a7672020-11-13 16:13:18 -05001148 // Stop inlining if we've reached our hard cap on new statements.
1149 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1150 break;
1151 }
1152
John Stiles915a38c2020-09-14 09:38:13 -04001153 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1154 // remain valid.
1155 }
1156
1157 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001158}
1159
John Stiles44e96be2020-08-31 13:16:04 -04001160} // namespace SkSL