blob: 7915776a3556ed1e6a41425d4008d689fa96350a [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 Stilese1182782021-03-30 22:09:37 -040020#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles44e96be2020-08-31 13:16:04 -040021#include "src/sksl/ir/SkSLContinueStatement.h"
22#include "src/sksl/ir/SkSLDiscardStatement.h"
23#include "src/sksl/ir/SkSLDoStatement.h"
24#include "src/sksl/ir/SkSLEnum.h"
25#include "src/sksl/ir/SkSLExpressionStatement.h"
26#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050027#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040028#include "src/sksl/ir/SkSLField.h"
29#include "src/sksl/ir/SkSLFieldAccess.h"
30#include "src/sksl/ir/SkSLFloatLiteral.h"
31#include "src/sksl/ir/SkSLForStatement.h"
32#include "src/sksl/ir/SkSLFunctionCall.h"
33#include "src/sksl/ir/SkSLFunctionDeclaration.h"
34#include "src/sksl/ir/SkSLFunctionDefinition.h"
35#include "src/sksl/ir/SkSLFunctionReference.h"
36#include "src/sksl/ir/SkSLIfStatement.h"
37#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040038#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040039#include "src/sksl/ir/SkSLIntLiteral.h"
40#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040041#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040042#include "src/sksl/ir/SkSLPostfixExpression.h"
43#include "src/sksl/ir/SkSLPrefixExpression.h"
44#include "src/sksl/ir/SkSLReturnStatement.h"
45#include "src/sksl/ir/SkSLSetting.h"
46#include "src/sksl/ir/SkSLSwitchCase.h"
47#include "src/sksl/ir/SkSLSwitchStatement.h"
48#include "src/sksl/ir/SkSLSwizzle.h"
49#include "src/sksl/ir/SkSLTernaryExpression.h"
50#include "src/sksl/ir/SkSLUnresolvedFunction.h"
51#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040052#include "src/sksl/ir/SkSLVariable.h"
53#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040054
55namespace SkSL {
56namespace {
57
John Stiles031a7672020-11-13 16:13:18 -050058static constexpr int kInlinedStatementLimit = 2500;
59
John Stiles44e96be2020-08-31 13:16:04 -040060static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
61 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
62 public:
63 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
64 this->visitProgramElement(funcDef);
65 }
66
John Stiles5b408a32021-03-17 09:53:32 -040067 bool visitExpression(const Expression& expr) override {
68 // Do not recurse into expressions.
69 return false;
70 }
71
John Stiles44e96be2020-08-31 13:16:04 -040072 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040073 switch (stmt.kind()) {
74 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040075 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040076 const auto& block = stmt.as<Block>();
77 return block.children().size() &&
78 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040079 }
Ethan Nicholase6592142020-09-08 10:22:09 -040080 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040081 case Statement::Kind::kDo:
82 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040083 // Don't introspect switches or loop structures at all.
84 return false;
85
Ethan Nicholase6592142020-09-08 10:22:09 -040086 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040087 ++fNumReturns;
88 [[fallthrough]];
89
90 default:
John Stiles93442622020-09-11 12:11:27 -040091 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040092 }
93 }
94
95 int fNumReturns = 0;
96 using INHERITED = ProgramVisitor;
97 };
98
99 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
100}
101
John Stiles991b09d2020-09-10 13:33:40 -0400102static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
103 class ContainsRecursiveCall : public ProgramVisitor {
104 public:
105 bool visit(const FunctionDeclaration& funcDecl) {
106 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400107 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
108 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400109 }
110
111 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400112 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400113 return true;
114 }
115 return INHERITED::visitExpression(expr);
116 }
117
118 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400119 if (stmt.is<InlineMarker>() &&
120 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400121 return true;
122 }
123 return INHERITED::visitStatement(stmt);
124 }
125
126 const FunctionDeclaration* fFuncDecl;
127 using INHERITED = ProgramVisitor;
128 };
129
130 return ContainsRecursiveCall{}.visit(funcDecl);
131}
132
John Stiles6d696082020-10-01 10:18:54 -0400133static std::unique_ptr<Statement>* find_parent_statement(
134 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400135 SkASSERT(!stmtStack.empty());
136
137 // Walk the statement stack from back to front, ignoring the last element (which is the
138 // enclosing statement).
139 auto iter = stmtStack.rbegin();
140 ++iter;
141
142 // Anything counts as a parent statement other than a scopeless Block.
143 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400144 std::unique_ptr<Statement>* stmt = *iter;
145 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400146 return stmt;
147 }
148 }
149
150 // There wasn't any parent statement to be found.
151 return nullptr;
152}
153
John Stilese41b4ee2020-09-28 12:28:16 -0400154std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
155 VariableReference::RefKind refKind) {
156 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500157 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400158 return clone;
159}
160
John Stiles77702f12020-12-17 14:38:56 -0500161class CountReturnsWithLimit : public ProgramVisitor {
162public:
163 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
164 this->visitProgramElement(funcDef);
165 }
166
John Stiles5b408a32021-03-17 09:53:32 -0400167 bool visitExpression(const Expression& expr) override {
168 // Do not recurse into expressions.
169 return false;
170 }
171
John Stiles77702f12020-12-17 14:38:56 -0500172 bool visitStatement(const Statement& stmt) override {
173 switch (stmt.kind()) {
174 case Statement::Kind::kReturn: {
175 ++fNumReturns;
176 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
177 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
178 }
John Stilesc5ff4862020-12-22 13:47:05 -0500179 case Statement::Kind::kVarDeclaration: {
180 if (fScopedBlockDepth > 1) {
181 fVariablesInBlocks = true;
182 }
183 return INHERITED::visitStatement(stmt);
184 }
John Stiles77702f12020-12-17 14:38:56 -0500185 case Statement::Kind::kBlock: {
186 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
187 fScopedBlockDepth += depthIncrement;
188 bool result = INHERITED::visitStatement(stmt);
189 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500190 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
191 // If closing this block puts us back at the top level, and we haven't
192 // encountered any return statements yet, any vardecls we may have encountered
193 // up until this point can be ignored. They are out of scope now, and they were
194 // never used in a return statement.
195 fVariablesInBlocks = false;
196 }
John Stiles77702f12020-12-17 14:38:56 -0500197 return result;
198 }
199 default:
200 return INHERITED::visitStatement(stmt);
201 }
202 }
203
204 int fNumReturns = 0;
205 int fDeepestReturn = 0;
206 int fLimit = 0;
207 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500208 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500209 using INHERITED = ProgramVisitor;
210};
211
John Stiles44e96be2020-08-31 13:16:04 -0400212} // namespace
213
John Stiles77702f12020-12-17 14:38:56 -0500214Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
215 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
216 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500217 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
218 return ReturnComplexity::kEarlyReturns;
219 }
John Stilesc5ff4862020-12-22 13:47:05 -0500220 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500221 return ReturnComplexity::kScopedReturns;
222 }
John Stilesc5ff4862020-12-22 13:47:05 -0500223 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
224 return ReturnComplexity::kScopedReturns;
225 }
John Stiles8937cd42021-03-17 19:32:59 +0000226 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500227}
228
John Stilesb61ee902020-09-21 12:26:59 -0400229void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
230 // No changes necessary if this statement isn't actually a block.
231 if (!inlinedBody || !inlinedBody->is<Block>()) {
232 return;
233 }
234
235 // No changes necessary if the parent statement doesn't require a scope.
236 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500237 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400238 return;
239 }
240
241 Block& block = inlinedBody->as<Block>();
242
243 // The inliner will create inlined function bodies as a Block containing multiple statements,
244 // but no scope. Normally, this is fine, but if this block is used as the statement for a
245 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
246 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
247 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
248 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
249 // absorbing the following statement into our loop--so we also add a scope to these.
250 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400251 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400252 // We found an explicit scope; all is well.
253 return;
254 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400255 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400256 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
257 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400258 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400259 return;
260 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400261 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400262 // This block has exactly one thing inside, and it's not another block. No need to scope
263 // it.
264 return;
265 }
266 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400267 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400268 }
269}
270
John Stilesd1204642021-02-17 16:30:02 -0500271void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400272 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500273 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500274 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400275}
276
277std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
278 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500279 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400280 const Expression& expression) {
281 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
282 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500283 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400284 }
285 return nullptr;
286 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400287 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
288 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400289 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400290 for (const std::unique_ptr<Expression>& arg : originalArgs) {
291 args.push_back(expr(arg));
292 }
293 return args;
294 };
295
Ethan Nicholase6592142020-09-08 10:22:09 -0400296 switch (expression.kind()) {
297 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500298 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500299 return BinaryExpression::Make(*fContext,
300 expr(binaryExpr.left()),
301 binaryExpr.getOperator(),
302 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400303 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400304 case Expression::Kind::kBoolLiteral:
305 case Expression::Kind::kIntLiteral:
306 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400307 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400308 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400309 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500310 auto inlinedCtor = Constructor::Convert(
311 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
312 argList(constructor.arguments()));
313 SkASSERT(inlinedCtor);
314 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400315 }
John Stilese1182782021-03-30 22:09:37 -0400316 case Expression::Kind::kConstructorDiagonalMatrix: {
317 const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
318 return ConstructorDiagonalMatrix::Make(*fContext, offset,
319 *ctor.type().clone(symbolTableForExpression),
320 expr(ctor.argument()));
321 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400322 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400323 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400324 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400325 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400326 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500327 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400328 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400329 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400330 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500331 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400332 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400333 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400334 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilescd7ba502021-03-19 10:54:59 -0400335 return FunctionCall::Make(*fContext,
336 offset,
337 funcCall.type().clone(symbolTableForExpression),
338 funcCall.function(),
339 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400340 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400341 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400342 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400343 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400344 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500345 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400346 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400347 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400348 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500349 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400350 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400351 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400352 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500353 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400354 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400355 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400356 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400357 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400358 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500359 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400360 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400361 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400362 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500363 return TernaryExpression::Make(*fContext, expr(t.test()),
364 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400365 }
Brian Osman83ba9302020-09-11 13:33:46 -0400366 case Expression::Kind::kTypeReference:
367 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400368 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400369 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400370 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400371 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400372 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400373 }
374 return v.clone();
375 }
376 default:
377 SkASSERT(false);
378 return nullptr;
379 }
380}
381
382std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
383 VariableRewriteMap* varMap,
384 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500385 std::unique_ptr<Expression>* resultExpr,
386 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400387 const Statement& statement,
388 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400389 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
390 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400391 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500392 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400393 }
394 return nullptr;
395 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400396 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400397 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400398 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400399 for (const std::unique_ptr<Statement>& child : block.children()) {
400 result.push_back(stmt(child));
401 }
402 return result;
403 };
John Stiles44e96be2020-08-31 13:16:04 -0400404 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
405 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500406 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400407 }
408 return nullptr;
409 };
John Stiles031a7672020-11-13 16:13:18 -0500410
411 ++fInlinedStatementCounter;
412
Ethan Nicholase6592142020-09-08 10:22:09 -0400413 switch (statement.kind()) {
414 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400415 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500416 return Block::Make(offset, blockStmts(b),
417 SymbolTable::WrapIfBuiltin(b.symbolTable()),
418 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400419 }
420
Ethan Nicholase6592142020-09-08 10:22:09 -0400421 case Statement::Kind::kBreak:
422 case Statement::Kind::kContinue:
423 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400424 return statement.clone();
425
Ethan Nicholase6592142020-09-08 10:22:09 -0400426 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400427 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500428 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400429 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400430 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400431 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500432 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400433 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400434 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400435 const ForStatement& f = statement.as<ForStatement>();
436 // need to ensure initializer is evaluated first so that we've already remapped its
437 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400438 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500439 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
440 expr(f.next()), stmt(f.statement()),
441 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400442 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400443 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400444 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500445 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
446 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400447 }
John Stiles98c1f822020-09-09 14:18:53 -0400448 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400449 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400450 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500451
Ethan Nicholase6592142020-09-08 10:22:09 -0400452 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400453 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500454 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400455 // This function doesn't return a value. We won't inline functions with early
456 // returns, so a return statement is a no-op and can be treated as such.
457 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400458 }
John Stiles77702f12020-12-17 14:38:56 -0500459
John Stilesc5ff4862020-12-22 13:47:05 -0500460 // If a function only contains a single return, and it doesn't reference variables from
461 // inside an Block's scope, we don't need to store the result in a variable at all. Just
462 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500463 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500464 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500465 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500466 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500467 }
468
469 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500470 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500471 auto assignment = ExpressionStatement::Make(
472 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500473 BinaryExpression::Make(
474 *fContext,
475 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500476 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500477 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500478
John Stiles77702f12020-12-17 14:38:56 -0500479 // Functions without early returns aren't wrapped in a for loop and don't need to worry
480 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500481 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400482 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400483 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400484 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500485 StatementArray cases;
486 cases.reserve_back(ss.cases().size());
487 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
488 const SwitchCase& sc = statement->as<SwitchCase>();
489 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
490 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400491 }
John Stilese1d1b082021-02-23 13:44:36 -0500492 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
493 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400494 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400495 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400496 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000497 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500498 const Variable& variable = decl.var();
499
John Stiles35fee4c2020-12-16 18:25:14 +0000500 // We assign unique names to inlined variables--scopes hide most of the problems in this
501 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
502 // names are important.
John Stilesd51c9792021-03-18 11:40:14 -0400503 const String* name = symbolTableForStatement->takeOwnershipOfString(
504 fMangler.uniqueName(variable.name(), symbolTableForStatement));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500505 auto clonedVar = std::make_unique<Variable>(
506 offset,
507 &variable.modifiers(),
John Stilesd51c9792021-03-18 11:40:14 -0400508 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500509 variable.type().clone(symbolTableForStatement),
510 isBuiltinCode,
511 variable.storage());
512 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
John Stilese67bd132021-03-19 18:39:25 -0400513 auto result = VarDeclaration::Make(*fContext,
514 clonedVar.get(),
515 decl.baseType().clone(symbolTableForStatement),
516 decl.arraySize(),
517 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500518 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
John Stilese67bd132021-03-19 18:39:25 -0400519 return result;
John Stiles44e96be2020-08-31 13:16:04 -0400520 }
John Stiles44e96be2020-08-31 13:16:04 -0400521 default:
522 SkASSERT(false);
523 return nullptr;
524 }
525}
526
John Stiles7b920442020-12-17 10:43:41 -0500527Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
528 const Type* type,
529 SymbolTable* symbolTable,
530 Modifiers modifiers,
531 bool isBuiltinCode,
532 std::unique_ptr<Expression>* initialValue) {
533 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
534 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
535 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500536 if (type->isLiteral()) {
537 SkDEBUGFAIL("found a $literal type while inlining");
538 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500539 }
540
John Stilesbff24ab2021-03-17 13:20:10 -0400541 // Out parameters aren't supported.
542 SkASSERT(!(modifiers.fFlags & Modifiers::kOut_Flag));
543
John Stiles7b920442020-12-17 10:43:41 -0500544 // Provide our new variable with a unique name, and add it to our symbol table.
John Stilesd51c9792021-03-18 11:40:14 -0400545 const String* name =
546 symbolTable->takeOwnershipOfString(fMangler.uniqueName(baseName, symbolTable));
John Stiles7b920442020-12-17 10:43:41 -0500547
548 // Create our new variable and add it to the symbol table.
549 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500550 auto var = std::make_unique<Variable>(/*offset=*/-1,
551 fModifiers->addToPool(Modifiers()),
John Stilesd51c9792021-03-18 11:40:14 -0400552 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500553 type,
554 isBuiltinCode,
555 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500556
John Stilesbff24ab2021-03-17 13:20:10 -0400557 // Create our variable declaration.
John Stilese67bd132021-03-19 18:39:25 -0400558 result.fVarDecl = VarDeclaration::Make(*fContext, var.get(), type, /*arraySize=*/0,
559 std::move(*initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500560 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500561 return result;
562}
563
John Stiles6eadf132020-09-08 10:16:10 -0400564Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500565 std::shared_ptr<SymbolTable> symbolTable,
John Stiles30fce9c2021-03-18 09:24:06 -0400566 const ProgramUsage& usage,
Brian Osman3887a012020-09-30 13:22:27 -0400567 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400568 // Inlining is more complicated here than in a typical compiler, because we have to have a
569 // high-level IR and can't just drop statements into the middle of an expression or even use
570 // gotos.
571 //
572 // Since we can't insert statements into an expression, we run the inline function as extra
573 // statements before the statement we're currently processing, relying on a lack of execution
574 // order guarantees. Since we can't use gotos (which are normally used to replace return
575 // statements), we wrap the whole function in a loop and use break statements to jump to the
576 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400577 SkASSERT(fContext);
578 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400579 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400580
John Stiles8e3b6be2020-10-13 11:14:08 -0400581 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400582 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400583 const FunctionDefinition& function = *call->function().definition();
John Stiles28257db2021-03-17 15:18:09 -0400584 const Block& body = function.body()->as<Block>();
John Stiles77702f12020-12-17 14:38:56 -0500585 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400586
John Stiles28257db2021-03-17 15:18:09 -0400587 StatementArray inlineStatements;
588 int expectedStmtCount = 1 + // Inline marker
589 1 + // Result variable
590 arguments.size() + // Function argument temp-vars
591 body.children().size(); // Inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400592
John Stiles28257db2021-03-17 15:18:09 -0400593 inlineStatements.reserve_back(expectedStmtCount);
594 inlineStatements.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400595
John Stilese41b4ee2020-09-28 12:28:16 -0400596 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500597 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400598 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500599 // Create a variable to hold the result in the extra statements. We don't need to do this
600 // for void-return functions, or in cases that are simple enough that we can just replace
601 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400602 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500603 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
604 &function.declaration().returnType(),
605 symbolTable.get(), Modifiers{},
606 caller->isBuiltin(), &noInitialValue);
John Stiles28257db2021-03-17 15:18:09 -0400607 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500608 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500609 }
John Stiles44e96be2020-08-31 13:16:04 -0400610
611 // Create variables in the extra statements to hold the arguments, and assign the arguments to
612 // them.
613 VariableRewriteMap varMap;
John Stilesbff24ab2021-03-17 13:20:10 -0400614 for (int i = 0; i < arguments.count(); ++i) {
John Stiles049f0df2021-03-19 09:39:44 -0400615 // If the parameter isn't written to within the inline function ...
John Stilesbff24ab2021-03-17 13:20:10 -0400616 const Variable* param = function.declaration().parameters()[i];
John Stiles049f0df2021-03-19 09:39:44 -0400617 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
618 if (!paramUsage.fWrite) {
619 // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
620 // or any expression without side effects that is only accessed at most once...
621 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arguments[i])
622 : !arguments[i]->hasSideEffects()) {
John Stilesf201af82020-09-29 16:57:55 -0400623 // ... we don't need to copy it at all! We can just use the existing expression.
624 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400625 continue;
626 }
627 }
John Stiles7b920442020-12-17 10:43:41 -0500628 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
629 symbolTable.get(), param->modifiers(),
630 caller->isBuiltin(), &arguments[i]);
John Stiles28257db2021-03-17 15:18:09 -0400631 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500632 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400633 }
634
John Stiles7b920442020-12-17 10:43:41 -0500635 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles28257db2021-03-17 15:18:09 -0400636 inlineStatements.push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
637 &resultExpr, returnComplexity, *stmt,
638 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400639 }
640
John Stiles28257db2021-03-17 15:18:09 -0400641 SkASSERT(inlineStatements.count() <= expectedStmtCount);
642
John Stilesbf16b6c2021-03-12 19:24:31 -0500643 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
644 // MakeUnscoped. This is because we need to add another child statement to the Block later.
John Stiles28257db2021-03-17 15:18:09 -0400645 InlinedCall inlinedCall;
646 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlineStatements),
John Stilesbf16b6c2021-03-12 19:24:31 -0500647 /*symbols=*/nullptr, /*isScope=*/false);
648
John Stiles0c2d14a2021-03-01 10:08:08 -0500649 if (resultExpr) {
650 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400651 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400652 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400653 // It's a void function, so it doesn't actually result in anything, but we have to return
654 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500655 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500656 } else {
657 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500658 // returned anything on any path! This should have been detected in the function finalizer.
659 // Still, discard our output and generate an error.
660 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
661 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500662 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500663 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500664 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400665 }
666
John Stiles44e96be2020-08-31 13:16:04 -0400667 return inlinedCall;
668}
669
John Stiles2d7973a2020-10-02 15:01:03 -0400670bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400671 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500672 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400673 return false;
674 }
675
John Stiles031a7672020-11-13 16:13:18 -0500676 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
677 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
678 return false;
679 }
680
John Stiles2d7973a2020-10-02 15:01:03 -0400681 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400682 // Can't inline something if we don't actually have its definition.
683 return false;
684 }
John Stiles2d7973a2020-10-02 15:01:03 -0400685
John Stiles0dd1a772021-03-09 22:14:27 -0500686 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
687 // Refuse to inline functions decorated with `noinline`.
688 return false;
689 }
690
John Stilesbff24ab2021-03-17 13:20:10 -0400691 // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
692 for (const Variable* param : functionDef->declaration().parameters()) {
693 if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
694 return false;
695 }
696 }
697
John Stilesdc208472021-03-17 10:58:16 -0400698 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
699 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400700}
701
John Stiles2d7973a2020-10-02 15:01:03 -0400702// A candidate function for inlining, containing everything that `inlineCall` needs.
703struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500704 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400705 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
706 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
707 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
708 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400709};
John Stiles93442622020-09-11 12:11:27 -0400710
John Stiles2d7973a2020-10-02 15:01:03 -0400711struct InlineCandidateList {
712 std::vector<InlineCandidate> fCandidates;
713};
714
715class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400716public:
717 // A list of all the inlining candidates we found during analysis.
718 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400719
John Stiles70957c82020-10-02 16:42:10 -0400720 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
721 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500722 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400723 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
724 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
725 // inliner might replace a statement with a block containing the statement.
726 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
727 // The function that we're currently processing (i.e. inlining into).
728 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400729
Brian Osman0006ad02020-11-18 15:38:39 -0500730 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500731 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500732 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400733 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500734 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400735
Brian Osman0006ad02020-11-18 15:38:39 -0500736 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400737 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400738 }
739
John Stiles70957c82020-10-02 16:42:10 -0400740 fSymbolTableStack.pop_back();
741 fCandidateList = nullptr;
742 }
743
744 void visitProgramElement(ProgramElement* pe) {
745 switch (pe->kind()) {
746 case ProgramElement::Kind::kFunction: {
747 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500748 fEnclosingFunction = &funcDef;
749 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400750 break;
John Stiles93442622020-09-11 12:11:27 -0400751 }
John Stiles70957c82020-10-02 16:42:10 -0400752 default:
753 // The inliner can't operate outside of a function's scope.
754 break;
755 }
756 }
757
758 void visitStatement(std::unique_ptr<Statement>* stmt,
759 bool isViableAsEnclosingStatement = true) {
760 if (!*stmt) {
761 return;
John Stiles93442622020-09-11 12:11:27 -0400762 }
763
John Stiles70957c82020-10-02 16:42:10 -0400764 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
765 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400766
John Stiles70957c82020-10-02 16:42:10 -0400767 if (isViableAsEnclosingStatement) {
768 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400769 }
770
John Stiles70957c82020-10-02 16:42:10 -0400771 switch ((*stmt)->kind()) {
772 case Statement::Kind::kBreak:
773 case Statement::Kind::kContinue:
774 case Statement::Kind::kDiscard:
775 case Statement::Kind::kInlineMarker:
776 case Statement::Kind::kNop:
777 break;
778
779 case Statement::Kind::kBlock: {
780 Block& block = (*stmt)->as<Block>();
781 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500782 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400783 }
784
785 for (std::unique_ptr<Statement>& stmt : block.children()) {
786 this->visitStatement(&stmt);
787 }
788 break;
John Stiles93442622020-09-11 12:11:27 -0400789 }
John Stiles70957c82020-10-02 16:42:10 -0400790 case Statement::Kind::kDo: {
791 DoStatement& doStmt = (*stmt)->as<DoStatement>();
792 // The loop body is a candidate for inlining.
793 this->visitStatement(&doStmt.statement());
794 // The inliner isn't smart enough to inline the test-expression for a do-while
795 // loop at this time. There are two limitations:
796 // - We would need to insert the inlined-body block at the very end of the do-
797 // statement's inner fStatement. We don't support that today, but it's doable.
798 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
799 // would skip over the inlined block that evaluates the test expression. There
800 // isn't a good fix for this--any workaround would be more complex than the cost
801 // of a function call. However, loops that don't use `continue` would still be
802 // viable candidates for inlining.
803 break;
John Stiles93442622020-09-11 12:11:27 -0400804 }
John Stiles70957c82020-10-02 16:42:10 -0400805 case Statement::Kind::kExpression: {
806 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
807 this->visitExpression(&expr.expression());
808 break;
809 }
810 case Statement::Kind::kFor: {
811 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400812 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500813 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400814 }
815
816 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400817 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400818 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400819 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400820
821 // The inliner isn't smart enough to inline the test- or increment-expressions
822 // of a for loop loop at this time. There are a handful of limitations:
823 // - We would need to insert the test-expression block at the very beginning of the
824 // for-loop's inner fStatement, and the increment-expression block at the very
825 // end. We don't support that today, but it's doable.
826 // - The for-loop's built-in test-expression would need to be dropped entirely,
827 // and the loop would be halted via a break statement at the end of the inlined
828 // test-expression. This is again something we don't support today, but it could
829 // be implemented.
830 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
831 // that would skip over the inlined block that evaluates the increment expression.
832 // There isn't a good fix for this--any workaround would be more complex than the
833 // cost of a function call. However, loops that don't use `continue` would still
834 // be viable candidates for increment-expression inlining.
835 break;
836 }
837 case Statement::Kind::kIf: {
838 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400839 this->visitExpression(&ifStmt.test());
840 this->visitStatement(&ifStmt.ifTrue());
841 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400842 break;
843 }
844 case Statement::Kind::kReturn: {
845 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400846 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400847 break;
848 }
849 case Statement::Kind::kSwitch: {
850 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400851 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500852 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400853 }
854
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400855 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500856 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400857 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500858 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400859 }
860 break;
861 }
862 case Statement::Kind::kVarDeclaration: {
863 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
864 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400865 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400866 break;
867 }
John Stiles70957c82020-10-02 16:42:10 -0400868 default:
869 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400870 }
871
John Stiles70957c82020-10-02 16:42:10 -0400872 // Pop our symbol and enclosing-statement stacks.
873 fSymbolTableStack.resize(oldSymbolStackSize);
874 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
875 }
876
877 void visitExpression(std::unique_ptr<Expression>* expr) {
878 if (!*expr) {
879 return;
John Stiles93442622020-09-11 12:11:27 -0400880 }
John Stiles70957c82020-10-02 16:42:10 -0400881
882 switch ((*expr)->kind()) {
883 case Expression::Kind::kBoolLiteral:
884 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500885 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400886 case Expression::Kind::kFieldAccess:
887 case Expression::Kind::kFloatLiteral:
888 case Expression::Kind::kFunctionReference:
889 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400890 case Expression::Kind::kSetting:
891 case Expression::Kind::kTypeReference:
892 case Expression::Kind::kVariableReference:
893 // Nothing to scan here.
894 break;
895
896 case Expression::Kind::kBinary: {
897 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400898 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400899
900 // Logical-and and logical-or binary expressions do not inline the right side,
901 // because that would invalidate short-circuiting. That is, when evaluating
902 // expressions like these:
903 // (false && x()) // always false
904 // (true || y()) // always true
905 // It is illegal for side-effects from x() or y() to occur. The simplest way to
906 // enforce that rule is to avoid inlining the right side entirely. However, it is
907 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500908 Operator op = binaryExpr.getOperator();
909 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
910 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400911 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400912 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400913 }
914 break;
915 }
916 case Expression::Kind::kConstructor: {
917 Constructor& constructorExpr = (*expr)->as<Constructor>();
918 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
919 this->visitExpression(&arg);
920 }
921 break;
922 }
John Stilese1182782021-03-30 22:09:37 -0400923 case Expression::Kind::kConstructorDiagonalMatrix: {
924 ConstructorDiagonalMatrix& ctorExpr = (*expr)->as<ConstructorDiagonalMatrix>();
925 this->visitExpression(&ctorExpr.argument());
926 break;
927 }
John Stiles70957c82020-10-02 16:42:10 -0400928 case Expression::Kind::kExternalFunctionCall: {
929 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
930 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
931 this->visitExpression(&arg);
932 }
933 break;
934 }
935 case Expression::Kind::kFunctionCall: {
936 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400937 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -0400938 this->visitExpression(&arg);
939 }
940 this->addInlineCandidate(expr);
941 break;
942 }
John Stiles708faba2021-03-19 09:43:23 -0400943 case Expression::Kind::kIndex: {
John Stiles70957c82020-10-02 16:42:10 -0400944 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400945 this->visitExpression(&indexExpr.base());
946 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -0400947 break;
948 }
949 case Expression::Kind::kPostfix: {
950 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400951 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400952 break;
953 }
954 case Expression::Kind::kPrefix: {
955 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400956 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400957 break;
958 }
959 case Expression::Kind::kSwizzle: {
960 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400961 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -0400962 break;
963 }
964 case Expression::Kind::kTernary: {
965 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
966 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -0400967 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -0400968 // The true- and false-expressions cannot be inlined, because we are only allowed to
969 // evaluate one side.
970 break;
971 }
972 default:
973 SkUNREACHABLE;
974 }
975 }
976
977 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
978 fCandidateList->fCandidates.push_back(
979 InlineCandidate{fSymbolTableStack.back(),
980 find_parent_statement(fEnclosingStmtStack),
981 fEnclosingStmtStack.back(),
982 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -0500983 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -0400984 }
John Stiles2d7973a2020-10-02 15:01:03 -0400985};
John Stiles93442622020-09-11 12:11:27 -0400986
John Stiles9b9415e2020-11-23 14:48:06 -0500987static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
988 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
989}
John Stiles915a38c2020-09-14 09:38:13 -0400990
John Stiles9b9415e2020-11-23 14:48:06 -0500991bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
992 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -0400993 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -0400994 if (wasInserted) {
995 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +0000996 iter->second = this->isSafeToInline(funcDecl.definition()) &&
997 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -0400998 }
999
John Stiles2d7973a2020-10-02 15:01:03 -04001000 return iter->second;
1001}
1002
John Stiles9b9415e2020-11-23 14:48:06 -05001003int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1004 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001005 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001006 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001007 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001008 }
John Stiles2d7973a2020-10-02 15:01:03 -04001009 return iter->second;
1010}
1011
Brian Osman0006ad02020-11-18 15:38:39 -05001012void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001013 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001014 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001015 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1016 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1017 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1018 // `const T&`.
1019 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001020 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001021
John Stiles0ad233f2020-11-25 11:02:05 -05001022 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001023 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001024 if (candidates.empty()) {
1025 return;
1026 }
1027
1028 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001029 InlinabilityCache cache;
1030 candidates.erase(std::remove_if(candidates.begin(),
1031 candidates.end(),
1032 [&](const InlineCandidate& candidate) {
1033 return !this->candidateCanBeInlined(candidate, &cache);
1034 }),
1035 candidates.end());
1036
John Stiles0ad233f2020-11-25 11:02:05 -05001037 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1038 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001039 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001040 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001041 }
John Stiles0ad233f2020-11-25 11:02:05 -05001042
1043 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1044 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1045 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1046 FunctionSizeCache functionSizeCache;
1047 FunctionSizeCache candidateTotalCost;
1048 for (InlineCandidate& candidate : candidates) {
1049 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1050 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1051 }
1052
John Stilesd1204642021-02-17 16:30:02 -05001053 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1054 [&](const InlineCandidate& candidate) {
1055 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1056 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1057 // Functions marked `inline` ignore size limitations.
1058 return false;
1059 }
1060 if (usage->get(fnDecl) == 1) {
1061 // If a function is only used once, it's cost-free to inline.
1062 return false;
1063 }
1064 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1065 // We won't exceed the inline threshold by inlining this.
1066 return false;
1067 }
1068 // Inlining this function will add too many IRNodes.
1069 return true;
1070 }),
1071 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001072}
1073
Brian Osman0006ad02020-11-18 15:38:39 -05001074bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001075 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001076 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001077 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001078 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001079 return false;
1080 }
1081
John Stiles031a7672020-11-13 16:13:18 -05001082 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1083 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1084 return false;
1085 }
1086
John Stiles2d7973a2020-10-02 15:01:03 -04001087 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001088 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001089
John Stiles915a38c2020-09-14 09:38:13 -04001090 // Inline the candidates where we've determined that it's safe to do so.
John Stiles708faba2021-03-19 09:43:23 -04001091 using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1092 std::unique_ptr<Statement>*>;
1093 StatementRemappingTable statementRemappingTable;
1094
John Stiles915a38c2020-09-14 09:38:13 -04001095 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001096 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001097 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001098
John Stiles915a38c2020-09-14 09:38:13 -04001099 // Convert the function call to its inlined equivalent.
John Stiles30fce9c2021-03-18 09:24:06 -04001100 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001101 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001102
John Stiles0c2d14a2021-03-01 10:08:08 -05001103 // Stop if an error was detected during the inlining process.
1104 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1105 break;
John Stiles915a38c2020-09-14 09:38:13 -04001106 }
1107
John Stiles0c2d14a2021-03-01 10:08:08 -05001108 // Ensure that the inlined body has a scope if it needs one.
1109 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1110
1111 // Add references within the inlined body
1112 usage->add(inlinedCall.fInlinedBody.get());
1113
John Stiles708faba2021-03-19 09:43:23 -04001114 // Look up the enclosing statement; remap it if necessary.
1115 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1116 for (;;) {
1117 auto iter = statementRemappingTable.find(enclosingStmt);
1118 if (iter == statementRemappingTable.end()) {
1119 break;
1120 }
1121 enclosingStmt = iter->second;
1122 }
1123
John Stiles0c2d14a2021-03-01 10:08:08 -05001124 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1125 // function, then replace the enclosing statement with that Block.
1126 // Before:
1127 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1128 // fEnclosingStmt = stmt4
1129 // After:
1130 // fInlinedBody = null
1131 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
John Stiles708faba2021-03-19 09:43:23 -04001132 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1133 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
John Stiles0c2d14a2021-03-01 10:08:08 -05001134
John Stiles915a38c2020-09-14 09:38:13 -04001135 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001136 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001137 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1138 madeChanges = true;
1139
John Stiles708faba2021-03-19 09:43:23 -04001140 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1141 // containing many other statements as well. Maintain a fix-up table to account for this.
1142 statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1143
John Stiles031a7672020-11-13 16:13:18 -05001144 // Stop inlining if we've reached our hard cap on new statements.
1145 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1146 break;
1147 }
1148
John Stiles915a38c2020-09-14 09:38:13 -04001149 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1150 // remain valid.
1151 }
1152
1153 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001154}
1155
John Stiles44e96be2020-08-31 13:16:04 -04001156} // namespace SkSL