blob: d30cbcaef01b52782762c2b67d7a8fdfc074e454 [file] [log] [blame]
John Stiles44e96be2020-08-31 13:16:04 -04001/*
2 * Copyright 2020 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/sksl/SkSLInliner.h"
9
John Stiles2d7973a2020-10-02 15:01:03 -040010#include <limits.h>
John Stiles44e96be2020-08-31 13:16:04 -040011#include <memory>
12#include <unordered_set>
13
Ethan Nicholasdaed2592021-03-04 14:30:25 -050014#include "include/private/SkSLLayout.h"
John Stiles44e96be2020-08-31 13:16:04 -040015#include "src/sksl/SkSLAnalysis.h"
16#include "src/sksl/ir/SkSLBinaryExpression.h"
17#include "src/sksl/ir/SkSLBoolLiteral.h"
18#include "src/sksl/ir/SkSLBreakStatement.h"
19#include "src/sksl/ir/SkSLConstructor.h"
20#include "src/sksl/ir/SkSLContinueStatement.h"
21#include "src/sksl/ir/SkSLDiscardStatement.h"
22#include "src/sksl/ir/SkSLDoStatement.h"
23#include "src/sksl/ir/SkSLEnum.h"
24#include "src/sksl/ir/SkSLExpressionStatement.h"
25#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050026#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040027#include "src/sksl/ir/SkSLField.h"
28#include "src/sksl/ir/SkSLFieldAccess.h"
29#include "src/sksl/ir/SkSLFloatLiteral.h"
30#include "src/sksl/ir/SkSLForStatement.h"
31#include "src/sksl/ir/SkSLFunctionCall.h"
32#include "src/sksl/ir/SkSLFunctionDeclaration.h"
33#include "src/sksl/ir/SkSLFunctionDefinition.h"
34#include "src/sksl/ir/SkSLFunctionReference.h"
35#include "src/sksl/ir/SkSLIfStatement.h"
36#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040037#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040038#include "src/sksl/ir/SkSLIntLiteral.h"
39#include "src/sksl/ir/SkSLInterfaceBlock.h"
John Stiles44e96be2020-08-31 13:16:04 -040040#include "src/sksl/ir/SkSLNop.h"
John Stiles44e96be2020-08-31 13:16:04 -040041#include "src/sksl/ir/SkSLPostfixExpression.h"
42#include "src/sksl/ir/SkSLPrefixExpression.h"
43#include "src/sksl/ir/SkSLReturnStatement.h"
44#include "src/sksl/ir/SkSLSetting.h"
45#include "src/sksl/ir/SkSLSwitchCase.h"
46#include "src/sksl/ir/SkSLSwitchStatement.h"
47#include "src/sksl/ir/SkSLSwizzle.h"
48#include "src/sksl/ir/SkSLTernaryExpression.h"
49#include "src/sksl/ir/SkSLUnresolvedFunction.h"
50#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040051#include "src/sksl/ir/SkSLVariable.h"
52#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040053
54namespace SkSL {
55namespace {
56
John Stiles031a7672020-11-13 16:13:18 -050057static constexpr int kInlinedStatementLimit = 2500;
58
John Stiles44e96be2020-08-31 13:16:04 -040059static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
60 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
61 public:
62 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
63 this->visitProgramElement(funcDef);
64 }
65
66 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040067 switch (stmt.kind()) {
68 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040069 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040070 const auto& block = stmt.as<Block>();
71 return block.children().size() &&
72 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040073 }
Ethan Nicholase6592142020-09-08 10:22:09 -040074 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040075 case Statement::Kind::kDo:
76 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040077 // Don't introspect switches or loop structures at all.
78 return false;
79
Ethan Nicholase6592142020-09-08 10:22:09 -040080 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040081 ++fNumReturns;
82 [[fallthrough]];
83
84 default:
John Stiles93442622020-09-11 12:11:27 -040085 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040086 }
87 }
88
89 int fNumReturns = 0;
90 using INHERITED = ProgramVisitor;
91 };
92
93 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
94}
95
John Stiles74ebd7e2020-12-17 14:41:50 -050096static int count_returns_in_continuable_constructs(const FunctionDefinition& funcDef) {
97 class CountReturnsInContinuableConstructs : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040098 public:
John Stiles74ebd7e2020-12-17 14:41:50 -050099 CountReturnsInContinuableConstructs(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400100 this->visitProgramElement(funcDef);
101 }
102
103 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400104 switch (stmt.kind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400105 case Statement::Kind::kDo:
106 case Statement::Kind::kFor: {
John Stiles74ebd7e2020-12-17 14:41:50 -0500107 ++fInsideContinuableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400108 bool result = INHERITED::visitStatement(stmt);
John Stiles74ebd7e2020-12-17 14:41:50 -0500109 --fInsideContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400110 return result;
111 }
112
Ethan Nicholase6592142020-09-08 10:22:09 -0400113 case Statement::Kind::kReturn:
John Stiles74ebd7e2020-12-17 14:41:50 -0500114 fNumReturns += (fInsideContinuableConstruct > 0) ? 1 : 0;
John Stiles44e96be2020-08-31 13:16:04 -0400115 [[fallthrough]];
116
117 default:
John Stiles93442622020-09-11 12:11:27 -0400118 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400119 }
120 }
121
122 int fNumReturns = 0;
John Stiles74ebd7e2020-12-17 14:41:50 -0500123 int fInsideContinuableConstruct = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400124 using INHERITED = ProgramVisitor;
125 };
126
John Stiles74ebd7e2020-12-17 14:41:50 -0500127 return CountReturnsInContinuableConstructs{funcDef}.fNumReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400128}
129
John Stiles991b09d2020-09-10 13:33:40 -0400130static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
131 class ContainsRecursiveCall : public ProgramVisitor {
132 public:
133 bool visit(const FunctionDeclaration& funcDecl) {
134 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400135 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
136 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400137 }
138
139 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400140 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400141 return true;
142 }
143 return INHERITED::visitExpression(expr);
144 }
145
146 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400147 if (stmt.is<InlineMarker>() &&
148 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400149 return true;
150 }
151 return INHERITED::visitStatement(stmt);
152 }
153
154 const FunctionDeclaration* fFuncDecl;
155 using INHERITED = ProgramVisitor;
156 };
157
158 return ContainsRecursiveCall{}.visit(funcDecl);
159}
160
John Stiles6d696082020-10-01 10:18:54 -0400161static std::unique_ptr<Statement>* find_parent_statement(
162 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400163 SkASSERT(!stmtStack.empty());
164
165 // Walk the statement stack from back to front, ignoring the last element (which is the
166 // enclosing statement).
167 auto iter = stmtStack.rbegin();
168 ++iter;
169
170 // Anything counts as a parent statement other than a scopeless Block.
171 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400172 std::unique_ptr<Statement>* stmt = *iter;
173 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400174 return stmt;
175 }
176 }
177
178 // There wasn't any parent statement to be found.
179 return nullptr;
180}
181
John Stilese41b4ee2020-09-28 12:28:16 -0400182std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
183 VariableReference::RefKind refKind) {
184 std::unique_ptr<Expression> clone = expr.clone();
John Stiles47c0a742021-02-09 09:30:35 -0500185 Analysis::UpdateRefKind(clone.get(), refKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400186 return clone;
187}
188
John Stiles77702f12020-12-17 14:38:56 -0500189class CountReturnsWithLimit : public ProgramVisitor {
190public:
191 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
192 this->visitProgramElement(funcDef);
193 }
194
195 bool visitStatement(const Statement& stmt) override {
196 switch (stmt.kind()) {
197 case Statement::Kind::kReturn: {
198 ++fNumReturns;
199 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
200 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
201 }
John Stilesc5ff4862020-12-22 13:47:05 -0500202 case Statement::Kind::kVarDeclaration: {
203 if (fScopedBlockDepth > 1) {
204 fVariablesInBlocks = true;
205 }
206 return INHERITED::visitStatement(stmt);
207 }
John Stiles77702f12020-12-17 14:38:56 -0500208 case Statement::Kind::kBlock: {
209 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
210 fScopedBlockDepth += depthIncrement;
211 bool result = INHERITED::visitStatement(stmt);
212 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500213 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
214 // If closing this block puts us back at the top level, and we haven't
215 // encountered any return statements yet, any vardecls we may have encountered
216 // up until this point can be ignored. They are out of scope now, and they were
217 // never used in a return statement.
218 fVariablesInBlocks = false;
219 }
John Stiles77702f12020-12-17 14:38:56 -0500220 return result;
221 }
222 default:
223 return INHERITED::visitStatement(stmt);
224 }
225 }
226
227 int fNumReturns = 0;
228 int fDeepestReturn = 0;
229 int fLimit = 0;
230 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500231 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500232 using INHERITED = ProgramVisitor;
233};
234
John Stiles44e96be2020-08-31 13:16:04 -0400235} // namespace
236
John Stiles77702f12020-12-17 14:38:56 -0500237Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
238 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
239 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500240 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
241 return ReturnComplexity::kEarlyReturns;
242 }
John Stilesc5ff4862020-12-22 13:47:05 -0500243 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500244 return ReturnComplexity::kScopedReturns;
245 }
John Stilesc5ff4862020-12-22 13:47:05 -0500246 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
247 return ReturnComplexity::kScopedReturns;
248 }
249 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500250}
251
John Stilesb61ee902020-09-21 12:26:59 -0400252void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
253 // No changes necessary if this statement isn't actually a block.
254 if (!inlinedBody || !inlinedBody->is<Block>()) {
255 return;
256 }
257
258 // No changes necessary if the parent statement doesn't require a scope.
259 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500260 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400261 return;
262 }
263
264 Block& block = inlinedBody->as<Block>();
265
266 // The inliner will create inlined function bodies as a Block containing multiple statements,
267 // but no scope. Normally, this is fine, but if this block is used as the statement for a
268 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
269 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
270 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
271 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
272 // absorbing the following statement into our loop--so we also add a scope to these.
273 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400274 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400275 // We found an explicit scope; all is well.
276 return;
277 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400278 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400279 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
280 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400281 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400282 return;
283 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400284 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400285 // This block has exactly one thing inside, and it's not another block. No need to scope
286 // it.
287 return;
288 }
289 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400290 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400291 }
292}
293
John Stilesd1204642021-02-17 16:30:02 -0500294void Inliner::reset(ModifiersPool* modifiers) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400295 fModifiers = modifiers;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500296 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500297 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400298}
299
300std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
301 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500302 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400303 const Expression& expression) {
304 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
305 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500306 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400307 }
308 return nullptr;
309 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400310 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
311 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400312 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400313 for (const std::unique_ptr<Expression>& arg : originalArgs) {
314 args.push_back(expr(arg));
315 }
316 return args;
317 };
318
Ethan Nicholase6592142020-09-08 10:22:09 -0400319 switch (expression.kind()) {
320 case Expression::Kind::kBinary: {
John Stiles6a1a98c2021-01-14 18:35:34 -0500321 const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
John Stilese2aec432021-03-01 09:27:48 -0500322 return BinaryExpression::Make(*fContext,
323 expr(binaryExpr.left()),
324 binaryExpr.getOperator(),
325 expr(binaryExpr.right()));
John Stiles44e96be2020-08-31 13:16:04 -0400326 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400327 case Expression::Kind::kBoolLiteral:
328 case Expression::Kind::kIntLiteral:
329 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400330 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400331 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400332 const Constructor& constructor = expression.as<Constructor>();
John Stiles23521a82021-03-02 17:02:51 -0500333 auto inlinedCtor = Constructor::Convert(
334 *fContext, offset, *constructor.type().clone(symbolTableForExpression),
335 argList(constructor.arguments()));
336 SkASSERT(inlinedCtor);
337 return inlinedCtor;
John Stiles44e96be2020-08-31 13:16:04 -0400338 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400339 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400340 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400341 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400342 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400343 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500344 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400345 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400346 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400347 const FieldAccess& f = expression.as<FieldAccess>();
John Stiles06d600f2021-03-08 09:18:21 -0500348 return FieldAccess::Make(*fContext, expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400349 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400350 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400351 const FunctionCall& funcCall = expression.as<FunctionCall>();
John Stilesddcc8432021-01-15 15:32:32 -0500352 return std::make_unique<FunctionCall>(offset,
353 funcCall.type().clone(symbolTableForExpression),
354 &funcCall.function(),
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400355 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400356 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400357 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400358 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400359 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400360 const IndexExpression& idx = expression.as<IndexExpression>();
John Stiles51d33982021-03-08 09:18:07 -0500361 return IndexExpression::Make(*fContext, expr(idx.base()), expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400362 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400363 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400364 const PrefixExpression& p = expression.as<PrefixExpression>();
John Stilesb0eb20f2021-02-26 15:29:33 -0500365 return PrefixExpression::Make(*fContext, p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400366 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400367 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400368 const PostfixExpression& p = expression.as<PostfixExpression>();
John Stiles52d3b012021-02-26 15:56:48 -0500369 return PostfixExpression::Make(*fContext, expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400370 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400371 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400372 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400373 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400374 const Swizzle& s = expression.as<Swizzle>();
John Stiles6e88e042021-02-19 14:09:38 -0500375 return Swizzle::Make(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400376 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400377 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400378 const TernaryExpression& t = expression.as<TernaryExpression>();
John Stiles90518f72021-02-26 20:44:54 -0500379 return TernaryExpression::Make(*fContext, expr(t.test()),
380 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400381 }
Brian Osman83ba9302020-09-11 13:33:46 -0400382 case Expression::Kind::kTypeReference:
383 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400384 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400385 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400386 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400387 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400388 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400389 }
390 return v.clone();
391 }
392 default:
393 SkASSERT(false);
394 return nullptr;
395 }
396}
397
398std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
399 VariableRewriteMap* varMap,
400 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500401 std::unique_ptr<Expression>* resultExpr,
402 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400403 const Statement& statement,
404 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400405 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
406 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400407 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500408 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400409 }
410 return nullptr;
411 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400412 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400413 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400414 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400415 for (const std::unique_ptr<Statement>& child : block.children()) {
416 result.push_back(stmt(child));
417 }
418 return result;
419 };
John Stiles44e96be2020-08-31 13:16:04 -0400420 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
421 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500422 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400423 }
424 return nullptr;
425 };
John Stiles031a7672020-11-13 16:13:18 -0500426
427 ++fInlinedStatementCounter;
428
Ethan Nicholase6592142020-09-08 10:22:09 -0400429 switch (statement.kind()) {
430 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400431 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400432 return std::make_unique<Block>(offset, blockStmts(b),
433 SymbolTable::WrapIfBuiltin(b.symbolTable()),
434 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400435 }
436
Ethan Nicholase6592142020-09-08 10:22:09 -0400437 case Statement::Kind::kBreak:
438 case Statement::Kind::kContinue:
439 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400440 return statement.clone();
441
Ethan Nicholase6592142020-09-08 10:22:09 -0400442 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400443 const DoStatement& d = statement.as<DoStatement>();
John Stilesea5822e2021-02-26 11:18:20 -0500444 return DoStatement::Make(*fContext, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400445 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400446 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400447 const ExpressionStatement& e = statement.as<ExpressionStatement>();
John Stiles3e5871c2021-02-25 20:52:03 -0500448 return ExpressionStatement::Make(*fContext, expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400449 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400450 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400451 const ForStatement& f = statement.as<ForStatement>();
452 // need to ensure initializer is evaluated first so that we've already remapped its
453 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400454 std::unique_ptr<Statement> initializer = stmt(f.initializer());
John Stilesb321a072021-02-25 16:24:19 -0500455 return ForStatement::Make(*fContext, offset, std::move(initializer), expr(f.test()),
456 expr(f.next()), stmt(f.statement()),
457 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400458 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400459 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400460 const IfStatement& i = statement.as<IfStatement>();
John Stilescf3059e2021-02-25 14:27:02 -0500461 return IfStatement::Make(*fContext, offset, i.isStatic(), expr(i.test()),
462 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400463 }
John Stiles98c1f822020-09-09 14:18:53 -0400464 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400465 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400466 return statement.clone();
John Stilesea5822e2021-02-26 11:18:20 -0500467
Ethan Nicholase6592142020-09-08 10:22:09 -0400468 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400469 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500470 if (!r.expression()) {
471 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
472 // This function doesn't return a value, but has early returns, so we've wrapped
473 // it in a for loop. Use a continue to jump to the end of the loop and "leave"
474 // the function.
John Stiles7b920442020-12-17 10:43:41 -0500475 return std::make_unique<ContinueStatement>(offset);
John Stiles44e96be2020-08-31 13:16:04 -0400476 } else {
John Stiles77702f12020-12-17 14:38:56 -0500477 // This function doesn't exit early or return a value. A return statement at the
478 // end is a no-op and can be treated as such.
John Stiles44e96be2020-08-31 13:16:04 -0400479 return std::make_unique<Nop>();
480 }
481 }
John Stiles77702f12020-12-17 14:38:56 -0500482
John Stilesc5ff4862020-12-22 13:47:05 -0500483 // If a function only contains a single return, and it doesn't reference variables from
484 // inside an Block's scope, we don't need to store the result in a variable at all. Just
485 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500486 SkASSERT(resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500487 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500488 *resultExpr = expr(r.expression());
489 return std::make_unique<Nop>();
490 }
491
492 // For more complex functions, assign their result into a variable.
John Stiles511c5002021-02-25 11:17:02 -0500493 SkASSERT(*resultExpr);
John Stiles3e5871c2021-02-25 20:52:03 -0500494 auto assignment = ExpressionStatement::Make(
495 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500496 BinaryExpression::Make(
497 *fContext,
498 clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite),
John Stiles77702f12020-12-17 14:38:56 -0500499 Token::Kind::TK_EQ,
John Stilese2aec432021-03-01 09:27:48 -0500500 expr(r.expression())));
John Stiles77702f12020-12-17 14:38:56 -0500501
502 // Early returns are wrapped in a for loop; we need to synthesize a continue statement
503 // to "leave" the function.
504 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
505 StatementArray block;
506 block.reserve_back(2);
507 block.push_back(std::move(assignment));
508 block.push_back(std::make_unique<ContinueStatement>(offset));
509 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
510 /*isScope=*/true);
511 }
512 // Functions without early returns aren't wrapped in a for loop and don't need to worry
513 // about breaking out of the control flow.
John Stiles3e5871c2021-02-25 20:52:03 -0500514 return assignment;
John Stiles44e96be2020-08-31 13:16:04 -0400515 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400516 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400517 const SwitchStatement& ss = statement.as<SwitchStatement>();
John Stilesb23a64b2021-03-11 08:27:59 -0500518 StatementArray cases;
519 cases.reserve_back(ss.cases().size());
520 for (const std::unique_ptr<Statement>& statement : ss.cases()) {
521 const SwitchCase& sc = statement->as<SwitchCase>();
522 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc.value()),
523 stmt(sc.statement())));
John Stiles44e96be2020-08-31 13:16:04 -0400524 }
John Stilese1d1b082021-02-23 13:44:36 -0500525 return SwitchStatement::Make(*fContext, offset, ss.isStatic(), expr(ss.value()),
526 std::move(cases), SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400527 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400528 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400529 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000530 std::unique_ptr<Expression> initialValue = expr(decl.value());
John Stilesddcc8432021-01-15 15:32:32 -0500531 const Variable& variable = decl.var();
532
John Stiles35fee4c2020-12-16 18:25:14 +0000533 // We assign unique names to inlined variables--scopes hide most of the problems in this
534 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
535 // names are important.
John Stilesddcc8432021-01-15 15:32:32 -0500536 auto name = std::make_unique<String>(fMangler.uniqueName(variable.name(),
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500537 symbolTableForStatement));
John Stiles35fee4c2020-12-16 18:25:14 +0000538 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500539 auto clonedVar = std::make_unique<Variable>(
540 offset,
541 &variable.modifiers(),
542 namePtr->c_str(),
543 variable.type().clone(symbolTableForStatement),
544 isBuiltinCode,
545 variable.storage());
546 (*varMap)[&variable] = std::make_unique<VariableReference>(offset, clonedVar.get());
547 auto result = std::make_unique<VarDeclaration>(clonedVar.get(),
John Stilesddcc8432021-01-15 15:32:32 -0500548 decl.baseType().clone(symbolTableForStatement),
549 decl.arraySize(),
John Stiles35fee4c2020-12-16 18:25:14 +0000550 std::move(initialValue));
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500551 clonedVar->setDeclaration(result.get());
552 symbolTableForStatement->takeOwnershipOfSymbol(std::move(clonedVar));
553 return std::move(result);
John Stiles44e96be2020-08-31 13:16:04 -0400554 }
John Stiles44e96be2020-08-31 13:16:04 -0400555 default:
556 SkASSERT(false);
557 return nullptr;
558 }
559}
560
John Stiles7b920442020-12-17 10:43:41 -0500561Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
562 const Type* type,
563 SymbolTable* symbolTable,
564 Modifiers modifiers,
565 bool isBuiltinCode,
566 std::unique_ptr<Expression>* initialValue) {
567 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
568 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
569 // somewhere during compilation.
John Stiles14975272021-01-12 11:41:14 -0500570 if (type->isLiteral()) {
571 SkDEBUGFAIL("found a $literal type while inlining");
572 type = &type->scalarTypeForLiteral();
John Stiles7b920442020-12-17 10:43:41 -0500573 }
574
575 // Provide our new variable with a unique name, and add it to our symbol table.
576 const String* namePtr = symbolTable->takeOwnershipOfString(
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500577 std::make_unique<String>(fMangler.uniqueName(baseName, symbolTable)));
John Stiles7b920442020-12-17 10:43:41 -0500578 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
579
580 // Create our new variable and add it to the symbol table.
581 InlineVariable result;
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500582 auto var = std::make_unique<Variable>(/*offset=*/-1,
583 fModifiers->addToPool(Modifiers()),
584 nameFrag,
585 type,
586 isBuiltinCode,
587 Variable::Storage::kLocal);
John Stiles7b920442020-12-17 10:43:41 -0500588
589 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
590 // initial value).
591 if (*initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500592 result.fVarDecl = std::make_unique<VarDeclaration>(var.get(), type, /*arraySize=*/0,
John Stiles7b920442020-12-17 10:43:41 -0500593 (*initialValue)->clone());
594 } else {
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500595 result.fVarDecl = std::make_unique<VarDeclaration>(var.get(), type, /*arraySize=*/0,
John Stiles7b920442020-12-17 10:43:41 -0500596 std::move(*initialValue));
597 }
Ethan Nicholas5b9b0db2021-01-21 13:12:01 -0500598 var->setDeclaration(&result.fVarDecl->as<VarDeclaration>());
599 result.fVarSymbol = symbolTable->add(std::move(var));
John Stiles7b920442020-12-17 10:43:41 -0500600 return result;
601}
602
John Stiles6eadf132020-09-08 10:16:10 -0400603Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500604 std::shared_ptr<SymbolTable> symbolTable,
Brian Osman3887a012020-09-30 13:22:27 -0400605 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400606 // Inlining is more complicated here than in a typical compiler, because we have to have a
607 // high-level IR and can't just drop statements into the middle of an expression or even use
608 // gotos.
609 //
610 // Since we can't insert statements into an expression, we run the inline function as extra
611 // statements before the statement we're currently processing, relying on a lack of execution
612 // order guarantees. Since we can't use gotos (which are normally used to replace return
613 // statements), we wrap the whole function in a loop and use break statements to jump to the
614 // end.
John Stiles44e96be2020-08-31 13:16:04 -0400615 SkASSERT(fContext);
616 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400617 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400618
John Stiles8e3b6be2020-10-13 11:14:08 -0400619 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400620 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400621 const FunctionDefinition& function = *call->function().definition();
John Stiles77702f12020-12-17 14:38:56 -0500622 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
623 bool hasEarlyReturn = (returnComplexity >= ReturnComplexity::kEarlyReturns);
John Stiles6eadf132020-09-08 10:16:10 -0400624
John Stiles44e96be2020-08-31 13:16:04 -0400625 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400626 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400627 /*symbols=*/nullptr,
628 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400629
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400630 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400631 inlinedBody.children().reserve_back(
632 1 + // Inline marker
633 1 + // Result variable
634 arguments.size() + // Function arguments (passing in)
635 arguments.size() + // Function arguments (copy out-params back)
John Stiles7b920442020-12-17 10:43:41 -0500636 1); // Block for inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400637
Ethan Nicholasceb62142020-10-09 16:51:18 -0400638 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400639
John Stilese41b4ee2020-09-28 12:28:16 -0400640 std::unique_ptr<Expression> resultExpr;
John Stiles511c5002021-02-25 11:17:02 -0500641 if (returnComplexity > ReturnComplexity::kSingleSafeReturn &&
642 function.declaration().returnType() != *fContext->fTypes.fVoid) {
643 // Create a variable to hold the result in the extra statements. We don't need to do this
644 // for void-return functions, or in cases that are simple enough that we can just replace
645 // the function-call node with the result expression.
John Stiles44e96be2020-08-31 13:16:04 -0400646 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500647 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
648 &function.declaration().returnType(),
649 symbolTable.get(), Modifiers{},
650 caller->isBuiltin(), &noInitialValue);
651 inlinedBody.children().push_back(std::move(var.fVarDecl));
652 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles511c5002021-02-25 11:17:02 -0500653 }
John Stiles44e96be2020-08-31 13:16:04 -0400654
655 // Create variables in the extra statements to hold the arguments, and assign the arguments to
656 // them.
657 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400658 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400659 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400660 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400661 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400662
John Stiles44733aa2020-09-29 17:42:23 -0400663 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500664 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400665 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400666 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400667 // ... we don't need to copy it at all! We can just use the existing expression.
668 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400669 continue;
670 }
671 }
John Stilese41b4ee2020-09-28 12:28:16 -0400672 if (isOutParam) {
673 argsToCopyBack.push_back(i);
674 }
John Stiles7b920442020-12-17 10:43:41 -0500675 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
676 symbolTable.get(), param->modifiers(),
677 caller->isBuiltin(), &arguments[i]);
678 inlinedBody.children().push_back(std::move(var.fVarDecl));
679 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400680 }
681
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400682 const Block& body = function.body()->as<Block>();
John Stiles7b920442020-12-17 10:43:41 -0500683 StatementArray* inlineStatements;
684
John Stiles44e96be2020-08-31 13:16:04 -0400685 if (hasEarlyReturn) {
686 // Since we output to backends that don't have a goto statement (which would normally be
John Stiles7b920442020-12-17 10:43:41 -0500687 // used to perform an early return), we fake it by wrapping the function in a single-
688 // iteration for loop, and use a continue statement to jump to the end of the loop
689 // prematurely.
690
691 // int _1_loop = 0;
692 symbolTable = std::make_shared<SymbolTable>(std::move(symbolTable), caller->isBuiltin());
John Stiles54e7c052021-01-11 14:22:36 -0500693 const Type* intType = fContext->fTypes.fInt.get();
John Stiles9ce80f72021-03-11 22:35:19 -0500694 std::unique_ptr<Expression> initialValue = IntLiteral::Make(/*offset=*/-1,
695 /*value=*/0,
696 intType);
John Stiles7b920442020-12-17 10:43:41 -0500697 InlineVariable loopVar = this->makeInlineVariable("loop", intType, symbolTable.get(),
698 Modifiers{}, caller->isBuiltin(),
699 &initialValue);
700
701 // _1_loop < 1;
John Stilese2aec432021-03-01 09:27:48 -0500702 std::unique_ptr<Expression> test = BinaryExpression::Make(
703 *fContext,
John Stiles7b920442020-12-17 10:43:41 -0500704 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol),
705 Token::Kind::TK_LT,
John Stiles9ce80f72021-03-11 22:35:19 -0500706 IntLiteral::Make(/*offset=*/-1, /*value=*/1, intType));
John Stiles7b920442020-12-17 10:43:41 -0500707
708 // _1_loop++
John Stiles52d3b012021-02-26 15:56:48 -0500709 std::unique_ptr<Expression> increment = PostfixExpression::Make(
710 *fContext,
John Stiles7b920442020-12-17 10:43:41 -0500711 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol,
712 VariableReference::RefKind::kReadWrite),
713 Token::Kind::TK_PLUSPLUS);
714
715 // {...}
716 auto innerBlock = std::make_unique<Block>(offset, StatementArray{},
717 /*symbols=*/nullptr, /*isScope=*/true);
718 inlineStatements = &innerBlock->children();
719
720 // for (int _1_loop = 0; _1_loop < 1; _1_loop++) {...}
John Stilesb321a072021-02-25 16:24:19 -0500721 inlinedBody.children().push_back(ForStatement::Make(*fContext, /*offset=*/-1,
722 std::move(loopVar.fVarDecl),
723 std::move(test),
724 std::move(increment),
725 std::move(innerBlock),
726 symbolTable));
John Stiles44e96be2020-08-31 13:16:04 -0400727 } else {
John Stilesfa9a0832020-12-17 10:43:58 -0500728 // No early returns, so we can just dump the code into our existing scopeless block.
729 inlineStatements = &inlinedBody.children();
John Stiles7b920442020-12-17 10:43:41 -0500730 }
731
732 inlineStatements->reserve_back(body.children().size() + argsToCopyBack.size());
733 for (const std::unique_ptr<Statement>& stmt : body.children()) {
734 inlineStatements->push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles77702f12020-12-17 14:38:56 -0500735 &resultExpr, returnComplexity, *stmt,
John Stiles7b920442020-12-17 10:43:41 -0500736 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400737 }
738
John Stilese41b4ee2020-09-28 12:28:16 -0400739 // Copy back the values of `out` parameters into their real destinations.
740 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400741 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400742 SkASSERT(varMap.find(p) != varMap.end());
John Stiles3e5871c2021-02-25 20:52:03 -0500743 inlineStatements->push_back(ExpressionStatement::Make(
744 *fContext,
John Stilese2aec432021-03-01 09:27:48 -0500745 BinaryExpression::Make(*fContext,
746 clone_with_ref_kind(*arguments[i], VariableRefKind::kWrite),
747 Token::Kind::TK_EQ,
748 std::move(varMap[p]))));
John Stiles44e96be2020-08-31 13:16:04 -0400749 }
750
John Stiles0c2d14a2021-03-01 10:08:08 -0500751 if (resultExpr) {
752 // Return our result expression as-is.
John Stilese41b4ee2020-09-28 12:28:16 -0400753 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles0c2d14a2021-03-01 10:08:08 -0500754 } else if (function.declaration().returnType() == *fContext->fTypes.fVoid) {
John Stiles44e96be2020-08-31 13:16:04 -0400755 // It's a void function, so it doesn't actually result in anything, but we have to return
756 // something non-null as a standin.
John Stiles9ce80f72021-03-11 22:35:19 -0500757 inlinedCall.fReplacementExpr = BoolLiteral::Make(*fContext, offset, /*value=*/false);
John Stiles0c2d14a2021-03-01 10:08:08 -0500758 } else {
759 // It's a non-void function, but it never created a result expression--that is, it never
John Stiles2dda50d2021-03-03 10:46:44 -0500760 // returned anything on any path! This should have been detected in the function finalizer.
761 // Still, discard our output and generate an error.
762 SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
763 fContext->fErrors.error(function.fOffset, "inliner found non-void function '" +
John Stiles0c2d14a2021-03-01 10:08:08 -0500764 function.declaration().name() +
John Stiles2dda50d2021-03-03 10:46:44 -0500765 "' that fails to return a value on any path");
John Stiles0c2d14a2021-03-01 10:08:08 -0500766 inlinedCall = {};
John Stiles44e96be2020-08-31 13:16:04 -0400767 }
768
John Stiles44e96be2020-08-31 13:16:04 -0400769 return inlinedCall;
770}
771
John Stiles2d7973a2020-10-02 15:01:03 -0400772bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles1c03d332020-10-13 10:30:23 -0400773 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -0500774 if (this->settings().fInlineThreshold <= 0) {
John Stiles1c03d332020-10-13 10:30:23 -0400775 return false;
776 }
777
John Stiles031a7672020-11-13 16:13:18 -0500778 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
779 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
780 return false;
781 }
782
John Stiles2d7973a2020-10-02 15:01:03 -0400783 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400784 // Can't inline something if we don't actually have its definition.
785 return false;
786 }
John Stiles2d7973a2020-10-02 15:01:03 -0400787
John Stiles0dd1a772021-03-09 22:14:27 -0500788 if (functionDef->declaration().modifiers().fFlags & Modifiers::kNoInline_Flag) {
789 // Refuse to inline functions decorated with `noinline`.
790 return false;
791 }
792
John Stiles74ebd7e2020-12-17 14:41:50 -0500793 // We don't have any mechanism to simulate early returns within a construct that supports
794 // continues (for/do/while), so we can't inline if there's a return inside one.
795 bool hasReturnInContinuableConstruct =
796 (count_returns_in_continuable_constructs(*functionDef) > 0);
797 return !hasReturnInContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400798}
799
John Stiles2d7973a2020-10-02 15:01:03 -0400800// A candidate function for inlining, containing everything that `inlineCall` needs.
801struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500802 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400803 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
804 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
805 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
806 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400807};
John Stiles93442622020-09-11 12:11:27 -0400808
John Stiles2d7973a2020-10-02 15:01:03 -0400809struct InlineCandidateList {
810 std::vector<InlineCandidate> fCandidates;
811};
812
813class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400814public:
815 // A list of all the inlining candidates we found during analysis.
816 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400817
John Stiles70957c82020-10-02 16:42:10 -0400818 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
819 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500820 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400821 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
822 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
823 // inliner might replace a statement with a block containing the statement.
824 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
825 // The function that we're currently processing (i.e. inlining into).
826 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400827
Brian Osman0006ad02020-11-18 15:38:39 -0500828 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500829 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500830 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400831 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500832 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400833
Brian Osman0006ad02020-11-18 15:38:39 -0500834 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400835 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400836 }
837
John Stiles70957c82020-10-02 16:42:10 -0400838 fSymbolTableStack.pop_back();
839 fCandidateList = nullptr;
840 }
841
842 void visitProgramElement(ProgramElement* pe) {
843 switch (pe->kind()) {
844 case ProgramElement::Kind::kFunction: {
845 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500846 fEnclosingFunction = &funcDef;
847 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400848 break;
John Stiles93442622020-09-11 12:11:27 -0400849 }
John Stiles70957c82020-10-02 16:42:10 -0400850 default:
851 // The inliner can't operate outside of a function's scope.
852 break;
853 }
854 }
855
856 void visitStatement(std::unique_ptr<Statement>* stmt,
857 bool isViableAsEnclosingStatement = true) {
858 if (!*stmt) {
859 return;
John Stiles93442622020-09-11 12:11:27 -0400860 }
861
John Stiles70957c82020-10-02 16:42:10 -0400862 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
863 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400864
John Stiles70957c82020-10-02 16:42:10 -0400865 if (isViableAsEnclosingStatement) {
866 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400867 }
868
John Stiles70957c82020-10-02 16:42:10 -0400869 switch ((*stmt)->kind()) {
870 case Statement::Kind::kBreak:
871 case Statement::Kind::kContinue:
872 case Statement::Kind::kDiscard:
873 case Statement::Kind::kInlineMarker:
874 case Statement::Kind::kNop:
875 break;
876
877 case Statement::Kind::kBlock: {
878 Block& block = (*stmt)->as<Block>();
879 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500880 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400881 }
882
883 for (std::unique_ptr<Statement>& stmt : block.children()) {
884 this->visitStatement(&stmt);
885 }
886 break;
John Stiles93442622020-09-11 12:11:27 -0400887 }
John Stiles70957c82020-10-02 16:42:10 -0400888 case Statement::Kind::kDo: {
889 DoStatement& doStmt = (*stmt)->as<DoStatement>();
890 // The loop body is a candidate for inlining.
891 this->visitStatement(&doStmt.statement());
892 // The inliner isn't smart enough to inline the test-expression for a do-while
893 // loop at this time. There are two limitations:
894 // - We would need to insert the inlined-body block at the very end of the do-
895 // statement's inner fStatement. We don't support that today, but it's doable.
896 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
897 // would skip over the inlined block that evaluates the test expression. There
898 // isn't a good fix for this--any workaround would be more complex than the cost
899 // of a function call. However, loops that don't use `continue` would still be
900 // viable candidates for inlining.
901 break;
John Stiles93442622020-09-11 12:11:27 -0400902 }
John Stiles70957c82020-10-02 16:42:10 -0400903 case Statement::Kind::kExpression: {
904 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
905 this->visitExpression(&expr.expression());
906 break;
907 }
908 case Statement::Kind::kFor: {
909 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400910 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500911 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400912 }
913
914 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400915 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400916 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400917 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400918
919 // The inliner isn't smart enough to inline the test- or increment-expressions
920 // of a for loop loop at this time. There are a handful of limitations:
921 // - We would need to insert the test-expression block at the very beginning of the
922 // for-loop's inner fStatement, and the increment-expression block at the very
923 // end. We don't support that today, but it's doable.
924 // - The for-loop's built-in test-expression would need to be dropped entirely,
925 // and the loop would be halted via a break statement at the end of the inlined
926 // test-expression. This is again something we don't support today, but it could
927 // be implemented.
928 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
929 // that would skip over the inlined block that evaluates the increment expression.
930 // There isn't a good fix for this--any workaround would be more complex than the
931 // cost of a function call. However, loops that don't use `continue` would still
932 // be viable candidates for increment-expression inlining.
933 break;
934 }
935 case Statement::Kind::kIf: {
936 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400937 this->visitExpression(&ifStmt.test());
938 this->visitStatement(&ifStmt.ifTrue());
939 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400940 break;
941 }
942 case Statement::Kind::kReturn: {
943 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400944 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400945 break;
946 }
947 case Statement::Kind::kSwitch: {
948 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400949 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500950 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400951 }
952
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400953 this->visitExpression(&switchStmt.value());
John Stilesb23a64b2021-03-11 08:27:59 -0500954 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400955 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stilesb23a64b2021-03-11 08:27:59 -0500956 this->visitStatement(&switchCase->as<SwitchCase>().statement());
John Stiles70957c82020-10-02 16:42:10 -0400957 }
958 break;
959 }
960 case Statement::Kind::kVarDeclaration: {
961 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
962 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400963 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400964 break;
965 }
John Stiles70957c82020-10-02 16:42:10 -0400966 default:
967 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400968 }
969
John Stiles70957c82020-10-02 16:42:10 -0400970 // Pop our symbol and enclosing-statement stacks.
971 fSymbolTableStack.resize(oldSymbolStackSize);
972 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
973 }
974
975 void visitExpression(std::unique_ptr<Expression>* expr) {
976 if (!*expr) {
977 return;
John Stiles93442622020-09-11 12:11:27 -0400978 }
John Stiles70957c82020-10-02 16:42:10 -0400979
980 switch ((*expr)->kind()) {
981 case Expression::Kind::kBoolLiteral:
982 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500983 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -0400984 case Expression::Kind::kFieldAccess:
985 case Expression::Kind::kFloatLiteral:
986 case Expression::Kind::kFunctionReference:
987 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -0400988 case Expression::Kind::kSetting:
989 case Expression::Kind::kTypeReference:
990 case Expression::Kind::kVariableReference:
991 // Nothing to scan here.
992 break;
993
994 case Expression::Kind::kBinary: {
995 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400996 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -0400997
998 // Logical-and and logical-or binary expressions do not inline the right side,
999 // because that would invalidate short-circuiting. That is, when evaluating
1000 // expressions like these:
1001 // (false && x()) // always false
1002 // (true || y()) // always true
1003 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1004 // enforce that rule is to avoid inlining the right side entirely. However, it is
1005 // safe for other types of binary expression to inline both sides.
John Stiles45990502021-02-16 10:55:27 -05001006 Operator op = binaryExpr.getOperator();
1007 bool shortCircuitable = (op.kind() == Token::Kind::TK_LOGICALAND ||
1008 op.kind() == Token::Kind::TK_LOGICALOR);
John Stiles70957c82020-10-02 16:42:10 -04001009 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001010 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001011 }
1012 break;
1013 }
1014 case Expression::Kind::kConstructor: {
1015 Constructor& constructorExpr = (*expr)->as<Constructor>();
1016 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1017 this->visitExpression(&arg);
1018 }
1019 break;
1020 }
1021 case Expression::Kind::kExternalFunctionCall: {
1022 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1023 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1024 this->visitExpression(&arg);
1025 }
1026 break;
1027 }
1028 case Expression::Kind::kFunctionCall: {
1029 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001030 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001031 this->visitExpression(&arg);
1032 }
1033 this->addInlineCandidate(expr);
1034 break;
1035 }
1036 case Expression::Kind::kIndex:{
1037 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001038 this->visitExpression(&indexExpr.base());
1039 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001040 break;
1041 }
1042 case Expression::Kind::kPostfix: {
1043 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001044 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001045 break;
1046 }
1047 case Expression::Kind::kPrefix: {
1048 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001049 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001050 break;
1051 }
1052 case Expression::Kind::kSwizzle: {
1053 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001054 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001055 break;
1056 }
1057 case Expression::Kind::kTernary: {
1058 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1059 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001060 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001061 // The true- and false-expressions cannot be inlined, because we are only allowed to
1062 // evaluate one side.
1063 break;
1064 }
1065 default:
1066 SkUNREACHABLE;
1067 }
1068 }
1069
1070 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1071 fCandidateList->fCandidates.push_back(
1072 InlineCandidate{fSymbolTableStack.back(),
1073 find_parent_statement(fEnclosingStmtStack),
1074 fEnclosingStmtStack.back(),
1075 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001076 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001077 }
John Stiles2d7973a2020-10-02 15:01:03 -04001078};
John Stiles93442622020-09-11 12:11:27 -04001079
John Stiles9b9415e2020-11-23 14:48:06 -05001080static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1081 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1082}
John Stiles915a38c2020-09-14 09:38:13 -04001083
John Stiles9b9415e2020-11-23 14:48:06 -05001084bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1085 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001086 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001087 if (wasInserted) {
1088 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001089 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1090 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001091 }
1092
John Stiles2d7973a2020-10-02 15:01:03 -04001093 return iter->second;
1094}
1095
John Stiles9b9415e2020-11-23 14:48:06 -05001096int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1097 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001098 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001099 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
John Stilesd1204642021-02-17 16:30:02 -05001100 this->settings().fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001101 }
John Stiles2d7973a2020-10-02 15:01:03 -04001102 return iter->second;
1103}
1104
Brian Osman0006ad02020-11-18 15:38:39 -05001105void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001106 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001107 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001108 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1109 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1110 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1111 // `const T&`.
1112 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001113 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001114
John Stiles0ad233f2020-11-25 11:02:05 -05001115 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001116 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001117 if (candidates.empty()) {
1118 return;
1119 }
1120
1121 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001122 InlinabilityCache cache;
1123 candidates.erase(std::remove_if(candidates.begin(),
1124 candidates.end(),
1125 [&](const InlineCandidate& candidate) {
1126 return !this->candidateCanBeInlined(candidate, &cache);
1127 }),
1128 candidates.end());
1129
John Stiles0ad233f2020-11-25 11:02:05 -05001130 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1131 // complete.
John Stilesd1204642021-02-17 16:30:02 -05001132 if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
John Stiles0ad233f2020-11-25 11:02:05 -05001133 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001134 }
John Stiles0ad233f2020-11-25 11:02:05 -05001135
1136 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1137 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1138 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1139 FunctionSizeCache functionSizeCache;
1140 FunctionSizeCache candidateTotalCost;
1141 for (InlineCandidate& candidate : candidates) {
1142 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1143 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1144 }
1145
John Stilesd1204642021-02-17 16:30:02 -05001146 candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1147 [&](const InlineCandidate& candidate) {
1148 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1149 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1150 // Functions marked `inline` ignore size limitations.
1151 return false;
1152 }
1153 if (usage->get(fnDecl) == 1) {
1154 // If a function is only used once, it's cost-free to inline.
1155 return false;
1156 }
1157 if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1158 // We won't exceed the inline threshold by inlining this.
1159 return false;
1160 }
1161 // Inlining this function will add too many IRNodes.
1162 return true;
1163 }),
1164 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001165}
1166
Brian Osman0006ad02020-11-18 15:38:39 -05001167bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001168 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001169 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001170 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
John Stilesd1204642021-02-17 16:30:02 -05001171 if (this->settings().fInlineThreshold <= 0) {
John Stilesd34d56e2020-10-12 12:04:47 -04001172 return false;
1173 }
1174
John Stiles031a7672020-11-13 16:13:18 -05001175 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1176 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1177 return false;
1178 }
1179
John Stiles2d7973a2020-10-02 15:01:03 -04001180 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001181 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001182
John Stiles915a38c2020-09-14 09:38:13 -04001183 // Inline the candidates where we've determined that it's safe to do so.
1184 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1185 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001186 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001187 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001188
1189 // Inlining two expressions using the same enclosing statement in the same inlining pass
1190 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1191 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1192 if (!inserted) {
1193 continue;
1194 }
1195
1196 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001197 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001198 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001199
John Stiles0c2d14a2021-03-01 10:08:08 -05001200 // Stop if an error was detected during the inlining process.
1201 if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1202 break;
John Stiles915a38c2020-09-14 09:38:13 -04001203 }
1204
John Stiles0c2d14a2021-03-01 10:08:08 -05001205 // Ensure that the inlined body has a scope if it needs one.
1206 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1207
1208 // Add references within the inlined body
1209 usage->add(inlinedCall.fInlinedBody.get());
1210
1211 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1212 // function, then replace the enclosing statement with that Block.
1213 // Before:
1214 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1215 // fEnclosingStmt = stmt4
1216 // After:
1217 // fInlinedBody = null
1218 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
1219 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
1220 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1221
John Stiles915a38c2020-09-14 09:38:13 -04001222 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001223 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001224 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1225 madeChanges = true;
1226
John Stiles031a7672020-11-13 16:13:18 -05001227 // Stop inlining if we've reached our hard cap on new statements.
1228 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1229 break;
1230 }
1231
John Stiles915a38c2020-09-14 09:38:13 -04001232 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1233 // remain valid.
1234 }
1235
1236 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001237}
1238
John Stiles44e96be2020-08-31 13:16:04 -04001239} // namespace SkSL