blob: e0fcc2fb57075a866f64f76844f0349b91fa5d04 [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
14#include "src/sksl/SkSLAnalysis.h"
15#include "src/sksl/ir/SkSLBinaryExpression.h"
16#include "src/sksl/ir/SkSLBoolLiteral.h"
17#include "src/sksl/ir/SkSLBreakStatement.h"
18#include "src/sksl/ir/SkSLConstructor.h"
19#include "src/sksl/ir/SkSLContinueStatement.h"
20#include "src/sksl/ir/SkSLDiscardStatement.h"
21#include "src/sksl/ir/SkSLDoStatement.h"
22#include "src/sksl/ir/SkSLEnum.h"
23#include "src/sksl/ir/SkSLExpressionStatement.h"
24#include "src/sksl/ir/SkSLExternalFunctionCall.h"
Brian Osmanbe0b3b72021-01-06 14:27:35 -050025#include "src/sksl/ir/SkSLExternalFunctionReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040026#include "src/sksl/ir/SkSLField.h"
27#include "src/sksl/ir/SkSLFieldAccess.h"
28#include "src/sksl/ir/SkSLFloatLiteral.h"
29#include "src/sksl/ir/SkSLForStatement.h"
30#include "src/sksl/ir/SkSLFunctionCall.h"
31#include "src/sksl/ir/SkSLFunctionDeclaration.h"
32#include "src/sksl/ir/SkSLFunctionDefinition.h"
33#include "src/sksl/ir/SkSLFunctionReference.h"
34#include "src/sksl/ir/SkSLIfStatement.h"
35#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040036#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040037#include "src/sksl/ir/SkSLIntLiteral.h"
38#include "src/sksl/ir/SkSLInterfaceBlock.h"
39#include "src/sksl/ir/SkSLLayout.h"
40#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 Stiles44e96be2020-08-31 13:16:04 -0400161static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
John Stilesc0c51062020-12-03 17:16:29 -0500162 if (src->isArray()) {
John Stilesc5ff4862020-12-22 13:47:05 -0500163 return symbolTable.takeOwnershipOfSymbol(
164 Type::MakeArrayType(src->name(), src->componentType(), src->columns()));
John Stiles44e96be2020-08-31 13:16:04 -0400165 }
166 return src;
167}
168
John Stiles6d696082020-10-01 10:18:54 -0400169static std::unique_ptr<Statement>* find_parent_statement(
170 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400171 SkASSERT(!stmtStack.empty());
172
173 // Walk the statement stack from back to front, ignoring the last element (which is the
174 // enclosing statement).
175 auto iter = stmtStack.rbegin();
176 ++iter;
177
178 // Anything counts as a parent statement other than a scopeless Block.
179 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400180 std::unique_ptr<Statement>* stmt = *iter;
181 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400182 return stmt;
183 }
184 }
185
186 // There wasn't any parent statement to be found.
187 return nullptr;
188}
189
John Stilese41b4ee2020-09-28 12:28:16 -0400190std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
191 VariableReference::RefKind refKind) {
192 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400193 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400194 public:
195 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400196 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400197 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400198 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400199 }
200 return INHERITED::visitExpression(expr);
201 }
202
203 private:
204 VariableReference::RefKind fRefKind;
205
John Stiles70b82422020-09-30 10:55:12 -0400206 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400207 };
208
209 SetRefKindInExpression{refKind}.visitExpression(*clone);
210 return clone;
211}
212
John Stiles77702f12020-12-17 14:38:56 -0500213class CountReturnsWithLimit : public ProgramVisitor {
214public:
215 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
216 this->visitProgramElement(funcDef);
217 }
218
219 bool visitStatement(const Statement& stmt) override {
220 switch (stmt.kind()) {
221 case Statement::Kind::kReturn: {
222 ++fNumReturns;
223 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
224 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
225 }
John Stilesc5ff4862020-12-22 13:47:05 -0500226 case Statement::Kind::kVarDeclaration: {
227 if (fScopedBlockDepth > 1) {
228 fVariablesInBlocks = true;
229 }
230 return INHERITED::visitStatement(stmt);
231 }
John Stiles77702f12020-12-17 14:38:56 -0500232 case Statement::Kind::kBlock: {
233 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
234 fScopedBlockDepth += depthIncrement;
235 bool result = INHERITED::visitStatement(stmt);
236 fScopedBlockDepth -= depthIncrement;
John Stilesc5ff4862020-12-22 13:47:05 -0500237 if (fNumReturns == 0 && fScopedBlockDepth <= 1) {
238 // If closing this block puts us back at the top level, and we haven't
239 // encountered any return statements yet, any vardecls we may have encountered
240 // up until this point can be ignored. They are out of scope now, and they were
241 // never used in a return statement.
242 fVariablesInBlocks = false;
243 }
John Stiles77702f12020-12-17 14:38:56 -0500244 return result;
245 }
246 default:
247 return INHERITED::visitStatement(stmt);
248 }
249 }
250
251 int fNumReturns = 0;
252 int fDeepestReturn = 0;
253 int fLimit = 0;
254 int fScopedBlockDepth = 0;
John Stilesc5ff4862020-12-22 13:47:05 -0500255 bool fVariablesInBlocks = false;
John Stiles77702f12020-12-17 14:38:56 -0500256 using INHERITED = ProgramVisitor;
257};
258
John Stiles44e96be2020-08-31 13:16:04 -0400259} // namespace
260
John Stiles77702f12020-12-17 14:38:56 -0500261Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
262 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
263 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
John Stiles77702f12020-12-17 14:38:56 -0500264 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
265 return ReturnComplexity::kEarlyReturns;
266 }
John Stilesc5ff4862020-12-22 13:47:05 -0500267 if (counter.fNumReturns > 1) {
John Stiles77702f12020-12-17 14:38:56 -0500268 return ReturnComplexity::kScopedReturns;
269 }
John Stilesc5ff4862020-12-22 13:47:05 -0500270 if (counter.fVariablesInBlocks && counter.fDeepestReturn > 1) {
271 return ReturnComplexity::kScopedReturns;
272 }
273 return ReturnComplexity::kSingleSafeReturn;
John Stiles77702f12020-12-17 14:38:56 -0500274}
275
John Stilesb61ee902020-09-21 12:26:59 -0400276void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
277 // No changes necessary if this statement isn't actually a block.
278 if (!inlinedBody || !inlinedBody->is<Block>()) {
279 return;
280 }
281
282 // No changes necessary if the parent statement doesn't require a scope.
283 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500284 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400285 return;
286 }
287
288 Block& block = inlinedBody->as<Block>();
289
290 // The inliner will create inlined function bodies as a Block containing multiple statements,
291 // but no scope. Normally, this is fine, but if this block is used as the statement for a
292 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
293 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
294 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
295 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
296 // absorbing the following statement into our loop--so we also add a scope to these.
297 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400298 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400299 // We found an explicit scope; all is well.
300 return;
301 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400302 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400303 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
304 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400305 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400306 return;
307 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400308 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400309 // This block has exactly one thing inside, and it's not another block. No need to scope
310 // it.
311 return;
312 }
313 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400314 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400315 }
316}
317
Brian Osman0006ad02020-11-18 15:38:39 -0500318void Inliner::reset(ModifiersPool* modifiers, const Program::Settings* settings) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400319 fModifiers = modifiers;
320 fSettings = settings;
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500321 fMangler.reset();
John Stiles031a7672020-11-13 16:13:18 -0500322 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400323}
324
325std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
326 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500327 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400328 const Expression& expression) {
329 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
330 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500331 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400332 }
333 return nullptr;
334 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400335 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
336 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400337 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400338 for (const std::unique_ptr<Expression>& arg : originalArgs) {
339 args.push_back(expr(arg));
340 }
341 return args;
342 };
343
Ethan Nicholase6592142020-09-08 10:22:09 -0400344 switch (expression.kind()) {
345 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400346 const BinaryExpression& b = expression.as<BinaryExpression>();
347 return std::make_unique<BinaryExpression>(offset,
John Stiles2d4f9592020-10-30 10:29:12 -0400348 expr(b.left()),
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400349 b.getOperator(),
John Stiles2d4f9592020-10-30 10:29:12 -0400350 expr(b.right()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400351 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400352 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400353 case Expression::Kind::kBoolLiteral:
354 case Expression::Kind::kIntLiteral:
355 case Expression::Kind::kFloatLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400356 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400357 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400358 const Constructor& constructor = expression.as<Constructor>();
John Stilesd7cc0932020-11-30 12:24:27 -0500359 const Type* type = copy_if_needed(&constructor.type(), *symbolTableForExpression);
360 return std::make_unique<Constructor>(offset, type, argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400361 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400362 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400363 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400364 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400365 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400366 }
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500367 case Expression::Kind::kExternalFunctionReference:
John Stiles44e96be2020-08-31 13:16:04 -0400368 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400369 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400370 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400371 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400372 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400373 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400374 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400375 return std::make_unique<FunctionCall>(offset, &funcCall.type(), &funcCall.function(),
376 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400377 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400378 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400379 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400380 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400381 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400382 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
383 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400384 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400385 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400386 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400387 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400388 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400389 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400390 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400391 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400392 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400393 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400394 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400395 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400396 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400397 return std::make_unique<Swizzle>(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400398 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400399 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400400 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400401 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
402 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400403 }
Brian Osman83ba9302020-09-11 13:33:46 -0400404 case Expression::Kind::kTypeReference:
405 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400406 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400407 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400408 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400409 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400410 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400411 }
412 return v.clone();
413 }
414 default:
415 SkASSERT(false);
416 return nullptr;
417 }
418}
419
420std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
421 VariableRewriteMap* varMap,
422 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500423 std::unique_ptr<Expression>* resultExpr,
424 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400425 const Statement& statement,
426 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400427 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
428 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400429 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500430 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400431 }
432 return nullptr;
433 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400434 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400435 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400436 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400437 for (const std::unique_ptr<Statement>& child : block.children()) {
438 result.push_back(stmt(child));
439 }
440 return result;
441 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400442 auto stmts = [&](const StatementArray& ss) {
443 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400444 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400445 for (const auto& s : ss) {
446 result.push_back(stmt(s));
447 }
448 return result;
449 };
450 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
451 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500452 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400453 }
454 return nullptr;
455 };
John Stiles031a7672020-11-13 16:13:18 -0500456
457 ++fInlinedStatementCounter;
458
Ethan Nicholase6592142020-09-08 10:22:09 -0400459 switch (statement.kind()) {
460 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400461 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400462 return std::make_unique<Block>(offset, blockStmts(b),
463 SymbolTable::WrapIfBuiltin(b.symbolTable()),
464 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400465 }
466
Ethan Nicholase6592142020-09-08 10:22:09 -0400467 case Statement::Kind::kBreak:
468 case Statement::Kind::kContinue:
469 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400470 return statement.clone();
471
Ethan Nicholase6592142020-09-08 10:22:09 -0400472 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400473 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400474 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400475 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400476 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400477 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400478 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400479 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400480 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400481 const ForStatement& f = statement.as<ForStatement>();
482 // need to ensure initializer is evaluated first so that we've already remapped its
483 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400484 std::unique_ptr<Statement> initializer = stmt(f.initializer());
485 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400486 expr(f.next()), stmt(f.statement()),
487 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400488 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400489 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400490 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400491 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
492 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400493 }
John Stiles98c1f822020-09-09 14:18:53 -0400494 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400495 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400496 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400497 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400498 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500499 if (!r.expression()) {
500 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
501 // This function doesn't return a value, but has early returns, so we've wrapped
502 // it in a for loop. Use a continue to jump to the end of the loop and "leave"
503 // the function.
John Stiles7b920442020-12-17 10:43:41 -0500504 return std::make_unique<ContinueStatement>(offset);
John Stiles44e96be2020-08-31 13:16:04 -0400505 } else {
John Stiles77702f12020-12-17 14:38:56 -0500506 // This function doesn't exit early or return a value. A return statement at the
507 // end is a no-op and can be treated as such.
John Stiles44e96be2020-08-31 13:16:04 -0400508 return std::make_unique<Nop>();
509 }
510 }
John Stiles77702f12020-12-17 14:38:56 -0500511
John Stilesc5ff4862020-12-22 13:47:05 -0500512 // If a function only contains a single return, and it doesn't reference variables from
513 // inside an Block's scope, we don't need to store the result in a variable at all. Just
514 // replace the function-call expression with the function's return expression.
John Stiles77702f12020-12-17 14:38:56 -0500515 SkASSERT(resultExpr);
516 SkASSERT(*resultExpr);
John Stilesc5ff4862020-12-22 13:47:05 -0500517 if (returnComplexity <= ReturnComplexity::kSingleSafeReturn) {
John Stiles77702f12020-12-17 14:38:56 -0500518 *resultExpr = expr(r.expression());
519 return std::make_unique<Nop>();
520 }
521
522 // For more complex functions, assign their result into a variable.
523 auto assignment =
524 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
525 offset,
526 clone_with_ref_kind(**resultExpr, VariableReference::RefKind::kWrite),
527 Token::Kind::TK_EQ,
528 expr(r.expression()),
529 &resultExpr->get()->type()));
530
531 // Early returns are wrapped in a for loop; we need to synthesize a continue statement
532 // to "leave" the function.
533 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
534 StatementArray block;
535 block.reserve_back(2);
536 block.push_back(std::move(assignment));
537 block.push_back(std::make_unique<ContinueStatement>(offset));
538 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
539 /*isScope=*/true);
540 }
541 // Functions without early returns aren't wrapped in a for loop and don't need to worry
542 // about breaking out of the control flow.
543 return std::move(assignment);
544
John Stiles44e96be2020-08-31 13:16:04 -0400545 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400546 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400547 const SwitchStatement& ss = statement.as<SwitchStatement>();
548 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400549 cases.reserve(ss.cases().size());
550 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
551 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
552 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400553 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400554 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400555 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400556 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400557 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400558 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400559 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000560 std::unique_ptr<Expression> initialValue = expr(decl.value());
561 int arraySize = decl.arraySize();
562 const Variable& old = decl.var();
563 // We assign unique names to inlined variables--scopes hide most of the problems in this
564 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
565 // names are important.
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500566 auto name = std::make_unique<String>(fMangler.uniqueName(String(old.name()),
567 symbolTableForStatement));
John Stiles35fee4c2020-12-16 18:25:14 +0000568 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
569 const Type* baseTypePtr = copy_if_needed(&decl.baseType(), *symbolTableForStatement);
570 const Type* typePtr = copy_if_needed(&old.type(), *symbolTableForStatement);
571 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
572 std::make_unique<Variable>(offset,
573 &old.modifiers(),
574 namePtr->c_str(),
575 typePtr,
576 isBuiltinCode,
577 old.storage(),
578 initialValue.get()));
579 (*varMap)[&old] = std::make_unique<VariableReference>(offset, clone);
580 return std::make_unique<VarDeclaration>(clone, baseTypePtr, arraySize,
581 std::move(initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400582 }
John Stiles44e96be2020-08-31 13:16:04 -0400583 default:
584 SkASSERT(false);
585 return nullptr;
586 }
587}
588
John Stiles7b920442020-12-17 10:43:41 -0500589Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
590 const Type* type,
591 SymbolTable* symbolTable,
592 Modifiers modifiers,
593 bool isBuiltinCode,
594 std::unique_ptr<Expression>* initialValue) {
595 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
596 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
597 // somewhere during compilation.
John Stiles54e7c052021-01-11 14:22:36 -0500598 if (type == fContext->fTypes.fFloatLiteral.get()) {
John Stiles7b920442020-12-17 10:43:41 -0500599 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stiles54e7c052021-01-11 14:22:36 -0500600 type = fContext->fTypes.fFloat.get();
601 } else if (type == fContext->fTypes.fIntLiteral.get()) {
John Stiles7b920442020-12-17 10:43:41 -0500602 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stiles54e7c052021-01-11 14:22:36 -0500603 type = fContext->fTypes.fInt.get();
John Stiles7b920442020-12-17 10:43:41 -0500604 }
605
606 // Provide our new variable with a unique name, and add it to our symbol table.
607 const String* namePtr = symbolTable->takeOwnershipOfString(
Ethan Nicholas6f4eee22021-01-11 12:37:42 -0500608 std::make_unique<String>(fMangler.uniqueName(baseName, symbolTable)));
John Stiles7b920442020-12-17 10:43:41 -0500609 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
610
611 // Create our new variable and add it to the symbol table.
612 InlineVariable result;
613 result.fVarSymbol =
614 symbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
615 fModifiers->addToPool(Modifiers()),
616 nameFrag,
617 type,
618 isBuiltinCode,
619 Variable::Storage::kLocal,
620 initialValue->get()));
621
622 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
623 // initial value).
624 if (*initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
625 result.fVarDecl = std::make_unique<VarDeclaration>(result.fVarSymbol, type, /*arraySize=*/0,
626 (*initialValue)->clone());
627 } else {
628 result.fVarDecl = std::make_unique<VarDeclaration>(result.fVarSymbol, type, /*arraySize=*/0,
629 std::move(*initialValue));
630 }
631 return result;
632}
633
John Stiles6eadf132020-09-08 10:16:10 -0400634Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500635 std::shared_ptr<SymbolTable> symbolTable,
Brian Osman3887a012020-09-30 13:22:27 -0400636 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400637 // Inlining is more complicated here than in a typical compiler, because we have to have a
638 // high-level IR and can't just drop statements into the middle of an expression or even use
639 // gotos.
640 //
641 // Since we can't insert statements into an expression, we run the inline function as extra
642 // statements before the statement we're currently processing, relying on a lack of execution
643 // order guarantees. Since we can't use gotos (which are normally used to replace return
644 // statements), we wrap the whole function in a loop and use break statements to jump to the
645 // end.
646 SkASSERT(fSettings);
647 SkASSERT(fContext);
648 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400649 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400650
John Stiles8e3b6be2020-10-13 11:14:08 -0400651 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400652 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400653 const FunctionDefinition& function = *call->function().definition();
John Stiles77702f12020-12-17 14:38:56 -0500654 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
655 bool hasEarlyReturn = (returnComplexity >= ReturnComplexity::kEarlyReturns);
John Stiles6eadf132020-09-08 10:16:10 -0400656
John Stiles44e96be2020-08-31 13:16:04 -0400657 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400658 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400659 /*symbols=*/nullptr,
660 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400661
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400662 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400663 inlinedBody.children().reserve_back(
664 1 + // Inline marker
665 1 + // Result variable
666 arguments.size() + // Function arguments (passing in)
667 arguments.size() + // Function arguments (copy out-params back)
John Stiles7b920442020-12-17 10:43:41 -0500668 1); // Block for inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400669
Ethan Nicholasceb62142020-10-09 16:51:18 -0400670 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400671
John Stiles44e96be2020-08-31 13:16:04 -0400672 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400673 std::unique_ptr<Expression> resultExpr;
John Stiles54e7c052021-01-11 14:22:36 -0500674 if (function.declaration().returnType() != *fContext->fTypes.fVoid) {
John Stiles44e96be2020-08-31 13:16:04 -0400675 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500676 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
677 &function.declaration().returnType(),
678 symbolTable.get(), Modifiers{},
679 caller->isBuiltin(), &noInitialValue);
680 inlinedBody.children().push_back(std::move(var.fVarDecl));
681 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles35fee4c2020-12-16 18:25:14 +0000682 }
John Stiles44e96be2020-08-31 13:16:04 -0400683
684 // Create variables in the extra statements to hold the arguments, and assign the arguments to
685 // them.
686 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400687 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400688 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400689 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400690 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400691
John Stiles44733aa2020-09-29 17:42:23 -0400692 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500693 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400694 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400695 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400696 // ... we don't need to copy it at all! We can just use the existing expression.
697 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400698 continue;
699 }
700 }
John Stilese41b4ee2020-09-28 12:28:16 -0400701 if (isOutParam) {
702 argsToCopyBack.push_back(i);
703 }
John Stiles7b920442020-12-17 10:43:41 -0500704 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
705 symbolTable.get(), param->modifiers(),
706 caller->isBuiltin(), &arguments[i]);
707 inlinedBody.children().push_back(std::move(var.fVarDecl));
708 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400709 }
710
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400711 const Block& body = function.body()->as<Block>();
John Stiles7b920442020-12-17 10:43:41 -0500712 StatementArray* inlineStatements;
713
John Stiles44e96be2020-08-31 13:16:04 -0400714 if (hasEarlyReturn) {
715 // Since we output to backends that don't have a goto statement (which would normally be
John Stiles7b920442020-12-17 10:43:41 -0500716 // used to perform an early return), we fake it by wrapping the function in a single-
717 // iteration for loop, and use a continue statement to jump to the end of the loop
718 // prematurely.
719
720 // int _1_loop = 0;
721 symbolTable = std::make_shared<SymbolTable>(std::move(symbolTable), caller->isBuiltin());
John Stiles54e7c052021-01-11 14:22:36 -0500722 const Type* intType = fContext->fTypes.fInt.get();
John Stiles7b920442020-12-17 10:43:41 -0500723 std::unique_ptr<Expression> initialValue = std::make_unique<IntLiteral>(/*offset=*/-1,
724 /*value=*/0,
725 intType);
726 InlineVariable loopVar = this->makeInlineVariable("loop", intType, symbolTable.get(),
727 Modifiers{}, caller->isBuiltin(),
728 &initialValue);
729
730 // _1_loop < 1;
731 std::unique_ptr<Expression> test = std::make_unique<BinaryExpression>(
John Stiles44e96be2020-08-31 13:16:04 -0400732 /*offset=*/-1,
John Stiles7b920442020-12-17 10:43:41 -0500733 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol),
734 Token::Kind::TK_LT,
735 std::make_unique<IntLiteral>(/*offset=*/-1, /*value=*/1, intType),
John Stiles54e7c052021-01-11 14:22:36 -0500736 fContext->fTypes.fBool.get());
John Stiles7b920442020-12-17 10:43:41 -0500737
738 // _1_loop++
739 std::unique_ptr<Expression> increment = std::make_unique<PostfixExpression>(
740 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol,
741 VariableReference::RefKind::kReadWrite),
742 Token::Kind::TK_PLUSPLUS);
743
744 // {...}
745 auto innerBlock = std::make_unique<Block>(offset, StatementArray{},
746 /*symbols=*/nullptr, /*isScope=*/true);
747 inlineStatements = &innerBlock->children();
748
749 // for (int _1_loop = 0; _1_loop < 1; _1_loop++) {...}
750 inlinedBody.children().push_back(std::make_unique<ForStatement>(/*offset=*/-1,
751 std::move(loopVar.fVarDecl),
752 std::move(test),
753 std::move(increment),
754 std::move(innerBlock),
755 symbolTable));
John Stiles44e96be2020-08-31 13:16:04 -0400756 } else {
John Stilesfa9a0832020-12-17 10:43:58 -0500757 // No early returns, so we can just dump the code into our existing scopeless block.
758 inlineStatements = &inlinedBody.children();
John Stiles7b920442020-12-17 10:43:41 -0500759 }
760
761 inlineStatements->reserve_back(body.children().size() + argsToCopyBack.size());
762 for (const std::unique_ptr<Statement>& stmt : body.children()) {
763 inlineStatements->push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles77702f12020-12-17 14:38:56 -0500764 &resultExpr, returnComplexity, *stmt,
John Stiles7b920442020-12-17 10:43:41 -0500765 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400766 }
767
John Stilese41b4ee2020-09-28 12:28:16 -0400768 // Copy back the values of `out` parameters into their real destinations.
769 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400770 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400771 SkASSERT(varMap.find(p) != varMap.end());
John Stiles7b920442020-12-17 10:43:41 -0500772 inlineStatements->push_back(
John Stilese41b4ee2020-09-28 12:28:16 -0400773 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
774 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400775 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400776 Token::Kind::TK_EQ,
777 std::move(varMap[p]),
778 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400779 }
780
John Stilese41b4ee2020-09-28 12:28:16 -0400781 if (resultExpr != nullptr) {
782 // Return our result variable as our replacement expression.
John Stilese41b4ee2020-09-28 12:28:16 -0400783 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400784 } else {
785 // It's a void function, so it doesn't actually result in anything, but we have to return
786 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400787 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
788 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400789 /*value=*/false);
790 }
791
John Stiles44e96be2020-08-31 13:16:04 -0400792 return inlinedCall;
793}
794
John Stiles2d7973a2020-10-02 15:01:03 -0400795bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400796 SkASSERT(fSettings);
797
John Stiles1c03d332020-10-13 10:30:23 -0400798 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
799 if (fSettings->fInlineThreshold <= 0) {
800 return false;
801 }
802
John Stiles031a7672020-11-13 16:13:18 -0500803 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
804 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
805 return false;
806 }
807
John Stiles2d7973a2020-10-02 15:01:03 -0400808 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400809 // Can't inline something if we don't actually have its definition.
810 return false;
811 }
John Stiles2d7973a2020-10-02 15:01:03 -0400812
John Stiles74ebd7e2020-12-17 14:41:50 -0500813 // We don't have any mechanism to simulate early returns within a construct that supports
814 // continues (for/do/while), so we can't inline if there's a return inside one.
815 bool hasReturnInContinuableConstruct =
816 (count_returns_in_continuable_constructs(*functionDef) > 0);
817 return !hasReturnInContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400818}
819
John Stiles2d7973a2020-10-02 15:01:03 -0400820// A candidate function for inlining, containing everything that `inlineCall` needs.
821struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500822 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400823 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
824 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
825 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
826 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400827};
John Stiles93442622020-09-11 12:11:27 -0400828
John Stiles2d7973a2020-10-02 15:01:03 -0400829struct InlineCandidateList {
830 std::vector<InlineCandidate> fCandidates;
831};
832
833class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400834public:
835 // A list of all the inlining candidates we found during analysis.
836 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400837
John Stiles70957c82020-10-02 16:42:10 -0400838 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
839 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500840 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400841 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
842 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
843 // inliner might replace a statement with a block containing the statement.
844 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
845 // The function that we're currently processing (i.e. inlining into).
846 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400847
Brian Osman0006ad02020-11-18 15:38:39 -0500848 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500849 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500850 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400851 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500852 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400853
Brian Osman0006ad02020-11-18 15:38:39 -0500854 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400855 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400856 }
857
John Stiles70957c82020-10-02 16:42:10 -0400858 fSymbolTableStack.pop_back();
859 fCandidateList = nullptr;
860 }
861
862 void visitProgramElement(ProgramElement* pe) {
863 switch (pe->kind()) {
864 case ProgramElement::Kind::kFunction: {
865 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500866 fEnclosingFunction = &funcDef;
867 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400868 break;
John Stiles93442622020-09-11 12:11:27 -0400869 }
John Stiles70957c82020-10-02 16:42:10 -0400870 default:
871 // The inliner can't operate outside of a function's scope.
872 break;
873 }
874 }
875
876 void visitStatement(std::unique_ptr<Statement>* stmt,
877 bool isViableAsEnclosingStatement = true) {
878 if (!*stmt) {
879 return;
John Stiles93442622020-09-11 12:11:27 -0400880 }
881
John Stiles70957c82020-10-02 16:42:10 -0400882 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
883 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400884
John Stiles70957c82020-10-02 16:42:10 -0400885 if (isViableAsEnclosingStatement) {
886 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400887 }
888
John Stiles70957c82020-10-02 16:42:10 -0400889 switch ((*stmt)->kind()) {
890 case Statement::Kind::kBreak:
891 case Statement::Kind::kContinue:
892 case Statement::Kind::kDiscard:
893 case Statement::Kind::kInlineMarker:
894 case Statement::Kind::kNop:
895 break;
896
897 case Statement::Kind::kBlock: {
898 Block& block = (*stmt)->as<Block>();
899 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500900 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400901 }
902
903 for (std::unique_ptr<Statement>& stmt : block.children()) {
904 this->visitStatement(&stmt);
905 }
906 break;
John Stiles93442622020-09-11 12:11:27 -0400907 }
John Stiles70957c82020-10-02 16:42:10 -0400908 case Statement::Kind::kDo: {
909 DoStatement& doStmt = (*stmt)->as<DoStatement>();
910 // The loop body is a candidate for inlining.
911 this->visitStatement(&doStmt.statement());
912 // The inliner isn't smart enough to inline the test-expression for a do-while
913 // loop at this time. There are two limitations:
914 // - We would need to insert the inlined-body block at the very end of the do-
915 // statement's inner fStatement. We don't support that today, but it's doable.
916 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
917 // would skip over the inlined block that evaluates the test expression. There
918 // isn't a good fix for this--any workaround would be more complex than the cost
919 // of a function call. However, loops that don't use `continue` would still be
920 // viable candidates for inlining.
921 break;
John Stiles93442622020-09-11 12:11:27 -0400922 }
John Stiles70957c82020-10-02 16:42:10 -0400923 case Statement::Kind::kExpression: {
924 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
925 this->visitExpression(&expr.expression());
926 break;
927 }
928 case Statement::Kind::kFor: {
929 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400930 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500931 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400932 }
933
934 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400935 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400936 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400937 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400938
939 // The inliner isn't smart enough to inline the test- or increment-expressions
940 // of a for loop loop at this time. There are a handful of limitations:
941 // - We would need to insert the test-expression block at the very beginning of the
942 // for-loop's inner fStatement, and the increment-expression block at the very
943 // end. We don't support that today, but it's doable.
944 // - The for-loop's built-in test-expression would need to be dropped entirely,
945 // and the loop would be halted via a break statement at the end of the inlined
946 // test-expression. This is again something we don't support today, but it could
947 // be implemented.
948 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
949 // that would skip over the inlined block that evaluates the increment expression.
950 // There isn't a good fix for this--any workaround would be more complex than the
951 // cost of a function call. However, loops that don't use `continue` would still
952 // be viable candidates for increment-expression inlining.
953 break;
954 }
955 case Statement::Kind::kIf: {
956 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400957 this->visitExpression(&ifStmt.test());
958 this->visitStatement(&ifStmt.ifTrue());
959 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400960 break;
961 }
962 case Statement::Kind::kReturn: {
963 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400964 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400965 break;
966 }
967 case Statement::Kind::kSwitch: {
968 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400969 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500970 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400971 }
972
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400973 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400974 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400975 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400976 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -0400977 this->visitStatement(&caseBlock);
978 }
979 }
980 break;
981 }
982 case Statement::Kind::kVarDeclaration: {
983 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
984 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400985 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400986 break;
987 }
John Stiles70957c82020-10-02 16:42:10 -0400988 default:
989 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400990 }
991
John Stiles70957c82020-10-02 16:42:10 -0400992 // Pop our symbol and enclosing-statement stacks.
993 fSymbolTableStack.resize(oldSymbolStackSize);
994 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
995 }
996
997 void visitExpression(std::unique_ptr<Expression>* expr) {
998 if (!*expr) {
999 return;
John Stiles93442622020-09-11 12:11:27 -04001000 }
John Stiles70957c82020-10-02 16:42:10 -04001001
1002 switch ((*expr)->kind()) {
1003 case Expression::Kind::kBoolLiteral:
1004 case Expression::Kind::kDefined:
Brian Osmanbe0b3b72021-01-06 14:27:35 -05001005 case Expression::Kind::kExternalFunctionReference:
John Stiles70957c82020-10-02 16:42:10 -04001006 case Expression::Kind::kFieldAccess:
1007 case Expression::Kind::kFloatLiteral:
1008 case Expression::Kind::kFunctionReference:
1009 case Expression::Kind::kIntLiteral:
John Stiles70957c82020-10-02 16:42:10 -04001010 case Expression::Kind::kSetting:
1011 case Expression::Kind::kTypeReference:
1012 case Expression::Kind::kVariableReference:
1013 // Nothing to scan here.
1014 break;
1015
1016 case Expression::Kind::kBinary: {
1017 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001018 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -04001019
1020 // Logical-and and logical-or binary expressions do not inline the right side,
1021 // because that would invalidate short-circuiting. That is, when evaluating
1022 // expressions like these:
1023 // (false && x()) // always false
1024 // (true || y()) // always true
1025 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1026 // enforce that rule is to avoid inlining the right side entirely. However, it is
1027 // safe for other types of binary expression to inline both sides.
1028 Token::Kind op = binaryExpr.getOperator();
1029 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1030 op == Token::Kind::TK_LOGICALOR);
1031 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001032 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001033 }
1034 break;
1035 }
1036 case Expression::Kind::kConstructor: {
1037 Constructor& constructorExpr = (*expr)->as<Constructor>();
1038 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1039 this->visitExpression(&arg);
1040 }
1041 break;
1042 }
1043 case Expression::Kind::kExternalFunctionCall: {
1044 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1045 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1046 this->visitExpression(&arg);
1047 }
1048 break;
1049 }
1050 case Expression::Kind::kFunctionCall: {
1051 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001052 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001053 this->visitExpression(&arg);
1054 }
1055 this->addInlineCandidate(expr);
1056 break;
1057 }
1058 case Expression::Kind::kIndex:{
1059 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001060 this->visitExpression(&indexExpr.base());
1061 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001062 break;
1063 }
1064 case Expression::Kind::kPostfix: {
1065 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001066 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001067 break;
1068 }
1069 case Expression::Kind::kPrefix: {
1070 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001071 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001072 break;
1073 }
1074 case Expression::Kind::kSwizzle: {
1075 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001076 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001077 break;
1078 }
1079 case Expression::Kind::kTernary: {
1080 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1081 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001082 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001083 // The true- and false-expressions cannot be inlined, because we are only allowed to
1084 // evaluate one side.
1085 break;
1086 }
1087 default:
1088 SkUNREACHABLE;
1089 }
1090 }
1091
1092 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1093 fCandidateList->fCandidates.push_back(
1094 InlineCandidate{fSymbolTableStack.back(),
1095 find_parent_statement(fEnclosingStmtStack),
1096 fEnclosingStmtStack.back(),
1097 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001098 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001099 }
John Stiles2d7973a2020-10-02 15:01:03 -04001100};
John Stiles93442622020-09-11 12:11:27 -04001101
John Stiles9b9415e2020-11-23 14:48:06 -05001102static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1103 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1104}
John Stiles915a38c2020-09-14 09:38:13 -04001105
John Stiles9b9415e2020-11-23 14:48:06 -05001106bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1107 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001108 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001109 if (wasInserted) {
1110 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001111 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1112 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001113 }
1114
John Stiles2d7973a2020-10-02 15:01:03 -04001115 return iter->second;
1116}
1117
John Stiles9b9415e2020-11-23 14:48:06 -05001118int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1119 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001120 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001121 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
1122 fSettings->fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001123 }
John Stiles2d7973a2020-10-02 15:01:03 -04001124 return iter->second;
1125}
1126
Brian Osman0006ad02020-11-18 15:38:39 -05001127void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001128 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001129 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001130 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1131 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1132 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1133 // `const T&`.
1134 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001135 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001136
John Stiles0ad233f2020-11-25 11:02:05 -05001137 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001138 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001139 if (candidates.empty()) {
1140 return;
1141 }
1142
1143 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001144 InlinabilityCache cache;
1145 candidates.erase(std::remove_if(candidates.begin(),
1146 candidates.end(),
1147 [&](const InlineCandidate& candidate) {
1148 return !this->candidateCanBeInlined(candidate, &cache);
1149 }),
1150 candidates.end());
1151
John Stiles0ad233f2020-11-25 11:02:05 -05001152 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1153 // complete.
1154 if (fSettings->fInlineThreshold == INT_MAX || candidates.empty()) {
1155 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001156 }
John Stiles0ad233f2020-11-25 11:02:05 -05001157
1158 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1159 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1160 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1161 FunctionSizeCache functionSizeCache;
1162 FunctionSizeCache candidateTotalCost;
1163 for (InlineCandidate& candidate : candidates) {
1164 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1165 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1166 }
1167
1168 candidates.erase(
1169 std::remove_if(candidates.begin(),
1170 candidates.end(),
1171 [&](const InlineCandidate& candidate) {
1172 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1173 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1174 // Functions marked `inline` ignore size limitations.
1175 return false;
1176 }
1177 if (usage->get(fnDecl) == 1) {
1178 // If a function is only used once, it's cost-free to inline.
1179 return false;
1180 }
1181 if (candidateTotalCost[&fnDecl] <= fSettings->fInlineThreshold) {
1182 // We won't exceed the inline threshold by inlining this.
1183 return false;
1184 }
1185 // Inlining this function will add too many IRNodes.
1186 return true;
1187 }),
1188 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001189}
1190
Brian Osman0006ad02020-11-18 15:38:39 -05001191bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001192 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001193 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001194 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1195 if (fSettings->fInlineThreshold <= 0) {
1196 return false;
1197 }
1198
John Stiles031a7672020-11-13 16:13:18 -05001199 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1200 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1201 return false;
1202 }
1203
John Stiles2d7973a2020-10-02 15:01:03 -04001204 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001205 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001206
John Stiles915a38c2020-09-14 09:38:13 -04001207 // Inline the candidates where we've determined that it's safe to do so.
1208 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1209 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001210 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001211 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001212
1213 // Inlining two expressions using the same enclosing statement in the same inlining pass
1214 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1215 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1216 if (!inserted) {
1217 continue;
1218 }
1219
1220 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001221 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001222 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001223 if (inlinedCall.fInlinedBody) {
1224 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001225 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001226
Brian Osman010ce6a2020-10-19 16:34:10 -04001227 // Add references within the inlined body
1228 usage->add(inlinedCall.fInlinedBody.get());
1229
John Stiles915a38c2020-09-14 09:38:13 -04001230 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1231 // function, then replace the enclosing statement with that Block.
1232 // Before:
1233 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1234 // fEnclosingStmt = stmt4
1235 // After:
1236 // fInlinedBody = null
1237 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001238 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001239 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1240 }
1241
1242 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001243 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001244 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1245 madeChanges = true;
1246
John Stiles031a7672020-11-13 16:13:18 -05001247 // Stop inlining if we've reached our hard cap on new statements.
1248 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1249 break;
1250 }
1251
John Stiles915a38c2020-09-14 09:38:13 -04001252 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1253 // remain valid.
1254 }
1255
1256 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001257}
1258
John Stiles44e96be2020-08-31 13:16:04 -04001259} // namespace SkSL