blob: f6c546518d6b4458e725a9112b436ceda309abd4 [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"
25#include "src/sksl/ir/SkSLExternalValueReference.h"
26#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"
41#include "src/sksl/ir/SkSLNullLiteral.h"
42#include "src/sksl/ir/SkSLPostfixExpression.h"
43#include "src/sksl/ir/SkSLPrefixExpression.h"
44#include "src/sksl/ir/SkSLReturnStatement.h"
45#include "src/sksl/ir/SkSLSetting.h"
46#include "src/sksl/ir/SkSLSwitchCase.h"
47#include "src/sksl/ir/SkSLSwitchStatement.h"
48#include "src/sksl/ir/SkSLSwizzle.h"
49#include "src/sksl/ir/SkSLTernaryExpression.h"
50#include "src/sksl/ir/SkSLUnresolvedFunction.h"
51#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stiles44e96be2020-08-31 13:16:04 -040052#include "src/sksl/ir/SkSLVariable.h"
53#include "src/sksl/ir/SkSLVariableReference.h"
John Stiles44e96be2020-08-31 13:16:04 -040054
55namespace SkSL {
56namespace {
57
John Stiles031a7672020-11-13 16:13:18 -050058static constexpr int kInlinedStatementLimit = 2500;
59
John Stiles44e96be2020-08-31 13:16:04 -040060static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
61 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
62 public:
63 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
64 this->visitProgramElement(funcDef);
65 }
66
67 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040068 switch (stmt.kind()) {
69 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040070 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040071 const auto& block = stmt.as<Block>();
72 return block.children().size() &&
73 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040074 }
Ethan Nicholase6592142020-09-08 10:22:09 -040075 case Statement::Kind::kSwitch:
Ethan Nicholase6592142020-09-08 10:22:09 -040076 case Statement::Kind::kDo:
77 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -040078 // Don't introspect switches or loop structures at all.
79 return false;
80
Ethan Nicholase6592142020-09-08 10:22:09 -040081 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040082 ++fNumReturns;
83 [[fallthrough]];
84
85 default:
John Stiles93442622020-09-11 12:11:27 -040086 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040087 }
88 }
89
90 int fNumReturns = 0;
91 using INHERITED = ProgramVisitor;
92 };
93
94 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
95}
96
John Stiles74ebd7e2020-12-17 14:41:50 -050097static int count_returns_in_continuable_constructs(const FunctionDefinition& funcDef) {
98 class CountReturnsInContinuableConstructs : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040099 public:
John Stiles74ebd7e2020-12-17 14:41:50 -0500100 CountReturnsInContinuableConstructs(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400101 this->visitProgramElement(funcDef);
102 }
103
104 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400105 switch (stmt.kind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400106 case Statement::Kind::kDo:
107 case Statement::Kind::kFor: {
John Stiles74ebd7e2020-12-17 14:41:50 -0500108 ++fInsideContinuableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400109 bool result = INHERITED::visitStatement(stmt);
John Stiles74ebd7e2020-12-17 14:41:50 -0500110 --fInsideContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400111 return result;
112 }
113
Ethan Nicholase6592142020-09-08 10:22:09 -0400114 case Statement::Kind::kReturn:
John Stiles74ebd7e2020-12-17 14:41:50 -0500115 fNumReturns += (fInsideContinuableConstruct > 0) ? 1 : 0;
John Stiles44e96be2020-08-31 13:16:04 -0400116 [[fallthrough]];
117
118 default:
John Stiles93442622020-09-11 12:11:27 -0400119 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400120 }
121 }
122
123 int fNumReturns = 0;
John Stiles74ebd7e2020-12-17 14:41:50 -0500124 int fInsideContinuableConstruct = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400125 using INHERITED = ProgramVisitor;
126 };
127
John Stiles74ebd7e2020-12-17 14:41:50 -0500128 return CountReturnsInContinuableConstructs{funcDef}.fNumReturns;
John Stiles44e96be2020-08-31 13:16:04 -0400129}
130
John Stiles991b09d2020-09-10 13:33:40 -0400131static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
132 class ContainsRecursiveCall : public ProgramVisitor {
133 public:
134 bool visit(const FunctionDeclaration& funcDecl) {
135 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400136 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
137 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400138 }
139
140 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400141 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400142 return true;
143 }
144 return INHERITED::visitExpression(expr);
145 }
146
147 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400148 if (stmt.is<InlineMarker>() &&
149 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400150 return true;
151 }
152 return INHERITED::visitStatement(stmt);
153 }
154
155 const FunctionDeclaration* fFuncDecl;
156 using INHERITED = ProgramVisitor;
157 };
158
159 return ContainsRecursiveCall{}.visit(funcDecl);
160}
161
John Stiles44e96be2020-08-31 13:16:04 -0400162static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
John Stilesc0c51062020-12-03 17:16:29 -0500163 if (src->isArray()) {
John Stiles74ff1d62020-11-30 11:56:16 -0500164 const Type* innerType = copy_if_needed(&src->componentType(), symbolTable);
John Stilesad2d4942020-12-11 16:55:58 -0500165 return symbolTable.takeOwnershipOfSymbol(Type::MakeArrayType(src->name(), *innerType,
166 src->columns()));
John Stiles44e96be2020-08-31 13:16:04 -0400167 }
168 return src;
169}
170
John Stiles6d696082020-10-01 10:18:54 -0400171static std::unique_ptr<Statement>* find_parent_statement(
172 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400173 SkASSERT(!stmtStack.empty());
174
175 // Walk the statement stack from back to front, ignoring the last element (which is the
176 // enclosing statement).
177 auto iter = stmtStack.rbegin();
178 ++iter;
179
180 // Anything counts as a parent statement other than a scopeless Block.
181 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400182 std::unique_ptr<Statement>* stmt = *iter;
183 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400184 return stmt;
185 }
186 }
187
188 // There wasn't any parent statement to be found.
189 return nullptr;
190}
191
John Stilese41b4ee2020-09-28 12:28:16 -0400192std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
193 VariableReference::RefKind refKind) {
194 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400195 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400196 public:
197 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400198 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400199 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400200 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400201 }
202 return INHERITED::visitExpression(expr);
203 }
204
205 private:
206 VariableReference::RefKind fRefKind;
207
John Stiles70b82422020-09-30 10:55:12 -0400208 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400209 };
210
211 SetRefKindInExpression{refKind}.visitExpression(*clone);
212 return clone;
213}
214
John Stiles77702f12020-12-17 14:38:56 -0500215class CountReturnsWithLimit : public ProgramVisitor {
216public:
217 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
218 this->visitProgramElement(funcDef);
219 }
220
221 bool visitStatement(const Statement& stmt) override {
222 switch (stmt.kind()) {
223 case Statement::Kind::kReturn: {
224 ++fNumReturns;
225 fDeepestReturn = std::max(fDeepestReturn, fScopedBlockDepth);
226 return (fNumReturns >= fLimit) || INHERITED::visitStatement(stmt);
227 }
228 case Statement::Kind::kBlock: {
229 int depthIncrement = stmt.as<Block>().isScope() ? 1 : 0;
230 fScopedBlockDepth += depthIncrement;
231 bool result = INHERITED::visitStatement(stmt);
232 fScopedBlockDepth -= depthIncrement;
233 return result;
234 }
235 default:
236 return INHERITED::visitStatement(stmt);
237 }
238 }
239
240 int fNumReturns = 0;
241 int fDeepestReturn = 0;
242 int fLimit = 0;
243 int fScopedBlockDepth = 0;
244 using INHERITED = ProgramVisitor;
245};
246
John Stiles44e96be2020-08-31 13:16:04 -0400247} // namespace
248
John Stiles77702f12020-12-17 14:38:56 -0500249Inliner::ReturnComplexity Inliner::GetReturnComplexity(const FunctionDefinition& funcDef) {
250 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
251 CountReturnsWithLimit counter{funcDef, returnsAtEndOfControlFlow + 1};
252
253 if (counter.fNumReturns > returnsAtEndOfControlFlow) {
254 return ReturnComplexity::kEarlyReturns;
255 }
256 if (counter.fNumReturns > 1 || counter.fDeepestReturn > 1) {
257 return ReturnComplexity::kScopedReturns;
258 }
259 return ReturnComplexity::kSingleTopLevelReturn;
260}
261
John Stilesb61ee902020-09-21 12:26:59 -0400262void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
263 // No changes necessary if this statement isn't actually a block.
264 if (!inlinedBody || !inlinedBody->is<Block>()) {
265 return;
266 }
267
268 // No changes necessary if the parent statement doesn't require a scope.
269 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
Brian Osmand6f23382020-12-15 17:08:59 -0500270 parentStmt->is<DoStatement>())) {
John Stilesb61ee902020-09-21 12:26:59 -0400271 return;
272 }
273
274 Block& block = inlinedBody->as<Block>();
275
276 // The inliner will create inlined function bodies as a Block containing multiple statements,
277 // but no scope. Normally, this is fine, but if this block is used as the statement for a
278 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
279 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
280 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
281 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
282 // absorbing the following statement into our loop--so we also add a scope to these.
283 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400284 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400285 // We found an explicit scope; all is well.
286 return;
287 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400288 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400289 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
290 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400291 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400292 return;
293 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400294 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400295 // This block has exactly one thing inside, and it's not another block. No need to scope
296 // it.
297 return;
298 }
299 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400300 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400301 }
302}
303
Brian Osman0006ad02020-11-18 15:38:39 -0500304void Inliner::reset(ModifiersPool* modifiers, const Program::Settings* settings) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400305 fModifiers = modifiers;
306 fSettings = settings;
John Stiles44e96be2020-08-31 13:16:04 -0400307 fInlineVarCounter = 0;
John Stiles031a7672020-11-13 16:13:18 -0500308 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400309}
310
John Stiles6f31e272020-12-16 13:30:54 -0500311String Inliner::uniqueNameForInlineVar(String baseName, SymbolTable* symbolTable) {
312 // The inliner runs more than once, so the base name might already have a prefix like "_123_x".
313 // Let's strip that prefix off to make the generated code easier to read.
314 if (baseName.startsWith("_")) {
315 // Determine if we have a string of digits.
316 int offset = 1;
317 while (isdigit(baseName[offset])) {
318 ++offset;
319 }
320 // If we found digits, another underscore, and anything else, that's the inliner prefix.
321 // Strip it off.
322 if (offset > 1 && baseName[offset] == '_' && baseName[offset + 1] != '\0') {
323 baseName.erase(0, offset + 1);
324 } else {
325 // This name doesn't contain an inliner prefix, but it does start with an underscore.
326 // OpenGL disallows two consecutive underscores anywhere in the string, and we'll be
327 // adding one as part of the inliner prefix, so strip the leading underscore.
328 baseName.erase(0, 1);
329 }
330 }
John Stilesc75abb82020-09-14 18:24:12 -0400331
332 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
333 // we're not reusing an existing name. (Note that within a single compilation pass, this check
334 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
335 String uniqueName;
336 for (;;) {
John Stiles6f31e272020-12-16 13:30:54 -0500337 uniqueName = String::printf("_%d_%s", fInlineVarCounter++, baseName.c_str());
John Stilesc75abb82020-09-14 18:24:12 -0400338 StringFragment frag{uniqueName.data(), uniqueName.length()};
339 if ((*symbolTable)[frag] == nullptr) {
340 break;
341 }
342 }
343
344 return uniqueName;
345}
346
John Stiles44e96be2020-08-31 13:16:04 -0400347std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
348 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500349 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400350 const Expression& expression) {
351 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
352 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500353 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400354 }
355 return nullptr;
356 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400357 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
358 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400359 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400360 for (const std::unique_ptr<Expression>& arg : originalArgs) {
361 args.push_back(expr(arg));
362 }
363 return args;
364 };
365
Ethan Nicholase6592142020-09-08 10:22:09 -0400366 switch (expression.kind()) {
367 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400368 const BinaryExpression& b = expression.as<BinaryExpression>();
369 return std::make_unique<BinaryExpression>(offset,
John Stiles2d4f9592020-10-30 10:29:12 -0400370 expr(b.left()),
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400371 b.getOperator(),
John Stiles2d4f9592020-10-30 10:29:12 -0400372 expr(b.right()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400373 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400374 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400375 case Expression::Kind::kBoolLiteral:
376 case Expression::Kind::kIntLiteral:
377 case Expression::Kind::kFloatLiteral:
378 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400379 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400380 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400381 const Constructor& constructor = expression.as<Constructor>();
John Stilesd7cc0932020-11-30 12:24:27 -0500382 const Type* type = copy_if_needed(&constructor.type(), *symbolTableForExpression);
383 return std::make_unique<Constructor>(offset, type, argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400384 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400385 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400386 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400387 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400388 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400389 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400390 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400391 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400392 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400393 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400394 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400395 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400396 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400397 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400398 return std::make_unique<FunctionCall>(offset, &funcCall.type(), &funcCall.function(),
399 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400400 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400401 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400402 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400403 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400404 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400405 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
406 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400407 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400408 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400409 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400410 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400411 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400412 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400413 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400414 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400415 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400416 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400417 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400418 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400419 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400420 return std::make_unique<Swizzle>(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400421 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400422 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400423 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400424 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
425 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400426 }
Brian Osman83ba9302020-09-11 13:33:46 -0400427 case Expression::Kind::kTypeReference:
428 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400429 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400430 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400431 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400432 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400433 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400434 }
435 return v.clone();
436 }
437 default:
438 SkASSERT(false);
439 return nullptr;
440 }
441}
442
443std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
444 VariableRewriteMap* varMap,
445 SymbolTable* symbolTableForStatement,
John Stiles77702f12020-12-17 14:38:56 -0500446 std::unique_ptr<Expression>* resultExpr,
447 ReturnComplexity returnComplexity,
Brian Osman3887a012020-09-30 13:22:27 -0400448 const Statement& statement,
449 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400450 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
451 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400452 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles77702f12020-12-17 14:38:56 -0500453 returnComplexity, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400454 }
455 return nullptr;
456 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400457 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400458 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400459 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400460 for (const std::unique_ptr<Statement>& child : block.children()) {
461 result.push_back(stmt(child));
462 }
463 return result;
464 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400465 auto stmts = [&](const StatementArray& ss) {
466 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400467 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400468 for (const auto& s : ss) {
469 result.push_back(stmt(s));
470 }
471 return result;
472 };
473 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
474 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500475 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400476 }
477 return nullptr;
478 };
John Stiles031a7672020-11-13 16:13:18 -0500479
480 ++fInlinedStatementCounter;
481
Ethan Nicholase6592142020-09-08 10:22:09 -0400482 switch (statement.kind()) {
483 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400484 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400485 return std::make_unique<Block>(offset, blockStmts(b),
486 SymbolTable::WrapIfBuiltin(b.symbolTable()),
487 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400488 }
489
Ethan Nicholase6592142020-09-08 10:22:09 -0400490 case Statement::Kind::kBreak:
491 case Statement::Kind::kContinue:
492 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400493 return statement.clone();
494
Ethan Nicholase6592142020-09-08 10:22:09 -0400495 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400496 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400497 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400498 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400499 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400500 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400501 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400502 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400503 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400504 const ForStatement& f = statement.as<ForStatement>();
505 // need to ensure initializer is evaluated first so that we've already remapped its
506 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400507 std::unique_ptr<Statement> initializer = stmt(f.initializer());
508 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400509 expr(f.next()), stmt(f.statement()),
510 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400511 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400512 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400513 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400514 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
515 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400516 }
John Stiles98c1f822020-09-09 14:18:53 -0400517 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400518 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400519 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400520 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400521 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles77702f12020-12-17 14:38:56 -0500522 if (!r.expression()) {
523 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
524 // This function doesn't return a value, but has early returns, so we've wrapped
525 // it in a for loop. Use a continue to jump to the end of the loop and "leave"
526 // the function.
John Stiles7b920442020-12-17 10:43:41 -0500527 return std::make_unique<ContinueStatement>(offset);
John Stiles44e96be2020-08-31 13:16:04 -0400528 } else {
John Stiles77702f12020-12-17 14:38:56 -0500529 // This function doesn't exit early or return a value. A return statement at the
530 // end is a no-op and can be treated as such.
John Stiles44e96be2020-08-31 13:16:04 -0400531 return std::make_unique<Nop>();
532 }
533 }
John Stiles77702f12020-12-17 14:38:56 -0500534
535 // For a function that only contains a single top-level return, we don't need to store
536 // the result in a variable at all. Just move the return value right into the result
537 // expression.
538 SkASSERT(resultExpr);
539 SkASSERT(*resultExpr);
540 if (returnComplexity <= ReturnComplexity::kSingleTopLevelReturn) {
541 *resultExpr = expr(r.expression());
542 return std::make_unique<Nop>();
543 }
544
545 // For more complex functions, assign their result into a variable.
546 auto assignment =
547 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
548 offset,
549 clone_with_ref_kind(**resultExpr, VariableReference::RefKind::kWrite),
550 Token::Kind::TK_EQ,
551 expr(r.expression()),
552 &resultExpr->get()->type()));
553
554 // Early returns are wrapped in a for loop; we need to synthesize a continue statement
555 // to "leave" the function.
556 if (returnComplexity >= ReturnComplexity::kEarlyReturns) {
557 StatementArray block;
558 block.reserve_back(2);
559 block.push_back(std::move(assignment));
560 block.push_back(std::make_unique<ContinueStatement>(offset));
561 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
562 /*isScope=*/true);
563 }
564 // Functions without early returns aren't wrapped in a for loop and don't need to worry
565 // about breaking out of the control flow.
566 return std::move(assignment);
567
John Stiles44e96be2020-08-31 13:16:04 -0400568 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400569 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400570 const SwitchStatement& ss = statement.as<SwitchStatement>();
571 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400572 cases.reserve(ss.cases().size());
573 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
574 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
575 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400576 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400577 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400578 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400579 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400580 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400581 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400582 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000583 std::unique_ptr<Expression> initialValue = expr(decl.value());
584 int arraySize = decl.arraySize();
585 const Variable& old = decl.var();
586 // We assign unique names to inlined variables--scopes hide most of the problems in this
587 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
588 // names are important.
589 auto name = std::make_unique<String>(
590 this->uniqueNameForInlineVar(String(old.name()), symbolTableForStatement));
591 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
592 const Type* baseTypePtr = copy_if_needed(&decl.baseType(), *symbolTableForStatement);
593 const Type* typePtr = copy_if_needed(&old.type(), *symbolTableForStatement);
594 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
595 std::make_unique<Variable>(offset,
596 &old.modifiers(),
597 namePtr->c_str(),
598 typePtr,
599 isBuiltinCode,
600 old.storage(),
601 initialValue.get()));
602 (*varMap)[&old] = std::make_unique<VariableReference>(offset, clone);
603 return std::make_unique<VarDeclaration>(clone, baseTypePtr, arraySize,
604 std::move(initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400605 }
John Stiles44e96be2020-08-31 13:16:04 -0400606 default:
607 SkASSERT(false);
608 return nullptr;
609 }
610}
611
John Stiles7b920442020-12-17 10:43:41 -0500612Inliner::InlineVariable Inliner::makeInlineVariable(const String& baseName,
613 const Type* type,
614 SymbolTable* symbolTable,
615 Modifiers modifiers,
616 bool isBuiltinCode,
617 std::unique_ptr<Expression>* initialValue) {
618 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
619 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
620 // somewhere during compilation.
621 if (type == fContext->fFloatLiteral_Type.get()) {
622 SkDEBUGFAIL("found a $floatLiteral type while inlining");
623 type = fContext->fFloat_Type.get();
624 } else if (type == fContext->fIntLiteral_Type.get()) {
625 SkDEBUGFAIL("found an $intLiteral type while inlining");
626 type = fContext->fInt_Type.get();
627 }
628
629 // Provide our new variable with a unique name, and add it to our symbol table.
630 const String* namePtr = symbolTable->takeOwnershipOfString(
631 std::make_unique<String>(this->uniqueNameForInlineVar(baseName, symbolTable)));
632 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
633
634 // Create our new variable and add it to the symbol table.
635 InlineVariable result;
636 result.fVarSymbol =
637 symbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
638 fModifiers->addToPool(Modifiers()),
639 nameFrag,
640 type,
641 isBuiltinCode,
642 Variable::Storage::kLocal,
643 initialValue->get()));
644
645 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
646 // initial value).
647 if (*initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
648 result.fVarDecl = std::make_unique<VarDeclaration>(result.fVarSymbol, type, /*arraySize=*/0,
649 (*initialValue)->clone());
650 } else {
651 result.fVarDecl = std::make_unique<VarDeclaration>(result.fVarSymbol, type, /*arraySize=*/0,
652 std::move(*initialValue));
653 }
654 return result;
655}
656
John Stiles6eadf132020-09-08 10:16:10 -0400657Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500658 std::shared_ptr<SymbolTable> symbolTable,
Brian Osman3887a012020-09-30 13:22:27 -0400659 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400660 // Inlining is more complicated here than in a typical compiler, because we have to have a
661 // high-level IR and can't just drop statements into the middle of an expression or even use
662 // gotos.
663 //
664 // Since we can't insert statements into an expression, we run the inline function as extra
665 // statements before the statement we're currently processing, relying on a lack of execution
666 // order guarantees. Since we can't use gotos (which are normally used to replace return
667 // statements), we wrap the whole function in a loop and use break statements to jump to the
668 // end.
669 SkASSERT(fSettings);
670 SkASSERT(fContext);
671 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400672 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400673
John Stiles8e3b6be2020-10-13 11:14:08 -0400674 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400675 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400676 const FunctionDefinition& function = *call->function().definition();
John Stiles77702f12020-12-17 14:38:56 -0500677 const ReturnComplexity returnComplexity = GetReturnComplexity(function);
678 bool hasEarlyReturn = (returnComplexity >= ReturnComplexity::kEarlyReturns);
John Stiles6eadf132020-09-08 10:16:10 -0400679
John Stiles44e96be2020-08-31 13:16:04 -0400680 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400681 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400682 /*symbols=*/nullptr,
683 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400684
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400685 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400686 inlinedBody.children().reserve_back(
687 1 + // Inline marker
688 1 + // Result variable
689 arguments.size() + // Function arguments (passing in)
690 arguments.size() + // Function arguments (copy out-params back)
John Stiles7b920442020-12-17 10:43:41 -0500691 1); // Block for inlined code
John Stiles98c1f822020-09-09 14:18:53 -0400692
Ethan Nicholasceb62142020-10-09 16:51:18 -0400693 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400694
John Stiles44e96be2020-08-31 13:16:04 -0400695 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400696 std::unique_ptr<Expression> resultExpr;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400697 if (function.declaration().returnType() != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400698 std::unique_ptr<Expression> noInitialValue;
John Stiles7b920442020-12-17 10:43:41 -0500699 InlineVariable var = this->makeInlineVariable(function.declaration().name(),
700 &function.declaration().returnType(),
701 symbolTable.get(), Modifiers{},
702 caller->isBuiltin(), &noInitialValue);
703 inlinedBody.children().push_back(std::move(var.fVarDecl));
704 resultExpr = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles35fee4c2020-12-16 18:25:14 +0000705 }
John Stiles44e96be2020-08-31 13:16:04 -0400706
707 // Create variables in the extra statements to hold the arguments, and assign the arguments to
708 // them.
709 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400710 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400711 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400712 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400713 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400714
John Stiles44733aa2020-09-29 17:42:23 -0400715 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500716 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400717 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400718 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400719 // ... we don't need to copy it at all! We can just use the existing expression.
720 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400721 continue;
722 }
723 }
John Stilese41b4ee2020-09-28 12:28:16 -0400724 if (isOutParam) {
725 argsToCopyBack.push_back(i);
726 }
John Stiles7b920442020-12-17 10:43:41 -0500727 InlineVariable var = this->makeInlineVariable(param->name(), &arguments[i]->type(),
728 symbolTable.get(), param->modifiers(),
729 caller->isBuiltin(), &arguments[i]);
730 inlinedBody.children().push_back(std::move(var.fVarDecl));
731 varMap[param] = std::make_unique<VariableReference>(/*offset=*/-1, var.fVarSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400732 }
733
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400734 const Block& body = function.body()->as<Block>();
John Stiles7b920442020-12-17 10:43:41 -0500735 StatementArray* inlineStatements;
736
John Stiles44e96be2020-08-31 13:16:04 -0400737 if (hasEarlyReturn) {
738 // Since we output to backends that don't have a goto statement (which would normally be
John Stiles7b920442020-12-17 10:43:41 -0500739 // used to perform an early return), we fake it by wrapping the function in a single-
740 // iteration for loop, and use a continue statement to jump to the end of the loop
741 // prematurely.
742
743 // int _1_loop = 0;
744 symbolTable = std::make_shared<SymbolTable>(std::move(symbolTable), caller->isBuiltin());
745 const Type* intType = fContext->fInt_Type.get();
746 std::unique_ptr<Expression> initialValue = std::make_unique<IntLiteral>(/*offset=*/-1,
747 /*value=*/0,
748 intType);
749 InlineVariable loopVar = this->makeInlineVariable("loop", intType, symbolTable.get(),
750 Modifiers{}, caller->isBuiltin(),
751 &initialValue);
752
753 // _1_loop < 1;
754 std::unique_ptr<Expression> test = std::make_unique<BinaryExpression>(
John Stiles44e96be2020-08-31 13:16:04 -0400755 /*offset=*/-1,
John Stiles7b920442020-12-17 10:43:41 -0500756 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol),
757 Token::Kind::TK_LT,
758 std::make_unique<IntLiteral>(/*offset=*/-1, /*value=*/1, intType),
759 fContext->fBool_Type.get());
760
761 // _1_loop++
762 std::unique_ptr<Expression> increment = std::make_unique<PostfixExpression>(
763 std::make_unique<VariableReference>(/*offset=*/-1, loopVar.fVarSymbol,
764 VariableReference::RefKind::kReadWrite),
765 Token::Kind::TK_PLUSPLUS);
766
767 // {...}
768 auto innerBlock = std::make_unique<Block>(offset, StatementArray{},
769 /*symbols=*/nullptr, /*isScope=*/true);
770 inlineStatements = &innerBlock->children();
771
772 // for (int _1_loop = 0; _1_loop < 1; _1_loop++) {...}
773 inlinedBody.children().push_back(std::make_unique<ForStatement>(/*offset=*/-1,
774 std::move(loopVar.fVarDecl),
775 std::move(test),
776 std::move(increment),
777 std::move(innerBlock),
778 symbolTable));
John Stiles44e96be2020-08-31 13:16:04 -0400779 } else {
John Stilesfa9a0832020-12-17 10:43:58 -0500780 // No early returns, so we can just dump the code into our existing scopeless block.
781 inlineStatements = &inlinedBody.children();
John Stiles7b920442020-12-17 10:43:41 -0500782 }
783
784 inlineStatements->reserve_back(body.children().size() + argsToCopyBack.size());
785 for (const std::unique_ptr<Statement>& stmt : body.children()) {
786 inlineStatements->push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles77702f12020-12-17 14:38:56 -0500787 &resultExpr, returnComplexity, *stmt,
John Stiles7b920442020-12-17 10:43:41 -0500788 caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400789 }
790
John Stilese41b4ee2020-09-28 12:28:16 -0400791 // Copy back the values of `out` parameters into their real destinations.
792 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400793 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400794 SkASSERT(varMap.find(p) != varMap.end());
John Stiles7b920442020-12-17 10:43:41 -0500795 inlineStatements->push_back(
John Stilese41b4ee2020-09-28 12:28:16 -0400796 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
797 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400798 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400799 Token::Kind::TK_EQ,
800 std::move(varMap[p]),
801 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400802 }
803
John Stilese41b4ee2020-09-28 12:28:16 -0400804 if (resultExpr != nullptr) {
805 // Return our result variable as our replacement expression.
John Stilese41b4ee2020-09-28 12:28:16 -0400806 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400807 } else {
808 // It's a void function, so it doesn't actually result in anything, but we have to return
809 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400810 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
811 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400812 /*value=*/false);
813 }
814
John Stiles44e96be2020-08-31 13:16:04 -0400815 return inlinedCall;
816}
817
John Stiles2d7973a2020-10-02 15:01:03 -0400818bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400819 SkASSERT(fSettings);
820
John Stiles1c03d332020-10-13 10:30:23 -0400821 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
822 if (fSettings->fInlineThreshold <= 0) {
823 return false;
824 }
825
John Stiles031a7672020-11-13 16:13:18 -0500826 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
827 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
828 return false;
829 }
830
John Stiles2d7973a2020-10-02 15:01:03 -0400831 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400832 // Can't inline something if we don't actually have its definition.
833 return false;
834 }
John Stiles2d7973a2020-10-02 15:01:03 -0400835
John Stiles74ebd7e2020-12-17 14:41:50 -0500836 // We don't have any mechanism to simulate early returns within a construct that supports
837 // continues (for/do/while), so we can't inline if there's a return inside one.
838 bool hasReturnInContinuableConstruct =
839 (count_returns_in_continuable_constructs(*functionDef) > 0);
840 return !hasReturnInContinuableConstruct;
John Stiles44e96be2020-08-31 13:16:04 -0400841}
842
John Stiles2d7973a2020-10-02 15:01:03 -0400843// A candidate function for inlining, containing everything that `inlineCall` needs.
844struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500845 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400846 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
847 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
848 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
849 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400850};
John Stiles93442622020-09-11 12:11:27 -0400851
John Stiles2d7973a2020-10-02 15:01:03 -0400852struct InlineCandidateList {
853 std::vector<InlineCandidate> fCandidates;
854};
855
856class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400857public:
858 // A list of all the inlining candidates we found during analysis.
859 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400860
John Stiles70957c82020-10-02 16:42:10 -0400861 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
862 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500863 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400864 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
865 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
866 // inliner might replace a statement with a block containing the statement.
867 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
868 // The function that we're currently processing (i.e. inlining into).
869 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400870
Brian Osman0006ad02020-11-18 15:38:39 -0500871 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500872 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500873 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400874 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500875 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400876
Brian Osman0006ad02020-11-18 15:38:39 -0500877 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400878 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400879 }
880
John Stiles70957c82020-10-02 16:42:10 -0400881 fSymbolTableStack.pop_back();
882 fCandidateList = nullptr;
883 }
884
885 void visitProgramElement(ProgramElement* pe) {
886 switch (pe->kind()) {
887 case ProgramElement::Kind::kFunction: {
888 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500889 fEnclosingFunction = &funcDef;
890 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400891 break;
John Stiles93442622020-09-11 12:11:27 -0400892 }
John Stiles70957c82020-10-02 16:42:10 -0400893 default:
894 // The inliner can't operate outside of a function's scope.
895 break;
896 }
897 }
898
899 void visitStatement(std::unique_ptr<Statement>* stmt,
900 bool isViableAsEnclosingStatement = true) {
901 if (!*stmt) {
902 return;
John Stiles93442622020-09-11 12:11:27 -0400903 }
904
John Stiles70957c82020-10-02 16:42:10 -0400905 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
906 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400907
John Stiles70957c82020-10-02 16:42:10 -0400908 if (isViableAsEnclosingStatement) {
909 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400910 }
911
John Stiles70957c82020-10-02 16:42:10 -0400912 switch ((*stmt)->kind()) {
913 case Statement::Kind::kBreak:
914 case Statement::Kind::kContinue:
915 case Statement::Kind::kDiscard:
916 case Statement::Kind::kInlineMarker:
917 case Statement::Kind::kNop:
918 break;
919
920 case Statement::Kind::kBlock: {
921 Block& block = (*stmt)->as<Block>();
922 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500923 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400924 }
925
926 for (std::unique_ptr<Statement>& stmt : block.children()) {
927 this->visitStatement(&stmt);
928 }
929 break;
John Stiles93442622020-09-11 12:11:27 -0400930 }
John Stiles70957c82020-10-02 16:42:10 -0400931 case Statement::Kind::kDo: {
932 DoStatement& doStmt = (*stmt)->as<DoStatement>();
933 // The loop body is a candidate for inlining.
934 this->visitStatement(&doStmt.statement());
935 // The inliner isn't smart enough to inline the test-expression for a do-while
936 // loop at this time. There are two limitations:
937 // - We would need to insert the inlined-body block at the very end of the do-
938 // statement's inner fStatement. We don't support that today, but it's doable.
939 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
940 // would skip over the inlined block that evaluates the test expression. There
941 // isn't a good fix for this--any workaround would be more complex than the cost
942 // of a function call. However, loops that don't use `continue` would still be
943 // viable candidates for inlining.
944 break;
John Stiles93442622020-09-11 12:11:27 -0400945 }
John Stiles70957c82020-10-02 16:42:10 -0400946 case Statement::Kind::kExpression: {
947 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
948 this->visitExpression(&expr.expression());
949 break;
950 }
951 case Statement::Kind::kFor: {
952 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400953 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500954 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400955 }
956
957 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400958 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400959 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400960 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400961
962 // The inliner isn't smart enough to inline the test- or increment-expressions
963 // of a for loop loop at this time. There are a handful of limitations:
964 // - We would need to insert the test-expression block at the very beginning of the
965 // for-loop's inner fStatement, and the increment-expression block at the very
966 // end. We don't support that today, but it's doable.
967 // - The for-loop's built-in test-expression would need to be dropped entirely,
968 // and the loop would be halted via a break statement at the end of the inlined
969 // test-expression. This is again something we don't support today, but it could
970 // be implemented.
971 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
972 // that would skip over the inlined block that evaluates the increment expression.
973 // There isn't a good fix for this--any workaround would be more complex than the
974 // cost of a function call. However, loops that don't use `continue` would still
975 // be viable candidates for increment-expression inlining.
976 break;
977 }
978 case Statement::Kind::kIf: {
979 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400980 this->visitExpression(&ifStmt.test());
981 this->visitStatement(&ifStmt.ifTrue());
982 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400983 break;
984 }
985 case Statement::Kind::kReturn: {
986 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400987 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400988 break;
989 }
990 case Statement::Kind::kSwitch: {
991 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400992 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500993 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400994 }
995
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400996 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400997 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400998 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400999 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -04001000 this->visitStatement(&caseBlock);
1001 }
1002 }
1003 break;
1004 }
1005 case Statement::Kind::kVarDeclaration: {
1006 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
1007 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001008 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -04001009 break;
1010 }
John Stiles70957c82020-10-02 16:42:10 -04001011 default:
1012 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -04001013 }
1014
John Stiles70957c82020-10-02 16:42:10 -04001015 // Pop our symbol and enclosing-statement stacks.
1016 fSymbolTableStack.resize(oldSymbolStackSize);
1017 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
1018 }
1019
1020 void visitExpression(std::unique_ptr<Expression>* expr) {
1021 if (!*expr) {
1022 return;
John Stiles93442622020-09-11 12:11:27 -04001023 }
John Stiles70957c82020-10-02 16:42:10 -04001024
1025 switch ((*expr)->kind()) {
1026 case Expression::Kind::kBoolLiteral:
1027 case Expression::Kind::kDefined:
1028 case Expression::Kind::kExternalValue:
1029 case Expression::Kind::kFieldAccess:
1030 case Expression::Kind::kFloatLiteral:
1031 case Expression::Kind::kFunctionReference:
1032 case Expression::Kind::kIntLiteral:
1033 case Expression::Kind::kNullLiteral:
1034 case Expression::Kind::kSetting:
1035 case Expression::Kind::kTypeReference:
1036 case Expression::Kind::kVariableReference:
1037 // Nothing to scan here.
1038 break;
1039
1040 case Expression::Kind::kBinary: {
1041 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001042 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -04001043
1044 // Logical-and and logical-or binary expressions do not inline the right side,
1045 // because that would invalidate short-circuiting. That is, when evaluating
1046 // expressions like these:
1047 // (false && x()) // always false
1048 // (true || y()) // always true
1049 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1050 // enforce that rule is to avoid inlining the right side entirely. However, it is
1051 // safe for other types of binary expression to inline both sides.
1052 Token::Kind op = binaryExpr.getOperator();
1053 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1054 op == Token::Kind::TK_LOGICALOR);
1055 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001056 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001057 }
1058 break;
1059 }
1060 case Expression::Kind::kConstructor: {
1061 Constructor& constructorExpr = (*expr)->as<Constructor>();
1062 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1063 this->visitExpression(&arg);
1064 }
1065 break;
1066 }
1067 case Expression::Kind::kExternalFunctionCall: {
1068 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1069 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1070 this->visitExpression(&arg);
1071 }
1072 break;
1073 }
1074 case Expression::Kind::kFunctionCall: {
1075 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001076 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001077 this->visitExpression(&arg);
1078 }
1079 this->addInlineCandidate(expr);
1080 break;
1081 }
1082 case Expression::Kind::kIndex:{
1083 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001084 this->visitExpression(&indexExpr.base());
1085 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001086 break;
1087 }
1088 case Expression::Kind::kPostfix: {
1089 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001090 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001091 break;
1092 }
1093 case Expression::Kind::kPrefix: {
1094 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001095 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001096 break;
1097 }
1098 case Expression::Kind::kSwizzle: {
1099 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001100 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001101 break;
1102 }
1103 case Expression::Kind::kTernary: {
1104 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1105 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001106 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001107 // The true- and false-expressions cannot be inlined, because we are only allowed to
1108 // evaluate one side.
1109 break;
1110 }
1111 default:
1112 SkUNREACHABLE;
1113 }
1114 }
1115
1116 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1117 fCandidateList->fCandidates.push_back(
1118 InlineCandidate{fSymbolTableStack.back(),
1119 find_parent_statement(fEnclosingStmtStack),
1120 fEnclosingStmtStack.back(),
1121 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001122 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001123 }
John Stiles2d7973a2020-10-02 15:01:03 -04001124};
John Stiles93442622020-09-11 12:11:27 -04001125
John Stiles9b9415e2020-11-23 14:48:06 -05001126static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1127 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1128}
John Stiles915a38c2020-09-14 09:38:13 -04001129
John Stiles9b9415e2020-11-23 14:48:06 -05001130bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1131 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001132 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001133 if (wasInserted) {
1134 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001135 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1136 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001137 }
1138
John Stiles2d7973a2020-10-02 15:01:03 -04001139 return iter->second;
1140}
1141
John Stiles9b9415e2020-11-23 14:48:06 -05001142int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1143 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001144 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001145 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
1146 fSettings->fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001147 }
John Stiles2d7973a2020-10-02 15:01:03 -04001148 return iter->second;
1149}
1150
Brian Osman0006ad02020-11-18 15:38:39 -05001151void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001152 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001153 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001154 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1155 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1156 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1157 // `const T&`.
1158 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001159 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001160
John Stiles0ad233f2020-11-25 11:02:05 -05001161 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001162 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001163 if (candidates.empty()) {
1164 return;
1165 }
1166
1167 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001168 InlinabilityCache cache;
1169 candidates.erase(std::remove_if(candidates.begin(),
1170 candidates.end(),
1171 [&](const InlineCandidate& candidate) {
1172 return !this->candidateCanBeInlined(candidate, &cache);
1173 }),
1174 candidates.end());
1175
John Stiles0ad233f2020-11-25 11:02:05 -05001176 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1177 // complete.
1178 if (fSettings->fInlineThreshold == INT_MAX || candidates.empty()) {
1179 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001180 }
John Stiles0ad233f2020-11-25 11:02:05 -05001181
1182 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1183 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1184 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1185 FunctionSizeCache functionSizeCache;
1186 FunctionSizeCache candidateTotalCost;
1187 for (InlineCandidate& candidate : candidates) {
1188 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1189 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1190 }
1191
1192 candidates.erase(
1193 std::remove_if(candidates.begin(),
1194 candidates.end(),
1195 [&](const InlineCandidate& candidate) {
1196 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1197 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1198 // Functions marked `inline` ignore size limitations.
1199 return false;
1200 }
1201 if (usage->get(fnDecl) == 1) {
1202 // If a function is only used once, it's cost-free to inline.
1203 return false;
1204 }
1205 if (candidateTotalCost[&fnDecl] <= fSettings->fInlineThreshold) {
1206 // We won't exceed the inline threshold by inlining this.
1207 return false;
1208 }
1209 // Inlining this function will add too many IRNodes.
1210 return true;
1211 }),
1212 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001213}
1214
Brian Osman0006ad02020-11-18 15:38:39 -05001215bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001216 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001217 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001218 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1219 if (fSettings->fInlineThreshold <= 0) {
1220 return false;
1221 }
1222
John Stiles031a7672020-11-13 16:13:18 -05001223 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1224 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1225 return false;
1226 }
1227
John Stiles2d7973a2020-10-02 15:01:03 -04001228 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001229 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001230
John Stiles915a38c2020-09-14 09:38:13 -04001231 // Inline the candidates where we've determined that it's safe to do so.
1232 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1233 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001234 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001235 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001236
1237 // Inlining two expressions using the same enclosing statement in the same inlining pass
1238 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1239 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1240 if (!inserted) {
1241 continue;
1242 }
1243
1244 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001245 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001246 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001247 if (inlinedCall.fInlinedBody) {
1248 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001249 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001250
Brian Osman010ce6a2020-10-19 16:34:10 -04001251 // Add references within the inlined body
1252 usage->add(inlinedCall.fInlinedBody.get());
1253
John Stiles915a38c2020-09-14 09:38:13 -04001254 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1255 // function, then replace the enclosing statement with that Block.
1256 // Before:
1257 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1258 // fEnclosingStmt = stmt4
1259 // After:
1260 // fInlinedBody = null
1261 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001262 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001263 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1264 }
1265
1266 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001267 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001268 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1269 madeChanges = true;
1270
John Stiles031a7672020-11-13 16:13:18 -05001271 // Stop inlining if we've reached our hard cap on new statements.
1272 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1273 break;
1274 }
1275
John Stiles915a38c2020-09-14 09:38:13 -04001276 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1277 // remain valid.
1278 }
1279
1280 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001281}
1282
John Stiles44e96be2020-08-31 13:16:04 -04001283} // namespace SkSL