blob: fbcf6cf798671023e0657990d5fc2ebf42fd097d [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 Stilesfd7252f2021-04-04 22:24:40 -040022#include "src/sksl/ir/SkSLConstructorScalarCast.h"
John Stiles2938eea2021-04-01 18:58:25 -040023#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stiles44e96be2020-08-31 13:16:04 -040024#include "src/sksl/ir/SkSLContinueStatement.h"
25#include "src/sksl/ir/SkSLDiscardStatement.h"
26#include "src/sksl/ir/SkSLDoStatement.h"
27#include "src/sksl/ir/SkSLEnum.h"
28#include "src/sksl/ir/SkSLExpressionStatement.h"
29#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050030#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040031#include "src/sksl/ir/SkSLField.h"
32#include "src/sksl/ir/SkSLFieldAccess.h"
33#include "src/sksl/ir/SkSLFloatLiteral.h"
34#include "src/sksl/ir/SkSLForStatement.h"
35#include "src/sksl/ir/SkSLFunctionCall.h"
36#include "src/sksl/ir/SkSLFunctionDeclaration.h"
37#include "src/sksl/ir/SkSLFunctionDefinition.h"
38#include "src/sksl/ir/SkSLFunctionReference.h"
39#include "src/sksl/ir/SkSLIfStatement.h"
40#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040041#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040042#include "src/sksl/ir/SkSLIntLiteral.h"
43#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040044#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040045#include "src/sksl/ir/SkSLPostfixExpression.h"
46#include "src/sksl/ir/SkSLPrefixExpression.h"
47#include "src/sksl/ir/SkSLReturnStatement.h"
48#include "src/sksl/ir/SkSLSetting.h"
49#include "src/sksl/ir/SkSLSwitchCase.h"
50#include "src/sksl/ir/SkSLSwitchStatement.h"
51#include "src/sksl/ir/SkSLSwizzle.h"
52#include "src/sksl/ir/SkSLTernaryExpression.h"
53#include "src/sksl/ir/SkSLUnresolvedFunction.h"
54#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040055#include "src/sksl/ir/SkSLVariable.h"
56#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040057
58namespace SkSL {
59namespace {
60
John Stiles031a7672020-11-13 16:13:18 -050061static constexpr int kInlinedStatementLimit = 2500;
62
John Stiles44e96be2020-08-31 13:16:04 -040063static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
64 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
65 public:
66 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
67 this->visitProgramElement(funcDef);
68 }
69
John Stiles5b408a32021-03-17 09:53:32 -040070 bool visitExpression(const Expression& expr) override {
71 // Do not recurse into expressions.
72 return false;
73 }
74
John Stiles44e96be2020-08-31 13:16:04 -040075 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040076 switch (stmt.kind()) {
77 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040078 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040079 const auto& block = stmt.as<Block>();
80 return block.children().size() &&
81 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040082 }
Ethan Nicholase6592142020-09-08 10:22:09 -040083 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040084 case Statement::Kind::kDo:
85 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040086 // Don't introspect switches or loop structures at all.
87 return false;
88
Ethan Nicholase6592142020-09-08 10:22:09 -040089 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040090 ++fNumReturns;
91 [[fallthrough]];
92
93 default:
John Stiles93442622020-09-11 12:11:27 -040094 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040095 }
96 }
97
98 int fNumReturns = 0;
99 using INHERITED = ProgramVisitor;
100 };
101
102 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
103}
104
John Stiles991b09d2020-09-10 13:33:40 -0400105static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
106 class ContainsRecursiveCall : public ProgramVisitor {
107 public:
108 bool visit(const FunctionDeclaration& funcDecl) {
109 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400110 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
111 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400112 }
113
114 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400115 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400116 return true;
117 }
118 return INHERITED::visitExpression(expr);
119 }
120
121 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400122 if (stmt.is<InlineMarker>() &&
123 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400124 return true;
125 }
126 return INHERITED::visitStatement(stmt);
127 }
128
129 const FunctionDeclaration* fFuncDecl;
130 using INHERITED = ProgramVisitor;
131 };
132
133 return ContainsRecursiveCall{}.visit(funcDecl);
134}
135
John Stiles6d696082020-10-01 10:18:54 -0400136static std::unique_ptr<Statement>* find_parent_statement(
137 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400138 SkASSERT(!stmtStack.empty());
139
140 // Walk the statement stack from back to front, ignoring the last element (which is the
141 // enclosing statement).
142 auto iter = stmtStack.rbegin();
143 ++iter;
144
145 // Anything counts as a parent statement other than a scopeless Block.
146 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400147 std::unique_ptr<Statement>* stmt = *iter;
148 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400149 return stmt;
150 }
151 }
152
153 // There wasn't any parent statement to be found.
154 return nullptr;
155}
156
John Stilese41b4ee2020-09-28 12:28:16 -0400157std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
158 VariableReference::RefKind refKind) {
159 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500160 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400161 return clone;
162}
163
John Stiles77702f12020-12-17 14:38:56 -0500164class CountReturnsWithLimit : public ProgramVisitor {
165public:
166 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
167 this->visitProgramElement(funcDef);
168 }
169
John Stiles5b408a32021-03-17 09:53:32 -0400170 bool visitExpression(const Expression& expr) override {
171 // Do not recurse into expressions.
172 return false;
173 }
174
John Stiles77702f12020-12-17 14:38:56 -0500175 bool visitStatement(const Statement& stmt) override {
176 switch (stmt.kind()) {
177 case Statement::Kind::kReturn: {
178 ++fNumReturns;
179 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
180 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
181 }
John Stilesc5ff4862020-12-22 13:47:05 -0500182 case Statement::Kind::kVarDeclaration: {
183 if (fScopedBlockDepth > 1) {
184 fVariablesInBlocks = true;
185 }
186 return INHERITED::visitStatement(stmt);
187 }
John Stiles77702f12020-12-17 14:38:56 -0500188 case Statement::Kind::kBlock: {
189 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
190 fScopedBlockDepth += depthIncrement;
191 bool result = INHERITED::visitStatement(stmt);
192 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500193 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
194 // If closing this block puts us back at the top level, and we haven't
195 // encountered any return statements yet, any vardecls we may have encountered
196 // up until this point can be ignored. They are out of scope now, and they were
197 // never used in a return statement.
198 fVariablesInBlocks = false;
199 }
John Stiles77702f12020-12-17 14:38:56 -0500200 return result;
201 }
202 default:
203 return INHERITED::visitStatement(stmt);
204 }
205 }
206
207 int fNumReturns = 0;
208 int fDeepestReturn = 0;
209 int fLimit = 0;
210 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500211 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500212 using INHERITED = ProgramVisitor;
213};
214
John Stiles44e96be2020-08-31 13:16:04 -0400215} // namespace
216
John Stiles77702f12020-12-17 14:38:56 -0500217Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
218 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
219 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500220 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
221 return ReturnComplexity::kEarlyReturns;
222 }
John Stilesc5ff4862020-12-22 13:47:05 -0500223 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500224 return ReturnComplexity::kScopedReturns;
225 }
John Stilesc5ff4862020-12-22 13:47:05 -0500226 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
227 return ReturnComplexity::kScopedReturns;
228 }
John Stiles8937cd42021-03-17 19:32:59 +0000229 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500230}
231
John Stilesb61ee902020-09-21 12:26:59 -0400232void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
233 // No changes necessary if this statement isn't actually a block.
234 if (!inlinedBody || !inlinedBody->is<Block>()) {
235 return;
236 }
237
238 // No changes necessary if the parent statement doesn't require a scope.
239 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500240 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400241 return;
242 }
243
244 Block& block = inlinedBody->as<Block>();
245
246 // The inliner will create inlined function bodies as a Block containing multiple statements,
247 // but no scope. Normally, this is fine, but if this block is used as the statement for a
248 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
249 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
250 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
251 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
252 // absorbing the following statement into our loop--so we also add a scope to these.
253 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400254 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400255 // We found an explicit scope; all is well.
256 return;
257 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400258 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400259 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
260 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400261 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400262 return;
263 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400264 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400265 // This block has exactly one thing inside, and it's not another block. No need to scope
266 // it.
267 return;
268 }
269 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400270 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400271 }
272}
273
John Stilesd1204642021-02-17 16:30:02 -0500274void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400275 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500276 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500277 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400278}
279
280std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
281 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500282 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400283 const Expression& expression) {
284 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
285 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500286 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400287 }
288 return nullptr;
289 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400290 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
291 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400292 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400293 for (const std::unique_ptr<Expression>& arg : originalArgs) {
294 args.push_back(expr(arg));
295 }
296 return args;
297 };
298
Ethan Nicholase6592142020-09-08 10:22:09 -0400299 switch (expression.kind()) {
300 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500301 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500302 return BinaryExpression::Make(*fContext,
303 expr(binaryExpr.left()),
304 binaryExpr.getOperator(),
305 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400306 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400307 case Expression::Kind::kBoolLiteral:
308 case Expression::Kind::kIntLiteral:
309 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400310 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400311 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400312 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500313 auto inlinedCtor = Constructor::Convert(
314 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
315 argList(constructor.arguments()));
316 SkASSERT(inlinedCtor);
317 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400318 }
John Stiles7384b372021-04-01 13:48:15 -0400319 case Expression::Kind::kConstructorArray: {
320 const ConstructorArray& ctor = expression.as<ConstructorArray>();
321 return ConstructorArray::Make(*fContext, offset,
322 *ctor.type().clone(symbolTableForExpression),
323 argList(ctor.arguments()));
324 }
John Stilese1182782021-03-30 22:09:37 -0400325 case Expression::Kind::kConstructorDiagonalMatrix: {
326 const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
327 return ConstructorDiagonalMatrix::Make(*fContext, offset,
328 *ctor.type().clone(symbolTableForExpression),
329 expr(ctor.argument()));
330 }
John Stilesfd7252f2021-04-04 22:24:40 -0400331 case Expression::Kind::kConstructorScalarCast: {
332 const ConstructorScalarCast& ctor = expression.as<ConstructorScalarCast>();
333 return ConstructorScalarCast::Make(*fContext, offset,
334 *ctor.type().clone(symbolTableForExpression),
335 expr(ctor.argument()));
336 }
John Stiles2938eea2021-04-01 18:58:25 -0400337 case Expression::Kind::kConstructorSplat: {
338 const ConstructorSplat& ctor = expression.as<ConstructorSplat>();
339 return ConstructorSplat::Make(*fContext, offset,
340 *ctor.type().clone(symbolTableForExpression),
341 expr(ctor.argument()));
342 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400343 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400344 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400345 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400346 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400347 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500348 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400349 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400350 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400351 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500352 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400353 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400354 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400355 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilescd7ba502021-03-19 10:54:59 -0400356 return FunctionCall::Make(*fContext,
357 offset,
358 funcCall.type().clone(symbolTableForExpression),
359 funcCall.function(),
360 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400361 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400362 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400363 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400364 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400365 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500366 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400367 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400368 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400369 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500370 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400371 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400372 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400373 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500374 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400375 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400376 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400377 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400378 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400379 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500380 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400381 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400382 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400383 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500384 return TernaryExpression::Make(*fContext, expr(t.test()),
385 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400386 }
Brian Osman83ba9302020-09-11 13:33:46 -0400387 case Expression::Kind::kTypeReference:
388 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400389 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400390 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400391 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400392 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400393 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400394 }
395 return v.clone();
396 }
397 default:
398 SkASSERT(false);
399 return nullptr;
400 }
401}
402
403std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
404 VariableRewriteMap* varMap,
405 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500406 std::unique_ptr<Expression>* resultExpr,
407 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400408 const Statement& statement,
409 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400410 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
411 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400412 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500413 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400414 }
415 return nullptr;
416 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400417 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400418 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400419 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400420 for (const std::unique_ptr<Statement>& child : block.children()) {
421 result.push_back(stmt(child));
422 }
423 return result;
424 };
John Stiles44e96be2020-08-31 13:16:04 -0400425 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
426 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500427 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400428 }
429 return nullptr;
430 };
John Stiles031a7672020-11-13 16:13:18 -0500431
432 ++fInlinedStatementCounter;
433
Ethan Nicholase6592142020-09-08 10:22:09 -0400434 switch (statement.kind()) {
435 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400436 const Block& b = statement.as<Block>();
John Stilesbf16b6c2021-03-12 19:24:31 -0500437 return Block::Make(offset, blockStmts(b),
438 SymbolTable::WrapIfBuiltin(b.symbolTable()),
439 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400440 }
441
Ethan Nicholase6592142020-09-08 10:22:09 -0400442 case Statement::Kind::kBreak:
443 case Statement::Kind::kContinue:
444 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400445 return statement.clone();
446
Ethan Nicholase6592142020-09-08 10:22:09 -0400447 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400448 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500449 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400450 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400451 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400452 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500453 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400454 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400455 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400456 const ForStatement& f = statement.as<ForStatement>();
457 // need to ensure initializer is evaluated first so that we've already remapped its
458 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400459 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500460 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
461 expr(f.next()), stmt(f.statement()),
462 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400463 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400464 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400465 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500466 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
467 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400468 }
John Stiles98c1f822020-09-09 14:18:53 -0400469 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400470 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400471 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500472
Ethan Nicholase6592142020-09-08 10:22:09 -0400473 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400474 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500475 if (!r.expression()) {
John Stilesdc208472021-03-17 10:58:16 -0400476 // This function doesn't return a value. We won't inline functions with early
477 // returns, so a return statement is a no-op and can be treated as such.
478 return Nop::Make();
John Stiles44e96be2020-08-31 13:16:04 -0400479 }
John Stiles77702f12020-12-17 14:38:56 -0500480
John Stilesc5ff4862020-12-22 13:47:05 -0500481 // If a function only contains a single return, and it doesn't reference variables from
482 // inside an Block's scope, we don't need to store the result in a variable at all. Just
483 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500484 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500485 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500486 *resultExpr = expr(r.expression());
John Stilesa0c04d62021-03-11 23:07:24 -0500487 return Nop::Make();
John Stiles77702f12020-12-17 14:38:56 -0500488 }
489
490 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500491 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500492 auto assignment = ExpressionStatement::Make(
493 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500494 BinaryExpression::Make(
495 *fContext,
496 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500497 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500498 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500499
John Stiles77702f12020-12-17 14:38:56 -0500500 // Functions without early returns aren't wrapped in a for loop and don't need to worry
501 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500502 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400503 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400504 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400505 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500506 StatementArray cases;
507 cases.reserve_back(ss.cases().size());
508 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
509 const SwitchCase& sc = statement->as<SwitchCase>();
510 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
511 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400512 }
John Stilese1d1b082021-02-23 13:44:36 -0500513 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
514 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400515 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400516 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400517 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000518 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500519 const Variable& variable = decl.var();
520
John Stiles35fee4c2020-12-16 18:25:14 +0000521 // We assign unique names to inlined variables--scopes hide most of the problems in this
522 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
523 // names are important.
John Stilesd51c9792021-03-18 11:40:14 -0400524 const String* name = symbolTableForStatement->takeOwnershipOfString(
525 fMangler.uniqueName(variable.name(), symbolTableForStatement));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500526 auto clonedVar = std::make_unique<Variable>(
527 offset,
528 &variable.modifiers(),
John Stilesd51c9792021-03-18 11:40:14 -0400529 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500530 variable.type().clone(symbolTableForStatement),
531 isBuiltinCode,
532 variable.storage());
533 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
John Stilese67bd132021-03-19 18:39:25 -0400534 auto result = VarDeclaration::Make(*fContext,
535 clonedVar.get(),
536 decl.baseType().clone(symbolTableForStatement),
537 decl.arraySize(),
538 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500539 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
John Stilese67bd132021-03-19 18:39:25 -0400540 return result;
John Stiles44e96be2020-08-31 13:16:04 -0400541 }
John Stiles44e96be2020-08-31 13:16:04 -0400542 default:
543 SkASSERT(false);
544 return nullptr;
545 }
546}
547
John Stiles7b920442020-12-17 10:43:41 -0500548Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
549 const Type* type,
550 SymbolTable* symbolTable,
551 Modifiers modifiers,
552 bool isBuiltinCode,
553 std::unique_ptr<Expression>* initialValue) {
554 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
555 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
556 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500557 if (type->isLiteral()) {
558 SkDEBUGFAIL("found a $literal type while inlining");
559 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500560 }
561
John Stilesbff24ab2021-03-17 13:20:10 -0400562 // Out parameters aren't supported.
563 SkASSERT(!(modifiers.fFlags & Modifiers::kOut_Flag));
564
John Stiles7b920442020-12-17 10:43:41 -0500565 // Provide our new variable with a unique name, and add it to our symbol table.
John Stilesd51c9792021-03-18 11:40:14 -0400566 const String* name =
567 symbolTable->takeOwnershipOfString(fMangler.uniqueName(baseName, symbolTable));
John Stiles7b920442020-12-17 10:43:41 -0500568
569 // Create our new variable and add it to the symbol table.
570 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500571 auto var = std::make_unique<Variable>(/*offset=*/-1,
572 fModifiers->addToPool(Modifiers()),
John Stilesd51c9792021-03-18 11:40:14 -0400573 name->c_str(),
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500574 type,
575 isBuiltinCode,
576 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500577
John Stilesbff24ab2021-03-17 13:20:10 -0400578 // Create our variable declaration.
John Stilese67bd132021-03-19 18:39:25 -0400579 result.fVarDecl = VarDeclaration::Make(*fContext, var.get(), type, /*arraySize=*/0,
580 std::move(*initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500581 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500582 return result;
583}
584
John Stiles6eadf132020-09-08 10:16:10 -0400585Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500586 std::shared_ptr<SymbolTable> symbolTable,
John Stiles30fce9c2021-03-18 09:24:06 -0400587 const ProgramUsage& usage,
Brian Osman3887a012020-09-30 13:22:27 -0400588 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400589 // Inlining is more complicated here than in a typical compiler, because we have to have a
590 // high-level IR and can't just drop statements into the middle of an expression or even use
591 // gotos.
592 //
593 // Since we can't insert statements into an expression, we run the inline function as extra
594 // statements before the statement we're currently processing, relying on a lack of execution
595 // order guarantees. Since we can't use gotos (which are normally used to replace return
596 // statements), we wrap the whole function in a loop and use break statements to jump to the
597 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400598 SkASSERT(fContext);
599 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400600 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400601
John Stiles8e3b6be2020-10-13 11:14:08 -0400602 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400603 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400604 const FunctionDefinition& function = *call->function().definition();
John Stiles28257db2021-03-17 15:18:09 -0400605 const Block& body = function.body()->as<Block>();
John Stiles77702f12020-12-17 14:38:56 -0500606 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
John Stiles6eadf132020-09-08 10:16:10 -0400607
John Stiles28257db2021-03-17 15:18:09 -0400608 StatementArray inlineStatements;
609 int expectedStmtCount = 1 + // Inline marker
610 1 + // Result variable
611 arguments.size() + // Function argument temp-vars
612 body.children().size(); // Inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400613
John Stiles28257db2021-03-17 15:18:09 -0400614 inlineStatements.reserve_back(expectedStmtCount);
615 inlineStatements.push_back(InlineMarker::Make(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400616
John Stilese41b4ee2020-09-28 12:28:16 -0400617 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500618 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
John Stiles2558c462021-03-16 17:49:20 -0400619 !function.declaration().returnType().isVoid()) {
John Stiles511c5002021-02-25 11:17:02 -0500620 // Create a variable to hold the result in the extra statements. We don't need to do this
621 // for void-return functions, or in cases that are simple enough that we can just replace
622 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400623 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500624 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
625 &function.declaration().returnType(),
626 symbolTable.get(), Modifiers{},
627 caller->isBuiltin(), &noInitialValue);
John Stiles28257db2021-03-17 15:18:09 -0400628 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500629 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500630 }
John Stiles44e96be2020-08-31 13:16:04 -0400631
632 // Create variables in the extra statements to hold the arguments, and assign the arguments to
633 // them.
634 VariableRewriteMap varMap;
John Stilesbff24ab2021-03-17 13:20:10 -0400635 for (int i = 0; i < arguments.count(); ++i) {
John Stiles049f0df2021-03-19 09:39:44 -0400636 // If the parameter isn't written to within the inline function ...
John Stilesbff24ab2021-03-17 13:20:10 -0400637 const Variable* param = function.declaration().parameters()[i];
John Stiles049f0df2021-03-19 09:39:44 -0400638 const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
639 if (!paramUsage.fWrite) {
640 // ... and can be inlined trivially (e.g. a swizzle, or a constant array index),
641 // or any expression without side effects that is only accessed at most once...
642 if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arguments[i])
643 : !arguments[i]->hasSideEffects()) {
John Stilesf201af82020-09-29 16:57:55 -0400644 // ... we don't need to copy it at all! We can just use the existing expression.
645 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400646 continue;
647 }
648 }
John Stiles7b920442020-12-17 10:43:41 -0500649 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
650 symbolTable.get(), param->modifiers(),
651 caller->isBuiltin(), &arguments[i]);
John Stiles28257db2021-03-17 15:18:09 -0400652 inlineStatements.push_back(std::move(var.fVarDecl));
John Stiles7b920442020-12-17 10:43:41 -0500653 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400654 }
655
John Stiles7b920442020-12-17 10:43:41 -0500656 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles28257db2021-03-17 15:18:09 -0400657 inlineStatements.push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
658 &resultExpr, returnComplexity, *stmt,
659 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400660 }
661
John Stiles28257db2021-03-17 15:18:09 -0400662 SkASSERT(inlineStatements.count() <= expectedStmtCount);
663
John Stilesbf16b6c2021-03-12 19:24:31 -0500664 // Wrap all of the generated statements in a block. We need a real Block here, so we can't use
665 // MakeUnscoped. This is because we need to add another child statement to the Block later.
John Stiles28257db2021-03-17 15:18:09 -0400666 InlinedCall inlinedCall;
667 inlinedCall.fInlinedBody = Block::Make(offset, std::move(inlineStatements),
John Stilesbf16b6c2021-03-12 19:24:31 -0500668 /*symbols=*/nullptr, /*isScope=*/false);
669
John Stiles0c2d14a2021-03-01 10:08:08 -0500670 if (resultExpr) {
671 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400672 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles2558c462021-03-16 17:49:20 -0400673 } else if (function.declaration().returnType().isVoid()) {
John Stiles44e96be2020-08-31 13:16:04 -0400674 // It's a void function, so it doesn't actually result in anything, but we have to return
675 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500676 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500677 } else {
678 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500679 // returned anything on any path! This should have been detected in the function finalizer.
680 // Still, discard our output and generate an error.
681 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
682 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500683 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500684 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500685 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400686 }
687
John Stiles44e96be2020-08-31 13:16:04 -0400688 return inlinedCall;
689}
690
John Stiles2d7973a2020-10-02 15:01:03 -0400691bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400692 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500693 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400694 return false;
695 }
696
John Stiles031a7672020-11-13 16:13:18 -0500697 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
698 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
699 return false;
700 }
701
John Stiles2d7973a2020-10-02 15:01:03 -0400702 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400703 // Can't inline something if we don't actually have its definition.
704 return false;
705 }
John Stiles2d7973a2020-10-02 15:01:03 -0400706
John Stiles0dd1a772021-03-09 22:14:27 -0500707 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
708 // Refuse to inline functions decorated with `noinline`.
709 return false;
710 }
711
John Stilesbff24ab2021-03-17 13:20:10 -0400712 // We don't allow inlining a function with out parameters. (See skia:11326 for rationale.)
713 for (const Variable* param : functionDef->declaration().parameters()) {
714 if (param->modifiers().fFlags & Modifiers::Flag::kOut_Flag) {
715 return false;
716 }
717 }
718
John Stilesdc208472021-03-17 10:58:16 -0400719 // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
720 return GetReturnComplexity(*functionDef) < ReturnComplexity::kEarlyReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400721}
722
John Stiles2d7973a2020-10-02 15:01:03 -0400723// A candidate function for inlining, containing everything that `inlineCall` needs.
724struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500725 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400726 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
727 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
728 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
729 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400730};
John Stiles93442622020-09-11 12:11:27 -0400731
John Stiles2d7973a2020-10-02 15:01:03 -0400732struct InlineCandidateList {
733 std::vector<InlineCandidate> fCandidates;
734};
735
736class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400737public:
738 // A list of all the inlining candidates we found during analysis.
739 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400740
John Stiles70957c82020-10-02 16:42:10 -0400741 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
742 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500743 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400744 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
745 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
746 // inliner might replace a statement with a block containing the statement.
747 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
748 // The function that we're currently processing (i.e. inlining into).
749 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400750
Brian Osman0006ad02020-11-18 15:38:39 -0500751 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500752 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500753 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400754 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500755 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400756
Brian Osman0006ad02020-11-18 15:38:39 -0500757 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400758 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400759 }
760
John Stiles70957c82020-10-02 16:42:10 -0400761 fSymbolTableStack.pop_back();
762 fCandidateList = nullptr;
763 }
764
765 void visitProgramElement(ProgramElement* pe) {
766 switch (pe->kind()) {
767 case ProgramElement::Kind::kFunction: {
768 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500769 fEnclosingFunction = &funcDef;
770 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400771 break;
John Stiles93442622020-09-11 12:11:27 -0400772 }
John Stiles70957c82020-10-02 16:42:10 -0400773 default:
774 // The inliner can't operate outside of a function's scope.
775 break;
776 }
777 }
778
779 void visitStatement(std::unique_ptr<Statement>* stmt,
780 bool isViableAsEnclosingStatement = true) {
781 if (!*stmt) {
782 return;
John Stiles93442622020-09-11 12:11:27 -0400783 }
784
John Stiles70957c82020-10-02 16:42:10 -0400785 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
786 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400787
John Stiles70957c82020-10-02 16:42:10 -0400788 if (isViableAsEnclosingStatement) {
789 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400790 }
791
John Stiles70957c82020-10-02 16:42:10 -0400792 switch ((*stmt)->kind()) {
793 case Statement::Kind::kBreak:
794 case Statement::Kind::kContinue:
795 case Statement::Kind::kDiscard:
796 case Statement::Kind::kInlineMarker:
797 case Statement::Kind::kNop:
798 break;
799
800 case Statement::Kind::kBlock: {
801 Block& block = (*stmt)->as<Block>();
802 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500803 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400804 }
805
806 for (std::unique_ptr<Statement>& stmt : block.children()) {
807 this->visitStatement(&stmt);
808 }
809 break;
John Stiles93442622020-09-11 12:11:27 -0400810 }
John Stiles70957c82020-10-02 16:42:10 -0400811 case Statement::Kind::kDo: {
812 DoStatement& doStmt = (*stmt)->as<DoStatement>();
813 // The loop body is a candidate for inlining.
814 this->visitStatement(&doStmt.statement());
815 // The inliner isn't smart enough to inline the test-expression for a do-while
816 // loop at this time. There are two limitations:
817 // - We would need to insert the inlined-body block at the very end of the do-
818 // statement's inner fStatement. We don't support that today, but it's doable.
819 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
820 // would skip over the inlined block that evaluates the test expression. There
821 // isn't a good fix for this--any workaround would be more complex than the cost
822 // of a function call. However, loops that don't use `continue` would still be
823 // viable candidates for inlining.
824 break;
John Stiles93442622020-09-11 12:11:27 -0400825 }
John Stiles70957c82020-10-02 16:42:10 -0400826 case Statement::Kind::kExpression: {
827 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
828 this->visitExpression(&expr.expression());
829 break;
830 }
831 case Statement::Kind::kFor: {
832 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400833 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500834 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400835 }
836
837 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400838 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400839 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400840 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400841
842 // The inliner isn't smart enough to inline the test- or increment-expressions
843 // of a for loop loop at this time. There are a handful of limitations:
844 // - We would need to insert the test-expression block at the very beginning of the
845 // for-loop's inner fStatement, and the increment-expression block at the very
846 // end. We don't support that today, but it's doable.
847 // - The for-loop's built-in test-expression would need to be dropped entirely,
848 // and the loop would be halted via a break statement at the end of the inlined
849 // test-expression. This is again something we don't support today, but it could
850 // be implemented.
851 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
852 // that would skip over the inlined block that evaluates the increment expression.
853 // There isn't a good fix for this--any workaround would be more complex than the
854 // cost of a function call. However, loops that don't use `continue` would still
855 // be viable candidates for increment-expression inlining.
856 break;
857 }
858 case Statement::Kind::kIf: {
859 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400860 this->visitExpression(&ifStmt.test());
861 this->visitStatement(&ifStmt.ifTrue());
862 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400863 break;
864 }
865 case Statement::Kind::kReturn: {
866 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400867 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400868 break;
869 }
870 case Statement::Kind::kSwitch: {
871 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400872 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500873 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400874 }
875
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400876 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500877 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400878 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500879 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400880 }
881 break;
882 }
883 case Statement::Kind::kVarDeclaration: {
884 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
885 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400886 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400887 break;
888 }
John Stiles70957c82020-10-02 16:42:10 -0400889 default:
890 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400891 }
892
John Stiles70957c82020-10-02 16:42:10 -0400893 // Pop our symbol and enclosing-statement stacks.
894 fSymbolTableStack.resize(oldSymbolStackSize);
895 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
896 }
897
898 void visitExpression(std::unique_ptr<Expression>* expr) {
899 if (!*expr) {
900 return;
John Stiles93442622020-09-11 12:11:27 -0400901 }
John Stiles70957c82020-10-02 16:42:10 -0400902
903 switch ((*expr)->kind()) {
904 case Expression::Kind::kBoolLiteral:
905 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500906 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400907 case Expression::Kind::kFieldAccess:
908 case Expression::Kind::kFloatLiteral:
909 case Expression::Kind::kFunctionReference:
910 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400911 case Expression::Kind::kSetting:
912 case Expression::Kind::kTypeReference:
913 case Expression::Kind::kVariableReference:
914 // Nothing to scan here.
915 break;
916
917 case Expression::Kind::kBinary: {
918 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400919 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400920
921 // Logical-and and logical-or binary expressions do not inline the right side,
922 // because that would invalidate short-circuiting. That is, when evaluating
923 // expressions like these:
924 // (false && x()) // always false
925 // (true || y()) // always true
926 // It is illegal for side-effects from x() or y() to occur. The simplest way to
927 // enforce that rule is to avoid inlining the right side entirely. However, it is
928 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -0500929 Operator op = binaryExpr.getOperator();
930 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
931 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -0400932 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -0400933 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -0400934 }
935 break;
936 }
John Stiles7384b372021-04-01 13:48:15 -0400937 case Expression::Kind::kConstructor:
938 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -0400939 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -0400940 case Expression::Kind::kConstructorScalarCast:
John Stiles2938eea2021-04-01 18:58:25 -0400941 case Expression::Kind::kConstructorSplat: {
John Stiles7384b372021-04-01 13:48:15 -0400942 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
943 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
John Stiles70957c82020-10-02 16:42:10 -0400944 this->visitExpression(&arg);
945 }
946 break;
947 }
948 case Expression::Kind::kExternalFunctionCall: {
949 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
950 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
951 this->visitExpression(&arg);
952 }
953 break;
954 }
955 case Expression::Kind::kFunctionCall: {
956 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400957 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -0400958 this->visitExpression(&arg);
959 }
960 this->addInlineCandidate(expr);
961 break;
962 }
John Stiles708faba2021-03-19 09:43:23 -0400963 case Expression::Kind::kIndex: {
John Stiles70957c82020-10-02 16:42:10 -0400964 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400965 this->visitExpression(&indexExpr.base());
966 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -0400967 break;
968 }
969 case Expression::Kind::kPostfix: {
970 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400971 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400972 break;
973 }
974 case Expression::Kind::kPrefix: {
975 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400976 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -0400977 break;
978 }
979 case Expression::Kind::kSwizzle: {
980 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400981 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -0400982 break;
983 }
984 case Expression::Kind::kTernary: {
985 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
986 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -0400987 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -0400988 // The true- and false-expressions cannot be inlined, because we are only allowed to
989 // evaluate one side.
990 break;
991 }
992 default:
993 SkUNREACHABLE;
994 }
995 }
996
997 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
998 fCandidateList->fCandidates.push_back(
999 InlineCandidate{fSymbolTableStack.back(),
1000 find_parent_statement(fEnclosingStmtStack),
1001 fEnclosingStmtStack.back(),
1002 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001003 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001004 }
John Stiles2d7973a2020-10-02 15:01:03 -04001005};
John Stiles93442622020-09-11 12:11:27 -04001006
John Stiles9b9415e2020-11-23 14:48:06 -05001007static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1008 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1009}
John Stiles915a38c2020-09-14 09:38:13 -04001010
John Stiles9b9415e2020-11-23 14:48:06 -05001011bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1012 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001013 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001014 if (wasInserted) {
1015 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles132cfdd2021-03-15 22:08:38 +00001016 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1017 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001018 }
1019
John Stiles2d7973a2020-10-02 15:01:03 -04001020 return iter->second;
1021}
1022
John Stiles9b9415e2020-11-23 14:48:06 -05001023int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1024 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001025 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001026 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001027 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001028 }
John Stiles2d7973a2020-10-02 15:01:03 -04001029 return iter->second;
1030}
1031
Brian Osman0006ad02020-11-18 15:38:39 -05001032void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001033 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001034 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001035 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1036 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1037 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1038 // `const T&`.
1039 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001040 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001041
John Stiles0ad233f2020-11-25 11:02:05 -05001042 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001043 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001044 if (candidates.empty()) {
1045 return;
1046 }
1047
1048 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001049 InlinabilityCache cache;
1050 candidates.erase(std::remove_if(candidates.begin(),
1051 candidates.end(),
1052 [&](const InlineCandidate& candidate) {
1053 return !this->candidateCanBeInlined(candidate, &cache);
1054 }),
1055 candidates.end());
1056
John Stiles0ad233f2020-11-25 11:02:05 -05001057 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1058 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001059 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001060 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001061 }
John Stiles0ad233f2020-11-25 11:02:05 -05001062
1063 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1064 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1065 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1066 FunctionSizeCache functionSizeCache;
1067 FunctionSizeCache candidateTotalCost;
1068 for (InlineCandidate& candidate : candidates) {
1069 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1070 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1071 }
1072
John Stilesd1204642021-02-17 16:30:02 -05001073 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1074 [&](const InlineCandidate& candidate) {
1075 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1076 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1077 // Functions marked `inline` ignore size limitations.
1078 return false;
1079 }
1080 if (usage->get(fnDecl) == 1) {
1081 // If a function is only used once, it's cost-free to inline.
1082 return false;
1083 }
1084 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1085 // We won't exceed the inline threshold by inlining this.
1086 return false;
1087 }
1088 // Inlining this function will add too many IRNodes.
1089 return true;
1090 }),
1091 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001092}
1093
Brian Osman0006ad02020-11-18 15:38:39 -05001094bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001095 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001096 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001097 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001098 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001099 return false;
1100 }
1101
John Stiles031a7672020-11-13 16:13:18 -05001102 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1103 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1104 return false;
1105 }
1106
John Stiles2d7973a2020-10-02 15:01:03 -04001107 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001108 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001109
John Stiles915a38c2020-09-14 09:38:13 -04001110 // Inline the candidates where we've determined that it's safe to do so.
John Stiles708faba2021-03-19 09:43:23 -04001111 using StatementRemappingTable = std::unordered_map<std::unique_ptr<Statement>*,
1112 std::unique_ptr<Statement>*>;
1113 StatementRemappingTable statementRemappingTable;
1114
John Stiles915a38c2020-09-14 09:38:13 -04001115 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001116 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001117 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001118
John Stiles915a38c2020-09-14 09:38:13 -04001119 // Convert the function call to its inlined equivalent.
John Stiles30fce9c2021-03-18 09:24:06 -04001120 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols, *usage,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001121 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001122
John Stiles0c2d14a2021-03-01 10:08:08 -05001123 // Stop if an error was detected during the inlining process.
1124 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1125 break;
John Stiles915a38c2020-09-14 09:38:13 -04001126 }
1127
John Stiles0c2d14a2021-03-01 10:08:08 -05001128 // Ensure that the inlined body has a scope if it needs one.
1129 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1130
1131 // Add references within the inlined body
1132 usage->add(inlinedCall.fInlinedBody.get());
1133
John Stiles708faba2021-03-19 09:43:23 -04001134 // Look up the enclosing statement; remap it if necessary.
1135 std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1136 for (;;) {
1137 auto iter = statementRemappingTable.find(enclosingStmt);
1138 if (iter == statementRemappingTable.end()) {
1139 break;
1140 }
1141 enclosingStmt = iter->second;
1142 }
1143
John Stiles0c2d14a2021-03-01 10:08:08 -05001144 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1145 // function, then replace the enclosing statement with that Block.
1146 // Before:
1147 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1148 // fEnclosingStmt = stmt4
1149 // After:
1150 // fInlinedBody = null
1151 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
John Stiles708faba2021-03-19 09:43:23 -04001152 inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1153 *enclosingStmt = std::move(inlinedCall.fInlinedBody);
John Stiles0c2d14a2021-03-01 10:08:08 -05001154
John Stiles915a38c2020-09-14 09:38:13 -04001155 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001156 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001157 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1158 madeChanges = true;
1159
John Stiles708faba2021-03-19 09:43:23 -04001160 // If anything else pointed at our enclosing statement, it's now pointing at a Block
1161 // containing many other statements as well. Maintain a fix-up table to account for this.
1162 statementRemappingTable[enclosingStmt] = &(*enclosingStmt)->as<Block>().children().back();
1163
John Stiles031a7672020-11-13 16:13:18 -05001164 // Stop inlining if we've reached our hard cap on new statements.
1165 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1166 break;
1167 }
1168
John Stiles915a38c2020-09-14 09:38:13 -04001169 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1170 // remain valid.
1171 }
1172
1173 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001174}
1175
John Stiles44e96be2020-08-31 13:16:04 -04001176} // namespace SkSL