blob: 3a0b5365a590ee7ff94dba38220c9cdee6e42b4e [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"
54#include "src/sksl/ir/SkSLWhileStatement.h"
55
56namespace SkSL {
57namespace {
58
John Stiles031a7672020-11-13 16:13:18 -050059static constexpr int kInlinedStatementLimit = 2500;
60
John Stiles9e948122020-12-16 18:24:48 +000061static bool contains_returns_above_limit(const FunctionDefinition& funcDef, int limit) {
John Stiles44dff4f2020-09-21 12:28:01 -040062 class CountReturnsWithLimit : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040063 public:
John Stiles44dff4f2020-09-21 12:28:01 -040064 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
John Stiles44e96be2020-08-31 13:16:04 -040065 this->visitProgramElement(funcDef);
66 }
67
68 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040069 switch (stmt.kind()) {
70 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040071 ++fNumReturns;
John Stiles9e948122020-12-16 18:24:48 +000072 return (fNumReturns > fLimit) || INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040073
74 default:
John Stiles93442622020-09-11 12:11:27 -040075 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040076 }
77 }
78
79 int fNumReturns = 0;
John Stiles44dff4f2020-09-21 12:28:01 -040080 int fLimit = 0;
John Stiles44e96be2020-08-31 13:16:04 -040081 using INHERITED = ProgramVisitor;
82 };
83
John Stiles9e948122020-12-16 18:24:48 +000084 return CountReturnsWithLimit{funcDef, limit}.fNumReturns > limit;
John Stiles44e96be2020-08-31 13:16:04 -040085}
86
87static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
88 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
89 public:
90 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
91 this->visitProgramElement(funcDef);
92 }
93
94 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040095 switch (stmt.kind()) {
96 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040097 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040098 const auto& block = stmt.as<Block>();
99 return block.children().size() &&
100 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -0400101 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400102 case Statement::Kind::kSwitch:
103 case Statement::Kind::kWhile:
104 case Statement::Kind::kDo:
105 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -0400106 // Don't introspect switches or loop structures at all.
107 return false;
108
Ethan Nicholase6592142020-09-08 10:22:09 -0400109 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400110 ++fNumReturns;
111 [[fallthrough]];
112
113 default:
John Stiles93442622020-09-11 12:11:27 -0400114 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400115 }
116 }
117
118 int fNumReturns = 0;
119 using INHERITED = ProgramVisitor;
120 };
121
122 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
123}
124
125static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
126 class CountReturnsInBreakableConstructs : public ProgramVisitor {
127 public:
128 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
129 this->visitProgramElement(funcDef);
130 }
131
132 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400133 switch (stmt.kind()) {
134 case Statement::Kind::kSwitch:
135 case Statement::Kind::kWhile:
136 case Statement::Kind::kDo:
137 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400138 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400139 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400140 --fInsideBreakableConstruct;
141 return result;
142 }
143
Ethan Nicholase6592142020-09-08 10:22:09 -0400144 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400145 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
146 [[fallthrough]];
147
148 default:
John Stiles93442622020-09-11 12:11:27 -0400149 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400150 }
151 }
152
153 int fNumReturns = 0;
154 int fInsideBreakableConstruct = 0;
155 using INHERITED = ProgramVisitor;
156 };
157
158 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
159}
160
John Stiles9e948122020-12-16 18:24:48 +0000161static bool has_early_return(const FunctionDefinition& funcDef) {
162 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
163 return contains_returns_above_limit(funcDef, returnsAtEndOfControlFlow);
164}
165
John Stiles991b09d2020-09-10 13:33:40 -0400166static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
167 class ContainsRecursiveCall : public ProgramVisitor {
168 public:
169 bool visit(const FunctionDeclaration& funcDecl) {
170 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400171 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
172 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400173 }
174
175 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400176 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400177 return true;
178 }
179 return INHERITED::visitExpression(expr);
180 }
181
182 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400183 if (stmt.is<InlineMarker>() &&
184 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400185 return true;
186 }
187 return INHERITED::visitStatement(stmt);
188 }
189
190 const FunctionDeclaration* fFuncDecl;
191 using INHERITED = ProgramVisitor;
192 };
193
194 return ContainsRecursiveCall{}.visit(funcDecl);
195}
196
John Stiles44e96be2020-08-31 13:16:04 -0400197static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
John Stilesc0c51062020-12-03 17:16:29 -0500198 if (src->isArray()) {
John Stiles74ff1d62020-11-30 11:56:16 -0500199 const Type* innerType = copy_if_needed(&src->componentType(), symbolTable);
John Stilesad2d4942020-12-11 16:55:58 -0500200 return symbolTable.takeOwnershipOfSymbol(Type::MakeArrayType(src->name(), *innerType,
201 src->columns()));
John Stiles44e96be2020-08-31 13:16:04 -0400202 }
203 return src;
204}
205
John Stiles6d696082020-10-01 10:18:54 -0400206static std::unique_ptr<Statement>* find_parent_statement(
207 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400208 SkASSERT(!stmtStack.empty());
209
210 // Walk the statement stack from back to front, ignoring the last element (which is the
211 // enclosing statement).
212 auto iter = stmtStack.rbegin();
213 ++iter;
214
215 // Anything counts as a parent statement other than a scopeless Block.
216 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400217 std::unique_ptr<Statement>* stmt = *iter;
218 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400219 return stmt;
220 }
221 }
222
223 // There wasn't any parent statement to be found.
224 return nullptr;
225}
226
John Stilese41b4ee2020-09-28 12:28:16 -0400227std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
228 VariableReference::RefKind refKind) {
229 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400230 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400231 public:
232 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400233 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400234 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400235 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400236 }
237 return INHERITED::visitExpression(expr);
238 }
239
240 private:
241 VariableReference::RefKind fRefKind;
242
John Stiles70b82422020-09-30 10:55:12 -0400243 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400244 };
245
246 SetRefKindInExpression{refKind}.visitExpression(*clone);
247 return clone;
248}
249
John Stiles44e96be2020-08-31 13:16:04 -0400250} // namespace
251
John Stilesb61ee902020-09-21 12:26:59 -0400252void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
253 // No changes necessary if this statement isn't actually a block.
254 if (!inlinedBody || !inlinedBody->is<Block>()) {
255 return;
256 }
257
258 // No changes necessary if the parent statement doesn't require a scope.
259 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
260 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
261 return;
262 }
263
264 Block& block = inlinedBody->as<Block>();
265
266 // The inliner will create inlined function bodies as a Block containing multiple statements,
267 // but no scope. Normally, this is fine, but if this block is used as the statement for a
268 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
269 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
270 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
271 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
272 // absorbing the following statement into our loop--so we also add a scope to these.
273 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400274 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400275 // We found an explicit scope; all is well.
276 return;
277 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400278 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400279 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
280 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400281 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400282 return;
283 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400284 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400285 // This block has exactly one thing inside, and it's not another block. No need to scope
286 // it.
287 return;
288 }
289 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400290 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400291 }
292}
293
Brian Osman0006ad02020-11-18 15:38:39 -0500294void Inliner::reset(ModifiersPool* modifiers, const Program::Settings* settings) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400295 fModifiers = modifiers;
296 fSettings = settings;
John Stiles44e96be2020-08-31 13:16:04 -0400297 fInlineVarCounter = 0;
John Stiles031a7672020-11-13 16:13:18 -0500298 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400299}
300
John Stiles6f31e272020-12-16 13:30:54 -0500301String Inliner::uniqueNameForInlineVar(String baseName, SymbolTable* symbolTable) {
302 // The inliner runs more than once, so the base name might already have a prefix like "_123_x".
303 // Let's strip that prefix off to make the generated code easier to read.
304 if (baseName.startsWith("_")) {
305 // Determine if we have a string of digits.
306 int offset = 1;
307 while (isdigit(baseName[offset])) {
308 ++offset;
309 }
310 // If we found digits, another underscore, and anything else, that's the inliner prefix.
311 // Strip it off.
312 if (offset > 1 && baseName[offset] == '_' && baseName[offset + 1] != '\0') {
313 baseName.erase(0, offset + 1);
314 } else {
315 // This name doesn't contain an inliner prefix, but it does start with an underscore.
316 // OpenGL disallows two consecutive underscores anywhere in the string, and we'll be
317 // adding one as part of the inliner prefix, so strip the leading underscore.
318 baseName.erase(0, 1);
319 }
320 }
John Stilesc75abb82020-09-14 18:24:12 -0400321
322 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
323 // we're not reusing an existing name. (Note that within a single compilation pass, this check
324 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
325 String uniqueName;
326 for (;;) {
John Stiles6f31e272020-12-16 13:30:54 -0500327 uniqueName = String::printf("_%d_%s", fInlineVarCounter++, baseName.c_str());
John Stilesc75abb82020-09-14 18:24:12 -0400328 StringFragment frag{uniqueName.data(), uniqueName.length()};
329 if ((*symbolTable)[frag] == nullptr) {
330 break;
331 }
332 }
333
334 return uniqueName;
335}
336
John Stiles44e96be2020-08-31 13:16:04 -0400337std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
338 VariableRewriteMap* varMap,
John Stilesd7cc0932020-11-30 12:24:27 -0500339 SymbolTable* symbolTableForExpression,
John Stiles44e96be2020-08-31 13:16:04 -0400340 const Expression& expression) {
341 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
342 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500343 return this->inlineExpression(offset, varMap, symbolTableForExpression, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400344 }
345 return nullptr;
346 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400347 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
348 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400349 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400350 for (const std::unique_ptr<Expression>& arg : originalArgs) {
351 args.push_back(expr(arg));
352 }
353 return args;
354 };
355
Ethan Nicholase6592142020-09-08 10:22:09 -0400356 switch (expression.kind()) {
357 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400358 const BinaryExpression& b = expression.as<BinaryExpression>();
359 return std::make_unique<BinaryExpression>(offset,
John Stiles2d4f9592020-10-30 10:29:12 -0400360 expr(b.left()),
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400361 b.getOperator(),
John Stiles2d4f9592020-10-30 10:29:12 -0400362 expr(b.right()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400363 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400364 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400365 case Expression::Kind::kBoolLiteral:
366 case Expression::Kind::kIntLiteral:
367 case Expression::Kind::kFloatLiteral:
368 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400369 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400370 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400371 const Constructor& constructor = expression.as<Constructor>();
John Stilesd7cc0932020-11-30 12:24:27 -0500372 const Type* type = copy_if_needed(&constructor.type(), *symbolTableForExpression);
373 return std::make_unique<Constructor>(offset, type, argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400374 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400375 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400376 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400377 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400378 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400379 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400380 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400381 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400382 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400383 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400384 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400385 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400386 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400387 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400388 return std::make_unique<FunctionCall>(offset, &funcCall.type(), &funcCall.function(),
389 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400390 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400391 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400392 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400393 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400394 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400395 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
396 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400397 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400398 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400399 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400400 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400401 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400402 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400403 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400404 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400405 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400406 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400407 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400408 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400409 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400410 return std::make_unique<Swizzle>(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400411 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400412 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400413 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400414 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
415 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400416 }
Brian Osman83ba9302020-09-11 13:33:46 -0400417 case Expression::Kind::kTypeReference:
418 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400419 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400420 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400421 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400422 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400423 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400424 }
425 return v.clone();
426 }
427 default:
428 SkASSERT(false);
429 return nullptr;
430 }
431}
432
433std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
434 VariableRewriteMap* varMap,
435 SymbolTable* symbolTableForStatement,
John Stiles9e948122020-12-16 18:24:48 +0000436 const Expression* resultExpr,
437 bool haveEarlyReturns,
Brian Osman3887a012020-09-30 13:22:27 -0400438 const Statement& statement,
439 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400440 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
441 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400442 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
John Stiles9e948122020-12-16 18:24:48 +0000443 haveEarlyReturns, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400444 }
445 return nullptr;
446 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400447 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400448 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400449 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400450 for (const std::unique_ptr<Statement>& child : block.children()) {
451 result.push_back(stmt(child));
452 }
453 return result;
454 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400455 auto stmts = [&](const StatementArray& ss) {
456 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400457 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400458 for (const auto& s : ss) {
459 result.push_back(stmt(s));
460 }
461 return result;
462 };
463 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
464 if (e) {
John Stilesd7cc0932020-11-30 12:24:27 -0500465 return this->inlineExpression(offset, varMap, symbolTableForStatement, *e);
John Stiles44e96be2020-08-31 13:16:04 -0400466 }
467 return nullptr;
468 };
John Stiles031a7672020-11-13 16:13:18 -0500469
470 ++fInlinedStatementCounter;
471
Ethan Nicholase6592142020-09-08 10:22:09 -0400472 switch (statement.kind()) {
473 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400474 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400475 return std::make_unique<Block>(offset, blockStmts(b),
476 SymbolTable::WrapIfBuiltin(b.symbolTable()),
477 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400478 }
479
Ethan Nicholase6592142020-09-08 10:22:09 -0400480 case Statement::Kind::kBreak:
481 case Statement::Kind::kContinue:
482 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400483 return statement.clone();
484
Ethan Nicholase6592142020-09-08 10:22:09 -0400485 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400486 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400487 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400488 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400489 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400490 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400491 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400492 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400493 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400494 const ForStatement& f = statement.as<ForStatement>();
495 // need to ensure initializer is evaluated first so that we've already remapped its
496 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400497 std::unique_ptr<Statement> initializer = stmt(f.initializer());
498 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400499 expr(f.next()), stmt(f.statement()),
500 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400501 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400502 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400503 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400504 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
505 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400506 }
John Stiles98c1f822020-09-09 14:18:53 -0400507 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400508 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400509 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400510 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400511 const ReturnStatement& r = statement.as<ReturnStatement>();
John Stiles9e948122020-12-16 18:24:48 +0000512 if (r.expression()) {
513 SkASSERT(resultExpr);
514 auto assignment =
515 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
516 offset,
517 clone_with_ref_kind(*resultExpr,
518 VariableReference::RefKind::kWrite),
519 Token::Kind::TK_EQ,
520 expr(r.expression()),
521 &resultExpr->type()));
522 if (haveEarlyReturns) {
523 StatementArray block;
524 block.reserve_back(2);
525 block.push_back(std::move(assignment));
526 block.push_back(std::make_unique<BreakStatement>(offset));
527 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
528 /*isScope=*/true);
529 } else {
530 return std::move(assignment);
531 }
532 } else {
533 if (haveEarlyReturns) {
John Stiles44e96be2020-08-31 13:16:04 -0400534 return std::make_unique<BreakStatement>(offset);
535 } else {
536 return std::make_unique<Nop>();
537 }
538 }
539 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400540 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400541 const SwitchStatement& ss = statement.as<SwitchStatement>();
542 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400543 cases.reserve(ss.cases().size());
544 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
545 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
546 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400547 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400548 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400549 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400550 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400551 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400552 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400553 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles35fee4c2020-12-16 18:25:14 +0000554 std::unique_ptr<Expression> initialValue = expr(decl.value());
555 int arraySize = decl.arraySize();
556 const Variable& old = decl.var();
557 // We assign unique names to inlined variables--scopes hide most of the problems in this
558 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
559 // names are important.
560 auto name = std::make_unique<String>(
561 this->uniqueNameForInlineVar(String(old.name()), symbolTableForStatement));
562 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
563 const Type* baseTypePtr = copy_if_needed(&decl.baseType(), *symbolTableForStatement);
564 const Type* typePtr = copy_if_needed(&old.type(), *symbolTableForStatement);
565 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
566 std::make_unique<Variable>(offset,
567 &old.modifiers(),
568 namePtr->c_str(),
569 typePtr,
570 isBuiltinCode,
571 old.storage(),
572 initialValue.get()));
573 (*varMap)[&old] = std::make_unique<VariableReference>(offset, clone);
574 return std::make_unique<VarDeclaration>(clone, baseTypePtr, arraySize,
575 std::move(initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400576 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400577 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400578 const WhileStatement& w = statement.as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400579 return std::make_unique<WhileStatement>(offset, expr(w.test()), stmt(w.statement()));
John Stiles44e96be2020-08-31 13:16:04 -0400580 }
581 default:
582 SkASSERT(false);
583 return nullptr;
584 }
585}
586
John Stiles6eadf132020-09-08 10:16:10 -0400587Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles78047582020-12-16 16:17:41 -0500588 std::shared_ptr<SymbolTable> symbolTable,
Brian Osman3887a012020-09-30 13:22:27 -0400589 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400590 // Inlining is more complicated here than in a typical compiler, because we have to have a
591 // high-level IR and can't just drop statements into the middle of an expression or even use
592 // gotos.
593 //
594 // Since we can't insert statements into an expression, we run the inline function as extra
595 // statements before the statement we're currently processing, relying on a lack of execution
596 // order guarantees. Since we can't use gotos (which are normally used to replace return
597 // statements), we wrap the whole function in a loop and use break statements to jump to the
598 // end.
599 SkASSERT(fSettings);
600 SkASSERT(fContext);
601 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400602 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stiles44e96be2020-08-31 13:16:04 -0400603
John Stiles8e3b6be2020-10-13 11:14:08 -0400604 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400605 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400606 const FunctionDefinition& function = *call->function().definition();
John Stiles9e948122020-12-16 18:24:48 +0000607 const bool hasEarlyReturn = has_early_return(function);
John Stiles6eadf132020-09-08 10:16:10 -0400608
John Stiles44e96be2020-08-31 13:16:04 -0400609 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400610 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400611 /*symbols=*/nullptr,
612 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400613
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400614 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400615 inlinedBody.children().reserve_back(
616 1 + // Inline marker
617 1 + // Result variable
618 arguments.size() + // Function arguments (passing in)
619 arguments.size() + // Function arguments (copy out-params back)
620 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400621
Ethan Nicholasceb62142020-10-09 16:51:18 -0400622 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400623
John Stilese41b4ee2020-09-28 12:28:16 -0400624 auto makeInlineVar =
625 [&](const String& baseName, const Type* type, Modifiers modifiers,
626 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400627 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
628 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
629 // somewhere during compilation.
630 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400631 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400632 type = fContext->fFloat_Type.get();
633 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400634 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400635 type = fContext->fInt_Type.get();
636 }
637
John Stilesc75abb82020-09-14 18:24:12 -0400638 // Provide our new variable with a unique name, and add it to our symbol table.
John Stiles78047582020-12-16 16:17:41 -0500639 const String* namePtr = symbolTable->takeOwnershipOfString(std::make_unique<String>(
640 this->uniqueNameForInlineVar(baseName, symbolTable.get())));
John Stiles44e96be2020-08-31 13:16:04 -0400641 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
642
643 // Add our new variable to the symbol table.
John Stiles78047582020-12-16 16:17:41 -0500644 const Variable* variableSymbol = symbolTable->add(std::make_unique<Variable>(
John Stiles586df952020-11-12 18:27:13 -0500645 /*offset=*/-1, fModifiers->addToPool(Modifiers()),
Ethan Nicholased84b732020-10-08 11:45:44 -0400646 nameFrag, type, caller->isBuiltin(),
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400647 Variable::Storage::kLocal, initialValue->get()));
John Stiles44e96be2020-08-31 13:16:04 -0400648
649 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
650 // initial value).
Brian Osmanc0213602020-10-06 14:43:32 -0400651 std::unique_ptr<Statement> variable;
John Stiles44e96be2020-08-31 13:16:04 -0400652 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
John Stiles62a56462020-12-03 10:41:58 -0500653 variable = std::make_unique<VarDeclaration>(variableSymbol, type, /*arraySize=*/0,
654 (*initialValue)->clone());
John Stiles44e96be2020-08-31 13:16:04 -0400655 } else {
John Stiles62a56462020-12-03 10:41:58 -0500656 variable = std::make_unique<VarDeclaration>(variableSymbol, type, /*arraySize=*/0,
657 std::move(*initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400658 }
659
660 // Add the new variable-declaration statement to our block of extra statements.
Brian Osmanc0213602020-10-06 14:43:32 -0400661 inlinedBody.children().push_back(std::move(variable));
John Stiles44e96be2020-08-31 13:16:04 -0400662
John Stilese41b4ee2020-09-28 12:28:16 -0400663 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400664 };
665
666 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400667 std::unique_ptr<Expression> resultExpr;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400668 if (function.declaration().returnType() != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400669 std::unique_ptr<Expression> noInitialValue;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400670 resultExpr = makeInlineVar(String(function.declaration().name()),
671 &function.declaration().returnType(),
John Stilese41b4ee2020-09-28 12:28:16 -0400672 Modifiers{}, &noInitialValue);
John Stiles35fee4c2020-12-16 18:25:14 +0000673 }
John Stiles44e96be2020-08-31 13:16:04 -0400674
675 // Create variables in the extra statements to hold the arguments, and assign the arguments to
676 // them.
677 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400678 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400679 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400680 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400681 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400682
John Stiles44733aa2020-09-29 17:42:23 -0400683 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
John Stilesc30fbca2020-11-19 16:25:49 -0500684 if (Analysis::IsTrivialExpression(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400685 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400686 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400687 // ... we don't need to copy it at all! We can just use the existing expression.
688 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400689 continue;
690 }
691 }
692
John Stilese41b4ee2020-09-28 12:28:16 -0400693 if (isOutParam) {
694 argsToCopyBack.push_back(i);
695 }
696
Ethan Nicholase2c49992020-10-05 11:49:11 -0400697 varMap[param] = makeInlineVar(String(param->name()), &arguments[i]->type(),
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400698 param->modifiers(), &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400699 }
700
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400701 const Block& body = function.body()->as<Block>();
John Stilesd0590052020-12-15 15:21:03 -0500702 auto inlineBlock = std::make_unique<Block>(offset, StatementArray{},
703 /*symbols=*/nullptr, /*isScope=*/hasEarlyReturn);
John Stilesf4bda742020-10-14 16:57:41 -0400704 inlineBlock->children().reserve_back(body.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400705 for (const std::unique_ptr<Statement>& stmt : body.children()) {
John Stiles78047582020-12-16 16:17:41 -0500706 inlineBlock->children().push_back(this->inlineStatement(offset, &varMap, symbolTable.get(),
John Stiles9e948122020-12-16 18:24:48 +0000707 resultExpr.get(), hasEarlyReturn,
Ethan Nicholased84b732020-10-08 11:45:44 -0400708 *stmt, caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400709 }
710 if (hasEarlyReturn) {
711 // Since we output to backends that don't have a goto statement (which would normally be
712 // used to perform an early return), we fake it by wrapping the function in a
713 // do { } while (false); and then use break statements to jump to the end in order to
714 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400715 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400716 /*offset=*/-1,
717 std::move(inlineBlock),
718 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
719 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400720 // No early returns, so we can just dump the code in. We still need to keep the block so we
721 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400722 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400723 }
724
John Stilese41b4ee2020-09-28 12:28:16 -0400725 // Copy back the values of `out` parameters into their real destinations.
726 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400727 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400728 SkASSERT(varMap.find(p) != varMap.end());
729 inlinedBody.children().push_back(
730 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
731 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400732 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400733 Token::Kind::TK_EQ,
734 std::move(varMap[p]),
735 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400736 }
737
John Stilese41b4ee2020-09-28 12:28:16 -0400738 if (resultExpr != nullptr) {
739 // Return our result variable as our replacement expression.
John Stiles9e948122020-12-16 18:24:48 +0000740 SkASSERT(resultExpr->as<VariableReference>().refKind() ==
741 VariableReference::RefKind::kRead);
John Stilese41b4ee2020-09-28 12:28:16 -0400742 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400743 } else {
744 // It's a void function, so it doesn't actually result in anything, but we have to return
745 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400746 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
747 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400748 /*value=*/false);
749 }
750
John Stiles44e96be2020-08-31 13:16:04 -0400751 return inlinedCall;
752}
753
John Stiles2d7973a2020-10-02 15:01:03 -0400754bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400755 SkASSERT(fSettings);
756
John Stiles1c03d332020-10-13 10:30:23 -0400757 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
758 if (fSettings->fInlineThreshold <= 0) {
759 return false;
760 }
761
John Stiles031a7672020-11-13 16:13:18 -0500762 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
763 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
764 return false;
765 }
766
John Stiles2d7973a2020-10-02 15:01:03 -0400767 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400768 // Can't inline something if we don't actually have its definition.
769 return false;
770 }
John Stiles2d7973a2020-10-02 15:01:03 -0400771
John Stiles345d7212020-12-15 18:06:29 -0500772 if (!fCaps || !fCaps->canUseDoLoops()) {
John Stiles9e948122020-12-16 18:24:48 +0000773 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
774 // can't inline functions that have an early return.
775 bool hasEarlyReturn = has_early_return(*functionDef);
776
John Stiles44e96be2020-08-31 13:16:04 -0400777 // If we didn't detect an early return, there shouldn't be any returns in breakable
778 // constructs either.
John Stiles2d7973a2020-10-02 15:01:03 -0400779 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(*functionDef) == 0);
John Stiles44e96be2020-08-31 13:16:04 -0400780 return !hasEarlyReturn;
781 }
782 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
783 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
John Stiles2d7973a2020-10-02 15:01:03 -0400784 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(*functionDef) > 0);
John Stiles44e96be2020-08-31 13:16:04 -0400785
786 // If we detected returns in breakable constructs, we should also detect an early return.
John Stiles9e948122020-12-16 18:24:48 +0000787 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(*functionDef));
John Stiles44e96be2020-08-31 13:16:04 -0400788 return !hasReturnInBreakableConstruct;
789}
790
John Stiles2d7973a2020-10-02 15:01:03 -0400791// A candidate function for inlining, containing everything that `inlineCall` needs.
792struct InlineCandidate {
John Stiles78047582020-12-16 16:17:41 -0500793 std::shared_ptr<SymbolTable> fSymbols; // the SymbolTable of the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400794 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
795 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
796 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
797 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles2d7973a2020-10-02 15:01:03 -0400798};
John Stiles93442622020-09-11 12:11:27 -0400799
John Stiles2d7973a2020-10-02 15:01:03 -0400800struct InlineCandidateList {
801 std::vector<InlineCandidate> fCandidates;
802};
803
804class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400805public:
806 // A list of all the inlining candidates we found during analysis.
807 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400808
John Stiles70957c82020-10-02 16:42:10 -0400809 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
810 // the enclosing-statement stack.
John Stiles78047582020-12-16 16:17:41 -0500811 std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
John Stiles70957c82020-10-02 16:42:10 -0400812 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
813 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
814 // inliner might replace a statement with a block containing the statement.
815 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
816 // The function that we're currently processing (i.e. inlining into).
817 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400818
Brian Osman0006ad02020-11-18 15:38:39 -0500819 void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -0500820 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -0500821 InlineCandidateList* candidateList) {
John Stiles70957c82020-10-02 16:42:10 -0400822 fCandidateList = candidateList;
Brian Osman0006ad02020-11-18 15:38:39 -0500823 fSymbolTableStack.push_back(symbols);
John Stiles93442622020-09-11 12:11:27 -0400824
Brian Osman0006ad02020-11-18 15:38:39 -0500825 for (const std::unique_ptr<ProgramElement>& pe : elements) {
Brian Osman1179fcf2020-10-08 16:04:40 -0400826 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400827 }
828
John Stiles70957c82020-10-02 16:42:10 -0400829 fSymbolTableStack.pop_back();
830 fCandidateList = nullptr;
831 }
832
833 void visitProgramElement(ProgramElement* pe) {
834 switch (pe->kind()) {
835 case ProgramElement::Kind::kFunction: {
836 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman0006ad02020-11-18 15:38:39 -0500837 fEnclosingFunction = &funcDef;
838 this->visitStatement(&funcDef.body());
John Stiles70957c82020-10-02 16:42:10 -0400839 break;
John Stiles93442622020-09-11 12:11:27 -0400840 }
John Stiles70957c82020-10-02 16:42:10 -0400841 default:
842 // The inliner can't operate outside of a function's scope.
843 break;
844 }
845 }
846
847 void visitStatement(std::unique_ptr<Statement>* stmt,
848 bool isViableAsEnclosingStatement = true) {
849 if (!*stmt) {
850 return;
John Stiles93442622020-09-11 12:11:27 -0400851 }
852
John Stiles70957c82020-10-02 16:42:10 -0400853 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
854 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400855
John Stiles70957c82020-10-02 16:42:10 -0400856 if (isViableAsEnclosingStatement) {
857 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400858 }
859
John Stiles70957c82020-10-02 16:42:10 -0400860 switch ((*stmt)->kind()) {
861 case Statement::Kind::kBreak:
862 case Statement::Kind::kContinue:
863 case Statement::Kind::kDiscard:
864 case Statement::Kind::kInlineMarker:
865 case Statement::Kind::kNop:
866 break;
867
868 case Statement::Kind::kBlock: {
869 Block& block = (*stmt)->as<Block>();
870 if (block.symbolTable()) {
John Stiles78047582020-12-16 16:17:41 -0500871 fSymbolTableStack.push_back(block.symbolTable());
John Stiles70957c82020-10-02 16:42:10 -0400872 }
873
874 for (std::unique_ptr<Statement>& stmt : block.children()) {
875 this->visitStatement(&stmt);
876 }
877 break;
John Stiles93442622020-09-11 12:11:27 -0400878 }
John Stiles70957c82020-10-02 16:42:10 -0400879 case Statement::Kind::kDo: {
880 DoStatement& doStmt = (*stmt)->as<DoStatement>();
881 // The loop body is a candidate for inlining.
882 this->visitStatement(&doStmt.statement());
883 // The inliner isn't smart enough to inline the test-expression for a do-while
884 // loop at this time. There are two limitations:
885 // - We would need to insert the inlined-body block at the very end of the do-
886 // statement's inner fStatement. We don't support that today, but it's doable.
887 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
888 // would skip over the inlined block that evaluates the test expression. There
889 // isn't a good fix for this--any workaround would be more complex than the cost
890 // of a function call. However, loops that don't use `continue` would still be
891 // viable candidates for inlining.
892 break;
John Stiles93442622020-09-11 12:11:27 -0400893 }
John Stiles70957c82020-10-02 16:42:10 -0400894 case Statement::Kind::kExpression: {
895 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
896 this->visitExpression(&expr.expression());
897 break;
898 }
899 case Statement::Kind::kFor: {
900 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400901 if (forStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500902 fSymbolTableStack.push_back(forStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400903 }
904
905 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400906 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400907 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400908 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400909
910 // The inliner isn't smart enough to inline the test- or increment-expressions
911 // of a for loop loop at this time. There are a handful of limitations:
912 // - We would need to insert the test-expression block at the very beginning of the
913 // for-loop's inner fStatement, and the increment-expression block at the very
914 // end. We don't support that today, but it's doable.
915 // - The for-loop's built-in test-expression would need to be dropped entirely,
916 // and the loop would be halted via a break statement at the end of the inlined
917 // test-expression. This is again something we don't support today, but it could
918 // be implemented.
919 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
920 // that would skip over the inlined block that evaluates the increment expression.
921 // There isn't a good fix for this--any workaround would be more complex than the
922 // cost of a function call. However, loops that don't use `continue` would still
923 // be viable candidates for increment-expression inlining.
924 break;
925 }
926 case Statement::Kind::kIf: {
927 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400928 this->visitExpression(&ifStmt.test());
929 this->visitStatement(&ifStmt.ifTrue());
930 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400931 break;
932 }
933 case Statement::Kind::kReturn: {
934 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400935 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400936 break;
937 }
938 case Statement::Kind::kSwitch: {
939 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400940 if (switchStmt.symbols()) {
John Stiles78047582020-12-16 16:17:41 -0500941 fSymbolTableStack.push_back(switchStmt.symbols());
John Stiles70957c82020-10-02 16:42:10 -0400942 }
943
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400944 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400945 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400946 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400947 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -0400948 this->visitStatement(&caseBlock);
949 }
950 }
951 break;
952 }
953 case Statement::Kind::kVarDeclaration: {
954 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
955 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400956 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400957 break;
958 }
John Stiles70957c82020-10-02 16:42:10 -0400959 case Statement::Kind::kWhile: {
960 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
961 // The loop body is a candidate for inlining.
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400962 this->visitStatement(&whileStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400963 // The inliner isn't smart enough to inline the test-expression for a while loop at
964 // this time. There are two limitations:
965 // - We would need to insert the inlined-body block at the very beginning of the
966 // while loop's inner fStatement. We don't support that today, but it's doable.
967 // - The while-loop's built-in test-expression would need to be replaced with a
968 // `true` BoolLiteral, and the loop would be halted via a break statement at the
969 // end of the inlined test-expression. This is again something we don't support
970 // today, but it could be implemented.
971 break;
972 }
973 default:
974 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400975 }
976
John Stiles70957c82020-10-02 16:42:10 -0400977 // Pop our symbol and enclosing-statement stacks.
978 fSymbolTableStack.resize(oldSymbolStackSize);
979 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
980 }
981
982 void visitExpression(std::unique_ptr<Expression>* expr) {
983 if (!*expr) {
984 return;
John Stiles93442622020-09-11 12:11:27 -0400985 }
John Stiles70957c82020-10-02 16:42:10 -0400986
987 switch ((*expr)->kind()) {
988 case Expression::Kind::kBoolLiteral:
989 case Expression::Kind::kDefined:
990 case Expression::Kind::kExternalValue:
991 case Expression::Kind::kFieldAccess:
992 case Expression::Kind::kFloatLiteral:
993 case Expression::Kind::kFunctionReference:
994 case Expression::Kind::kIntLiteral:
995 case Expression::Kind::kNullLiteral:
996 case Expression::Kind::kSetting:
997 case Expression::Kind::kTypeReference:
998 case Expression::Kind::kVariableReference:
999 // Nothing to scan here.
1000 break;
1001
1002 case Expression::Kind::kBinary: {
1003 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001004 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -04001005
1006 // Logical-and and logical-or binary expressions do not inline the right side,
1007 // because that would invalidate short-circuiting. That is, when evaluating
1008 // expressions like these:
1009 // (false && x()) // always false
1010 // (true || y()) // always true
1011 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1012 // enforce that rule is to avoid inlining the right side entirely. However, it is
1013 // safe for other types of binary expression to inline both sides.
1014 Token::Kind op = binaryExpr.getOperator();
1015 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1016 op == Token::Kind::TK_LOGICALOR);
1017 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001018 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001019 }
1020 break;
1021 }
1022 case Expression::Kind::kConstructor: {
1023 Constructor& constructorExpr = (*expr)->as<Constructor>();
1024 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1025 this->visitExpression(&arg);
1026 }
1027 break;
1028 }
1029 case Expression::Kind::kExternalFunctionCall: {
1030 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1031 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1032 this->visitExpression(&arg);
1033 }
1034 break;
1035 }
1036 case Expression::Kind::kFunctionCall: {
1037 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001038 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001039 this->visitExpression(&arg);
1040 }
1041 this->addInlineCandidate(expr);
1042 break;
1043 }
1044 case Expression::Kind::kIndex:{
1045 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001046 this->visitExpression(&indexExpr.base());
1047 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001048 break;
1049 }
1050 case Expression::Kind::kPostfix: {
1051 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001052 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001053 break;
1054 }
1055 case Expression::Kind::kPrefix: {
1056 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001057 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001058 break;
1059 }
1060 case Expression::Kind::kSwizzle: {
1061 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001062 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001063 break;
1064 }
1065 case Expression::Kind::kTernary: {
1066 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1067 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001068 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001069 // The true- and false-expressions cannot be inlined, because we are only allowed to
1070 // evaluate one side.
1071 break;
1072 }
1073 default:
1074 SkUNREACHABLE;
1075 }
1076 }
1077
1078 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1079 fCandidateList->fCandidates.push_back(
1080 InlineCandidate{fSymbolTableStack.back(),
1081 find_parent_statement(fEnclosingStmtStack),
1082 fEnclosingStmtStack.back(),
1083 candidate,
John Stiles9b9415e2020-11-23 14:48:06 -05001084 fEnclosingFunction});
John Stiles70957c82020-10-02 16:42:10 -04001085 }
John Stiles2d7973a2020-10-02 15:01:03 -04001086};
John Stiles93442622020-09-11 12:11:27 -04001087
John Stiles9b9415e2020-11-23 14:48:06 -05001088static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
1089 return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1090}
John Stiles915a38c2020-09-14 09:38:13 -04001091
John Stiles9b9415e2020-11-23 14:48:06 -05001092bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1093 const FunctionDeclaration& funcDecl = candidate_func(candidate);
John Stiles1c03d332020-10-13 10:30:23 -04001094 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001095 if (wasInserted) {
1096 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001097 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1098 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001099 }
1100
John Stiles2d7973a2020-10-02 15:01:03 -04001101 return iter->second;
1102}
1103
John Stiles9b9415e2020-11-23 14:48:06 -05001104int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1105 auto [iter, wasInserted] = cache->insert({&funcDecl, 0});
John Stiles2d7973a2020-10-02 15:01:03 -04001106 if (wasInserted) {
John Stiles9b9415e2020-11-23 14:48:06 -05001107 iter->second = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
1108 fSettings->fInlineThreshold);
John Stiles2d7973a2020-10-02 15:01:03 -04001109 }
John Stiles2d7973a2020-10-02 15:01:03 -04001110 return iter->second;
1111}
1112
Brian Osman0006ad02020-11-18 15:38:39 -05001113void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001114 std::shared_ptr<SymbolTable> symbols, ProgramUsage* usage,
Brian Osman0006ad02020-11-18 15:38:39 -05001115 InlineCandidateList* candidateList) {
John Stiles2d7973a2020-10-02 15:01:03 -04001116 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1117 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1118 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1119 // `const T&`.
1120 InlineCandidateAnalyzer analyzer;
Brian Osman0006ad02020-11-18 15:38:39 -05001121 analyzer.visit(elements, symbols, candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001122
John Stiles0ad233f2020-11-25 11:02:05 -05001123 // Early out if there are no inlining candidates.
John Stiles2d7973a2020-10-02 15:01:03 -04001124 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
John Stiles0ad233f2020-11-25 11:02:05 -05001125 if (candidates.empty()) {
1126 return;
1127 }
1128
1129 // Remove candidates that are not safe to inline.
John Stiles2d7973a2020-10-02 15:01:03 -04001130 InlinabilityCache cache;
1131 candidates.erase(std::remove_if(candidates.begin(),
1132 candidates.end(),
1133 [&](const InlineCandidate& candidate) {
1134 return !this->candidateCanBeInlined(candidate, &cache);
1135 }),
1136 candidates.end());
1137
John Stiles0ad233f2020-11-25 11:02:05 -05001138 // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1139 // complete.
1140 if (fSettings->fInlineThreshold == INT_MAX || candidates.empty()) {
1141 return;
John Stiles2d7973a2020-10-02 15:01:03 -04001142 }
John Stiles0ad233f2020-11-25 11:02:05 -05001143
1144 // Remove candidates on a per-function basis if the effect of inlining would be to make more
1145 // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1146 // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1147 FunctionSizeCache functionSizeCache;
1148 FunctionSizeCache candidateTotalCost;
1149 for (InlineCandidate& candidate : candidates) {
1150 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1151 candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1152 }
1153
1154 candidates.erase(
1155 std::remove_if(candidates.begin(),
1156 candidates.end(),
1157 [&](const InlineCandidate& candidate) {
1158 const FunctionDeclaration& fnDecl = candidate_func(candidate);
1159 if (fnDecl.modifiers().fFlags & Modifiers::kInline_Flag) {
1160 // Functions marked `inline` ignore size limitations.
1161 return false;
1162 }
1163 if (usage->get(fnDecl) == 1) {
1164 // If a function is only used once, it's cost-free to inline.
1165 return false;
1166 }
1167 if (candidateTotalCost[&fnDecl] <= fSettings->fInlineThreshold) {
1168 // We won't exceed the inline threshold by inlining this.
1169 return false;
1170 }
1171 // Inlining this function will add too many IRNodes.
1172 return true;
1173 }),
1174 candidates.end());
John Stiles2d7973a2020-10-02 15:01:03 -04001175}
1176
Brian Osman0006ad02020-11-18 15:38:39 -05001177bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
John Stiles78047582020-12-16 16:17:41 -05001178 std::shared_ptr<SymbolTable> symbols,
Brian Osman0006ad02020-11-18 15:38:39 -05001179 ProgramUsage* usage) {
John Stilesd34d56e2020-10-12 12:04:47 -04001180 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1181 if (fSettings->fInlineThreshold <= 0) {
1182 return false;
1183 }
1184
John Stiles031a7672020-11-13 16:13:18 -05001185 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1186 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1187 return false;
1188 }
1189
John Stiles2d7973a2020-10-02 15:01:03 -04001190 InlineCandidateList candidateList;
John Stiles9b9415e2020-11-23 14:48:06 -05001191 this->buildCandidateList(elements, symbols, usage, &candidateList);
John Stiles2d7973a2020-10-02 15:01:03 -04001192
John Stiles915a38c2020-09-14 09:38:13 -04001193 // Inline the candidates where we've determined that it's safe to do so.
1194 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1195 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001196 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001197 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
John Stiles915a38c2020-09-14 09:38:13 -04001198
1199 // Inlining two expressions using the same enclosing statement in the same inlining pass
1200 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1201 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1202 if (!inserted) {
1203 continue;
1204 }
1205
1206 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001207 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001208 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001209 if (inlinedCall.fInlinedBody) {
1210 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001211 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001212
Brian Osman010ce6a2020-10-19 16:34:10 -04001213 // Add references within the inlined body
1214 usage->add(inlinedCall.fInlinedBody.get());
1215
John Stiles915a38c2020-09-14 09:38:13 -04001216 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1217 // function, then replace the enclosing statement with that Block.
1218 // Before:
1219 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1220 // fEnclosingStmt = stmt4
1221 // After:
1222 // fInlinedBody = null
1223 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001224 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001225 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1226 }
1227
1228 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001229 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001230 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1231 madeChanges = true;
1232
John Stiles031a7672020-11-13 16:13:18 -05001233 // Stop inlining if we've reached our hard cap on new statements.
1234 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1235 break;
1236 }
1237
John Stiles915a38c2020-09-14 09:38:13 -04001238 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1239 // remain valid.
1240 }
1241
1242 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001243}
1244
John Stiles44e96be2020-08-31 13:16:04 -04001245} // namespace SkSL