blob: 8ad07f587c528fb523a6d55af3102a8af9cf7edd [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 Stiles44dff4f2020-09-21 12:28:01 -040061static bool contains_returns_above_limit(const FunctionDefinition& funcDef, int limit) {
62 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 Stiles44dff4f2020-09-21 12:28:01 -040072 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 Stiles44dff4f2020-09-21 12:28:01 -040084 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
161static bool has_early_return(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400162 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
John Stiles44dff4f2020-09-21 12:28:01 -0400163 return contains_returns_above_limit(funcDef, returnsAtEndOfControlFlow);
John Stiles44e96be2020-08-31 13:16:04 -0400164}
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) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400198 if (src->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400199 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(src->name(),
200 src->typeKind(),
201 src->componentType(),
202 src->columns()));
John Stiles44e96be2020-08-31 13:16:04 -0400203 }
204 return src;
205}
206
John Stiles6d696082020-10-01 10:18:54 -0400207static std::unique_ptr<Statement>* find_parent_statement(
208 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400209 SkASSERT(!stmtStack.empty());
210
211 // Walk the statement stack from back to front, ignoring the last element (which is the
212 // enclosing statement).
213 auto iter = stmtStack.rbegin();
214 ++iter;
215
216 // Anything counts as a parent statement other than a scopeless Block.
217 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400218 std::unique_ptr<Statement>* stmt = *iter;
219 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400220 return stmt;
221 }
222 }
223
224 // There wasn't any parent statement to be found.
225 return nullptr;
226}
227
John Stilese41b4ee2020-09-28 12:28:16 -0400228std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
229 VariableReference::RefKind refKind) {
230 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400231 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400232 public:
233 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400234 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400235 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400236 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400237 }
238 return INHERITED::visitExpression(expr);
239 }
240
241 private:
242 VariableReference::RefKind fRefKind;
243
John Stiles70b82422020-09-30 10:55:12 -0400244 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400245 };
246
247 SetRefKindInExpression{refKind}.visitExpression(*clone);
248 return clone;
249}
250
John Stiles44733aa2020-09-29 17:42:23 -0400251bool is_trivial_argument(const Expression& argument) {
252 return argument.is<VariableReference>() ||
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400253 (argument.is<Swizzle>() && is_trivial_argument(*argument.as<Swizzle>().base())) ||
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400254 (argument.is<FieldAccess>() &&
255 is_trivial_argument(*argument.as<FieldAccess>().base())) ||
John Stiles80ccdbd2020-09-30 11:58:16 -0400256 (argument.is<Constructor>() &&
257 argument.as<Constructor>().arguments().size() == 1 &&
258 is_trivial_argument(*argument.as<Constructor>().arguments().front())) ||
John Stiles44733aa2020-09-29 17:42:23 -0400259 (argument.is<IndexExpression>() &&
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400260 argument.as<IndexExpression>().index()->is<IntLiteral>() &&
261 is_trivial_argument(*argument.as<IndexExpression>().base()));
John Stiles44733aa2020-09-29 17:42:23 -0400262}
263
John Stiles44e96be2020-08-31 13:16:04 -0400264} // namespace
265
John Stilesb61ee902020-09-21 12:26:59 -0400266void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
267 // No changes necessary if this statement isn't actually a block.
268 if (!inlinedBody || !inlinedBody->is<Block>()) {
269 return;
270 }
271
272 // No changes necessary if the parent statement doesn't require a scope.
273 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
274 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
275 return;
276 }
277
278 Block& block = inlinedBody->as<Block>();
279
280 // The inliner will create inlined function bodies as a Block containing multiple statements,
281 // but no scope. Normally, this is fine, but if this block is used as the statement for a
282 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
283 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
284 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
285 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
286 // absorbing the following statement into our loop--so we also add a scope to these.
287 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400288 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400289 // We found an explicit scope; all is well.
290 return;
291 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400292 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400293 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
294 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400295 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400296 return;
297 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400298 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400299 // This block has exactly one thing inside, and it's not another block. No need to scope
300 // it.
301 return;
302 }
303 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400304 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400305 }
306}
307
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400308void Inliner::reset(const Context* context, ModifiersPool* modifiers,
Brian Osmand7e76592020-11-02 12:26:22 -0500309 const Program::Settings* settings, const ShaderCapsClass* caps) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400310 fContext = context;
311 fModifiers = modifiers;
312 fSettings = settings;
Brian Osmand7e76592020-11-02 12:26:22 -0500313 fCaps = caps;
John Stiles44e96be2020-08-31 13:16:04 -0400314 fInlineVarCounter = 0;
John Stiles031a7672020-11-13 16:13:18 -0500315 fInlinedStatementCounter = 0;
John Stiles44e96be2020-08-31 13:16:04 -0400316}
317
John Stilesc75abb82020-09-14 18:24:12 -0400318String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
319 // If the base name starts with an underscore, like "_coords", we can't append another
320 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
321 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
322 // putting in this special case.
323 const char* splitter = baseName.startsWith("_") ? "" : "_";
324
325 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
326 // we're not reusing an existing name. (Note that within a single compilation pass, this check
327 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
328 String uniqueName;
329 for (;;) {
330 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
331 StringFragment frag{uniqueName.data(), uniqueName.length()};
332 if ((*symbolTable)[frag] == nullptr) {
333 break;
334 }
335 }
336
337 return uniqueName;
338}
339
John Stiles44e96be2020-08-31 13:16:04 -0400340std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
341 VariableRewriteMap* varMap,
342 const Expression& expression) {
343 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
344 if (e) {
345 return this->inlineExpression(offset, varMap, *e);
346 }
347 return nullptr;
348 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400349 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
350 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400351 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400352 for (const std::unique_ptr<Expression>& arg : originalArgs) {
353 args.push_back(expr(arg));
354 }
355 return args;
356 };
357
Ethan Nicholase6592142020-09-08 10:22:09 -0400358 switch (expression.kind()) {
359 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400360 const BinaryExpression& b = expression.as<BinaryExpression>();
361 return std::make_unique<BinaryExpression>(offset,
John Stiles2d4f9592020-10-30 10:29:12 -0400362 expr(b.left()),
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400363 b.getOperator(),
John Stiles2d4f9592020-10-30 10:29:12 -0400364 expr(b.right()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400365 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400366 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400367 case Expression::Kind::kBoolLiteral:
368 case Expression::Kind::kIntLiteral:
369 case Expression::Kind::kFloatLiteral:
370 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400371 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400372 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400373 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400374 return std::make_unique<Constructor>(offset, &constructor.type(),
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400375 argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400376 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400377 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400378 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400379 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400380 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400381 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400382 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400383 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400384 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400385 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400386 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400387 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400388 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400389 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400390 return std::make_unique<FunctionCall>(offset, &funcCall.type(), &funcCall.function(),
391 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400392 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400393 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400394 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400395 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400396 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400397 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
398 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400399 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400400 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400401 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400402 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400403 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400404 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400405 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400406 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400407 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400408 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400409 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400410 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400411 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400412 return std::make_unique<Swizzle>(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400413 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400414 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400415 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400416 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
417 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400418 }
Brian Osman83ba9302020-09-11 13:33:46 -0400419 case Expression::Kind::kTypeReference:
420 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400421 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400422 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400423 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400424 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400425 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400426 }
427 return v.clone();
428 }
429 default:
430 SkASSERT(false);
431 return nullptr;
432 }
433}
434
435std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
436 VariableRewriteMap* varMap,
437 SymbolTable* symbolTableForStatement,
John Stilese41b4ee2020-09-28 12:28:16 -0400438 const Expression* resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400439 bool haveEarlyReturns,
Brian Osman3887a012020-09-30 13:22:27 -0400440 const Statement& statement,
441 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400442 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
443 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400444 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
Brian Osman3887a012020-09-30 13:22:27 -0400445 haveEarlyReturns, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400446 }
447 return nullptr;
448 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400449 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400450 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400451 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400452 for (const std::unique_ptr<Statement>& child : block.children()) {
453 result.push_back(stmt(child));
454 }
455 return result;
456 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400457 auto stmts = [&](const StatementArray& ss) {
458 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400459 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400460 for (const auto& s : ss) {
461 result.push_back(stmt(s));
462 }
463 return result;
464 };
465 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
466 if (e) {
467 return this->inlineExpression(offset, varMap, *e);
468 }
469 return nullptr;
470 };
John Stiles031a7672020-11-13 16:13:18 -0500471
472 ++fInlinedStatementCounter;
473
Ethan Nicholase6592142020-09-08 10:22:09 -0400474 switch (statement.kind()) {
475 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400476 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400477 return std::make_unique<Block>(offset, blockStmts(b),
478 SymbolTable::WrapIfBuiltin(b.symbolTable()),
479 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400480 }
481
Ethan Nicholase6592142020-09-08 10:22:09 -0400482 case Statement::Kind::kBreak:
483 case Statement::Kind::kContinue:
484 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400485 return statement.clone();
486
Ethan Nicholase6592142020-09-08 10:22:09 -0400487 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400488 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400489 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400490 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400491 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400492 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400493 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400494 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400495 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400496 const ForStatement& f = statement.as<ForStatement>();
497 // need to ensure initializer is evaluated first so that we've already remapped its
498 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400499 std::unique_ptr<Statement> initializer = stmt(f.initializer());
500 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400501 expr(f.next()), stmt(f.statement()),
502 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400503 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400504 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400505 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400506 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
507 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400508 }
John Stiles98c1f822020-09-09 14:18:53 -0400509 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400510 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400511 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400512 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400513 const ReturnStatement& r = statement.as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400514 if (r.expression()) {
John Stilese41b4ee2020-09-28 12:28:16 -0400515 SkASSERT(resultExpr);
John Stilesa5f3c312020-09-22 12:05:16 -0400516 auto assignment =
517 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
518 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400519 clone_with_ref_kind(*resultExpr,
520 VariableReference::RefKind::kWrite),
John Stilesa5f3c312020-09-22 12:05:16 -0400521 Token::Kind::TK_EQ,
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400522 expr(r.expression()),
John Stilese41b4ee2020-09-28 12:28:16 -0400523 &resultExpr->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400524 if (haveEarlyReturns) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400525 StatementArray block;
John Stilesf4bda742020-10-14 16:57:41 -0400526 block.reserve_back(2);
John Stiles44e96be2020-08-31 13:16:04 -0400527 block.push_back(std::move(assignment));
John Stiles8f2a0cf2020-10-13 12:48:21 -0400528 block.push_back(std::make_unique<BreakStatement>(offset));
John Stiles44e96be2020-08-31 13:16:04 -0400529 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
530 /*isScope=*/true);
531 } else {
532 return std::move(assignment);
533 }
534 } else {
535 if (haveEarlyReturns) {
536 return std::make_unique<BreakStatement>(offset);
537 } else {
538 return std::make_unique<Nop>();
539 }
540 }
541 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400542 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400543 const SwitchStatement& ss = statement.as<SwitchStatement>();
544 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400545 cases.reserve(ss.cases().size());
546 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
547 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
548 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400549 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400550 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400551 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400552 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400553 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400554 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400555 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles87ae34e2020-10-13 12:50:11 -0400556 ExpressionArray sizes;
John Stiles2d4f9592020-10-30 10:29:12 -0400557 sizes.reserve_back(decl.sizes().count());
558 for (const std::unique_ptr<Expression>& size : decl.sizes()) {
559 sizes.push_back(expr(size));
John Stiles44e96be2020-08-31 13:16:04 -0400560 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400561 std::unique_ptr<Expression> initialValue = expr(decl.value());
562 const Variable& old = decl.var();
John Stilesc75abb82020-09-14 18:24:12 -0400563 // We assign unique names to inlined variables--scopes hide most of the problems in this
564 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
565 // names are important.
566 auto name = std::make_unique<String>(
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400567 this->uniqueNameForInlineVar(String(old.name()), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400568 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400569 const Type* baseTypePtr = copy_if_needed(&decl.baseType(), *symbolTableForStatement);
570 const Type* typePtr = copy_if_needed(&old.type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400571 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
572 std::make_unique<Variable>(offset,
John Stiles586df952020-11-12 18:27:13 -0500573 &old.modifiers(),
John Stiles44e96be2020-08-31 13:16:04 -0400574 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400575 typePtr,
Brian Osman3887a012020-09-30 13:22:27 -0400576 isBuiltinCode,
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400577 old.storage(),
John Stiles44e96be2020-08-31 13:16:04 -0400578 initialValue.get()));
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400579 (*varMap)[&old] = std::make_unique<VariableReference>(offset, clone);
Brian Osmanc0213602020-10-06 14:43:32 -0400580 return std::make_unique<VarDeclaration>(clone, baseTypePtr, std::move(sizes),
John Stiles44e96be2020-08-31 13:16:04 -0400581 std::move(initialValue));
582 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400583 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400584 const WhileStatement& w = statement.as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400585 return std::make_unique<WhileStatement>(offset, expr(w.test()), stmt(w.statement()));
John Stiles44e96be2020-08-31 13:16:04 -0400586 }
587 default:
588 SkASSERT(false);
589 return nullptr;
590 }
591}
592
John Stiles6eadf132020-09-08 10:16:10 -0400593Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
Brian Osman3887a012020-09-30 13:22:27 -0400594 SymbolTable* symbolTableForCall,
595 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400596 // Inlining is more complicated here than in a typical compiler, because we have to have a
597 // high-level IR and can't just drop statements into the middle of an expression or even use
598 // gotos.
599 //
600 // Since we can't insert statements into an expression, we run the inline function as extra
601 // statements before the statement we're currently processing, relying on a lack of execution
602 // order guarantees. Since we can't use gotos (which are normally used to replace return
603 // statements), we wrap the whole function in a loop and use break statements to jump to the
604 // end.
605 SkASSERT(fSettings);
606 SkASSERT(fContext);
607 SkASSERT(call);
Ethan Nicholased84b732020-10-08 11:45:44 -0400608 SkASSERT(this->isSafeToInline(call->function().definition()));
John Stilesa1e2b412020-10-20 14:51:28 -0400609 SkASSERT(!symbolTableForCall->isBuiltin());
John Stiles44e96be2020-08-31 13:16:04 -0400610
John Stiles8e3b6be2020-10-13 11:14:08 -0400611 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400612 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400613 const FunctionDefinition& function = *call->function().definition();
John Stiles6eadf132020-09-08 10:16:10 -0400614 const bool hasEarlyReturn = has_early_return(function);
615
John Stiles44e96be2020-08-31 13:16:04 -0400616 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400617 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400618 /*symbols=*/nullptr,
619 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400620
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400621 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400622 inlinedBody.children().reserve_back(
623 1 + // Inline marker
624 1 + // Result variable
625 arguments.size() + // Function arguments (passing in)
626 arguments.size() + // Function arguments (copy out-params back)
627 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400628
Ethan Nicholasceb62142020-10-09 16:51:18 -0400629 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400630
John Stilese41b4ee2020-09-28 12:28:16 -0400631 auto makeInlineVar =
632 [&](const String& baseName, const Type* type, Modifiers modifiers,
633 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400634 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
635 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
636 // somewhere during compilation.
637 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400638 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400639 type = fContext->fFloat_Type.get();
640 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400641 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400642 type = fContext->fInt_Type.get();
643 }
644
John Stilesc75abb82020-09-14 18:24:12 -0400645 // Provide our new variable with a unique name, and add it to our symbol table.
646 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400647 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
648 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400649 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
650
651 // Add our new variable to the symbol table.
John Stilesb8cc6652020-10-08 09:12:07 -0400652 const Variable* variableSymbol = symbolTableForCall->add(std::make_unique<Variable>(
John Stiles586df952020-11-12 18:27:13 -0500653 /*offset=*/-1, fModifiers->addToPool(Modifiers()),
Ethan Nicholased84b732020-10-08 11:45:44 -0400654 nameFrag, type, caller->isBuiltin(),
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400655 Variable::Storage::kLocal, initialValue->get()));
John Stiles44e96be2020-08-31 13:16:04 -0400656
657 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
658 // initial value).
Brian Osmanc0213602020-10-06 14:43:32 -0400659 std::unique_ptr<Statement> variable;
John Stiles44e96be2020-08-31 13:16:04 -0400660 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -0400661 variable = std::make_unique<VarDeclaration>(
John Stiles87ae34e2020-10-13 12:50:11 -0400662 variableSymbol, type, /*sizes=*/ExpressionArray{}, (*initialValue)->clone());
John Stiles44e96be2020-08-31 13:16:04 -0400663 } else {
Brian Osmanc0213602020-10-06 14:43:32 -0400664 variable = std::make_unique<VarDeclaration>(
John Stiles87ae34e2020-10-13 12:50:11 -0400665 variableSymbol, type, /*sizes=*/ExpressionArray{}, std::move(*initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400666 }
667
668 // Add the new variable-declaration statement to our block of extra statements.
Brian Osmanc0213602020-10-06 14:43:32 -0400669 inlinedBody.children().push_back(std::move(variable));
John Stiles44e96be2020-08-31 13:16:04 -0400670
John Stilese41b4ee2020-09-28 12:28:16 -0400671 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400672 };
673
674 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400675 std::unique_ptr<Expression> resultExpr;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400676 if (function.declaration().returnType() != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400677 std::unique_ptr<Expression> noInitialValue;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400678 resultExpr = makeInlineVar(String(function.declaration().name()),
679 &function.declaration().returnType(),
John Stilese41b4ee2020-09-28 12:28:16 -0400680 Modifiers{}, &noInitialValue);
681 }
John Stiles44e96be2020-08-31 13:16:04 -0400682
683 // Create variables in the extra statements to hold the arguments, and assign the arguments to
684 // them.
685 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400686 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400687 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400688 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400689 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400690
John Stiles44733aa2020-09-29 17:42:23 -0400691 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
692 if (is_trivial_argument(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400693 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400694 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400695 // ... we don't need to copy it at all! We can just use the existing expression.
696 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400697 continue;
698 }
699 }
700
John Stilese41b4ee2020-09-28 12:28:16 -0400701 if (isOutParam) {
702 argsToCopyBack.push_back(i);
703 }
704
Ethan Nicholase2c49992020-10-05 11:49:11 -0400705 varMap[param] = makeInlineVar(String(param->name()), &arguments[i]->type(),
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400706 param->modifiers(), &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400707 }
708
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400709 const Block& body = function.body()->as<Block>();
John Stiles8f2a0cf2020-10-13 12:48:21 -0400710 auto inlineBlock = std::make_unique<Block>(offset, StatementArray{});
John Stilesf4bda742020-10-14 16:57:41 -0400711 inlineBlock->children().reserve_back(body.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400712 for (const std::unique_ptr<Statement>& stmt : body.children()) {
Brian Osman3887a012020-09-30 13:22:27 -0400713 inlineBlock->children().push_back(this->inlineStatement(offset, &varMap, symbolTableForCall,
714 resultExpr.get(), hasEarlyReturn,
Ethan Nicholased84b732020-10-08 11:45:44 -0400715 *stmt, caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400716 }
717 if (hasEarlyReturn) {
718 // Since we output to backends that don't have a goto statement (which would normally be
719 // used to perform an early return), we fake it by wrapping the function in a
720 // do { } while (false); and then use break statements to jump to the end in order to
721 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400722 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400723 /*offset=*/-1,
724 std::move(inlineBlock),
725 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
726 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400727 // No early returns, so we can just dump the code in. We still need to keep the block so we
728 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400729 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400730 }
731
John Stilese41b4ee2020-09-28 12:28:16 -0400732 // Copy back the values of `out` parameters into their real destinations.
733 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400734 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400735 SkASSERT(varMap.find(p) != varMap.end());
736 inlinedBody.children().push_back(
737 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
738 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400739 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400740 Token::Kind::TK_EQ,
741 std::move(varMap[p]),
742 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400743 }
744
John Stilese41b4ee2020-09-28 12:28:16 -0400745 if (resultExpr != nullptr) {
746 // Return our result variable as our replacement expression.
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400747 SkASSERT(resultExpr->as<VariableReference>().refKind() ==
748 VariableReference::RefKind::kRead);
John Stilese41b4ee2020-09-28 12:28:16 -0400749 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400750 } else {
751 // It's a void function, so it doesn't actually result in anything, but we have to return
752 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400753 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
754 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400755 /*value=*/false);
756 }
757
John Stiles44e96be2020-08-31 13:16:04 -0400758 return inlinedCall;
759}
760
John Stiles2d7973a2020-10-02 15:01:03 -0400761bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400762 SkASSERT(fSettings);
763
John Stiles1c03d332020-10-13 10:30:23 -0400764 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
765 if (fSettings->fInlineThreshold <= 0) {
766 return false;
767 }
768
John Stiles031a7672020-11-13 16:13:18 -0500769 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
770 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
771 return false;
772 }
773
John Stiles2d7973a2020-10-02 15:01:03 -0400774 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400775 // Can't inline something if we don't actually have its definition.
776 return false;
777 }
John Stiles2d7973a2020-10-02 15:01:03 -0400778
Brian Osmand7e76592020-11-02 12:26:22 -0500779 if (!fCaps || !fCaps->canUseDoLoops()) {
John Stiles44e96be2020-08-31 13:16:04 -0400780 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
781 // can't inline functions that have an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400782 bool hasEarlyReturn = has_early_return(*functionDef);
John Stiles44e96be2020-08-31 13:16:04 -0400783
784 // If we didn't detect an early return, there shouldn't be any returns in breakable
785 // constructs either.
John Stiles2d7973a2020-10-02 15:01:03 -0400786 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(*functionDef) == 0);
John Stiles44e96be2020-08-31 13:16:04 -0400787 return !hasEarlyReturn;
788 }
789 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
790 // 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 -0400791 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(*functionDef) > 0);
John Stiles44e96be2020-08-31 13:16:04 -0400792
793 // If we detected returns in breakable constructs, we should also detect an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400794 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(*functionDef));
John Stiles44e96be2020-08-31 13:16:04 -0400795 return !hasReturnInBreakableConstruct;
796}
797
John Stiles2d7973a2020-10-02 15:01:03 -0400798// A candidate function for inlining, containing everything that `inlineCall` needs.
799struct InlineCandidate {
800 SymbolTable* fSymbols; // the SymbolTable of the candidate
801 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
802 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
803 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
804 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
805 bool fIsLargeFunction; // does candidate exceed the inline threshold?
806};
John Stiles93442622020-09-11 12:11:27 -0400807
John Stiles2d7973a2020-10-02 15:01:03 -0400808struct InlineCandidateList {
809 std::vector<InlineCandidate> fCandidates;
810};
811
812class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400813public:
814 // A list of all the inlining candidates we found during analysis.
815 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400816
John Stiles70957c82020-10-02 16:42:10 -0400817 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
818 // the enclosing-statement stack.
819 std::vector<SymbolTable*> fSymbolTableStack;
820 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
821 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
822 // inliner might replace a statement with a block containing the statement.
823 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
824 // The function that we're currently processing (i.e. inlining into).
825 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400826
John Stiles70957c82020-10-02 16:42:10 -0400827 void visit(Program& program, InlineCandidateList* candidateList) {
828 fCandidateList = candidateList;
829 fSymbolTableStack.push_back(program.fSymbols.get());
John Stiles93442622020-09-11 12:11:27 -0400830
Brian Osman1179fcf2020-10-08 16:04:40 -0400831 for (const auto& pe : program.elements()) {
832 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400833 }
834
John Stiles70957c82020-10-02 16:42:10 -0400835 fSymbolTableStack.pop_back();
836 fCandidateList = nullptr;
837 }
838
839 void visitProgramElement(ProgramElement* pe) {
840 switch (pe->kind()) {
841 case ProgramElement::Kind::kFunction: {
842 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
John Stilesa1e2b412020-10-20 14:51:28 -0400843 // Don't attempt to mutate any builtin functions. (If we stop cloning builtins into
844 // the program, this check can become an assertion.)
John Stiles607d36b2020-10-19 15:00:01 -0400845 if (!funcDef.isBuiltin()) {
846 fEnclosingFunction = &funcDef;
847 this->visitStatement(&funcDef.body());
848 }
John Stiles70957c82020-10-02 16:42:10 -0400849 break;
John Stiles93442622020-09-11 12:11:27 -0400850 }
John Stiles70957c82020-10-02 16:42:10 -0400851 default:
852 // The inliner can't operate outside of a function's scope.
853 break;
854 }
855 }
856
857 void visitStatement(std::unique_ptr<Statement>* stmt,
858 bool isViableAsEnclosingStatement = true) {
859 if (!*stmt) {
860 return;
John Stiles93442622020-09-11 12:11:27 -0400861 }
862
John Stiles70957c82020-10-02 16:42:10 -0400863 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
864 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400865
John Stiles70957c82020-10-02 16:42:10 -0400866 if (isViableAsEnclosingStatement) {
867 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400868 }
869
John Stiles70957c82020-10-02 16:42:10 -0400870 switch ((*stmt)->kind()) {
871 case Statement::Kind::kBreak:
872 case Statement::Kind::kContinue:
873 case Statement::Kind::kDiscard:
874 case Statement::Kind::kInlineMarker:
875 case Statement::Kind::kNop:
876 break;
877
878 case Statement::Kind::kBlock: {
879 Block& block = (*stmt)->as<Block>();
880 if (block.symbolTable()) {
881 fSymbolTableStack.push_back(block.symbolTable().get());
882 }
883
884 for (std::unique_ptr<Statement>& stmt : block.children()) {
885 this->visitStatement(&stmt);
886 }
887 break;
John Stiles93442622020-09-11 12:11:27 -0400888 }
John Stiles70957c82020-10-02 16:42:10 -0400889 case Statement::Kind::kDo: {
890 DoStatement& doStmt = (*stmt)->as<DoStatement>();
891 // The loop body is a candidate for inlining.
892 this->visitStatement(&doStmt.statement());
893 // The inliner isn't smart enough to inline the test-expression for a do-while
894 // loop at this time. There are two limitations:
895 // - We would need to insert the inlined-body block at the very end of the do-
896 // statement's inner fStatement. We don't support that today, but it's doable.
897 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
898 // would skip over the inlined block that evaluates the test expression. There
899 // isn't a good fix for this--any workaround would be more complex than the cost
900 // of a function call. However, loops that don't use `continue` would still be
901 // viable candidates for inlining.
902 break;
John Stiles93442622020-09-11 12:11:27 -0400903 }
John Stiles70957c82020-10-02 16:42:10 -0400904 case Statement::Kind::kExpression: {
905 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
906 this->visitExpression(&expr.expression());
907 break;
908 }
909 case Statement::Kind::kFor: {
910 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400911 if (forStmt.symbols()) {
912 fSymbolTableStack.push_back(forStmt.symbols().get());
John Stiles70957c82020-10-02 16:42:10 -0400913 }
914
915 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400916 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400917 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400918 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400919
920 // The inliner isn't smart enough to inline the test- or increment-expressions
921 // of a for loop loop at this time. There are a handful of limitations:
922 // - We would need to insert the test-expression block at the very beginning of the
923 // for-loop's inner fStatement, and the increment-expression block at the very
924 // end. We don't support that today, but it's doable.
925 // - The for-loop's built-in test-expression would need to be dropped entirely,
926 // and the loop would be halted via a break statement at the end of the inlined
927 // test-expression. This is again something we don't support today, but it could
928 // be implemented.
929 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
930 // that would skip over the inlined block that evaluates the increment expression.
931 // There isn't a good fix for this--any workaround would be more complex than the
932 // cost of a function call. However, loops that don't use `continue` would still
933 // be viable candidates for increment-expression inlining.
934 break;
935 }
936 case Statement::Kind::kIf: {
937 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400938 this->visitExpression(&ifStmt.test());
939 this->visitStatement(&ifStmt.ifTrue());
940 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400941 break;
942 }
943 case Statement::Kind::kReturn: {
944 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400945 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400946 break;
947 }
948 case Statement::Kind::kSwitch: {
949 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400950 if (switchStmt.symbols()) {
951 fSymbolTableStack.push_back(switchStmt.symbols().get());
John Stiles70957c82020-10-02 16:42:10 -0400952 }
953
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400954 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400955 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400956 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400957 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -0400958 this->visitStatement(&caseBlock);
959 }
960 }
961 break;
962 }
963 case Statement::Kind::kVarDeclaration: {
964 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
965 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400966 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400967 break;
968 }
John Stiles70957c82020-10-02 16:42:10 -0400969 case Statement::Kind::kWhile: {
970 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
971 // The loop body is a candidate for inlining.
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400972 this->visitStatement(&whileStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400973 // The inliner isn't smart enough to inline the test-expression for a while loop at
974 // this time. There are two limitations:
975 // - We would need to insert the inlined-body block at the very beginning of the
976 // while loop's inner fStatement. We don't support that today, but it's doable.
977 // - The while-loop's built-in test-expression would need to be replaced with a
978 // `true` BoolLiteral, and the loop would be halted via a break statement at the
979 // end of the inlined test-expression. This is again something we don't support
980 // today, but it could be implemented.
981 break;
982 }
983 default:
984 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400985 }
986
John Stiles70957c82020-10-02 16:42:10 -0400987 // Pop our symbol and enclosing-statement stacks.
988 fSymbolTableStack.resize(oldSymbolStackSize);
989 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
990 }
991
992 void visitExpression(std::unique_ptr<Expression>* expr) {
993 if (!*expr) {
994 return;
John Stiles93442622020-09-11 12:11:27 -0400995 }
John Stiles70957c82020-10-02 16:42:10 -0400996
997 switch ((*expr)->kind()) {
998 case Expression::Kind::kBoolLiteral:
999 case Expression::Kind::kDefined:
1000 case Expression::Kind::kExternalValue:
1001 case Expression::Kind::kFieldAccess:
1002 case Expression::Kind::kFloatLiteral:
1003 case Expression::Kind::kFunctionReference:
1004 case Expression::Kind::kIntLiteral:
1005 case Expression::Kind::kNullLiteral:
1006 case Expression::Kind::kSetting:
1007 case Expression::Kind::kTypeReference:
1008 case Expression::Kind::kVariableReference:
1009 // Nothing to scan here.
1010 break;
1011
1012 case Expression::Kind::kBinary: {
1013 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001014 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -04001015
1016 // Logical-and and logical-or binary expressions do not inline the right side,
1017 // because that would invalidate short-circuiting. That is, when evaluating
1018 // expressions like these:
1019 // (false && x()) // always false
1020 // (true || y()) // always true
1021 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1022 // enforce that rule is to avoid inlining the right side entirely. However, it is
1023 // safe for other types of binary expression to inline both sides.
1024 Token::Kind op = binaryExpr.getOperator();
1025 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1026 op == Token::Kind::TK_LOGICALOR);
1027 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001028 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001029 }
1030 break;
1031 }
1032 case Expression::Kind::kConstructor: {
1033 Constructor& constructorExpr = (*expr)->as<Constructor>();
1034 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1035 this->visitExpression(&arg);
1036 }
1037 break;
1038 }
1039 case Expression::Kind::kExternalFunctionCall: {
1040 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1041 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1042 this->visitExpression(&arg);
1043 }
1044 break;
1045 }
1046 case Expression::Kind::kFunctionCall: {
1047 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001048 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001049 this->visitExpression(&arg);
1050 }
1051 this->addInlineCandidate(expr);
1052 break;
1053 }
1054 case Expression::Kind::kIndex:{
1055 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001056 this->visitExpression(&indexExpr.base());
1057 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001058 break;
1059 }
1060 case Expression::Kind::kPostfix: {
1061 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001062 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001063 break;
1064 }
1065 case Expression::Kind::kPrefix: {
1066 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001067 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001068 break;
1069 }
1070 case Expression::Kind::kSwizzle: {
1071 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001072 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001073 break;
1074 }
1075 case Expression::Kind::kTernary: {
1076 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1077 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001078 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001079 // The true- and false-expressions cannot be inlined, because we are only allowed to
1080 // evaluate one side.
1081 break;
1082 }
1083 default:
1084 SkUNREACHABLE;
1085 }
1086 }
1087
1088 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1089 fCandidateList->fCandidates.push_back(
1090 InlineCandidate{fSymbolTableStack.back(),
1091 find_parent_statement(fEnclosingStmtStack),
1092 fEnclosingStmtStack.back(),
1093 candidate,
1094 fEnclosingFunction,
1095 /*isLargeFunction=*/false});
1096 }
John Stiles2d7973a2020-10-02 15:01:03 -04001097};
John Stiles93442622020-09-11 12:11:27 -04001098
John Stiles2d7973a2020-10-02 15:01:03 -04001099bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
John Stiles1c03d332020-10-13 10:30:23 -04001100 const FunctionDeclaration& funcDecl =
1101 (*candidate.fCandidateExpr)->as<FunctionCall>().function();
John Stiles915a38c2020-09-14 09:38:13 -04001102
John Stiles1c03d332020-10-13 10:30:23 -04001103 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001104 if (wasInserted) {
1105 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001106 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1107 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001108 }
1109
John Stiles2d7973a2020-10-02 15:01:03 -04001110 return iter->second;
1111}
1112
John Stiles1c03d332020-10-13 10:30:23 -04001113bool Inliner::isLargeFunction(const FunctionDefinition* functionDef) {
1114 return Analysis::NodeCountExceeds(*functionDef, fSettings->fInlineThreshold);
1115}
John Stiles2d7973a2020-10-02 15:01:03 -04001116
John Stiles1c03d332020-10-13 10:30:23 -04001117bool Inliner::isLargeFunction(const InlineCandidate& candidate, LargeFunctionCache* cache) {
1118 const FunctionDeclaration& funcDecl =
1119 (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1120
1121 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001122 if (wasInserted) {
John Stiles1c03d332020-10-13 10:30:23 -04001123 iter->second = this->isLargeFunction(funcDecl.definition());
John Stiles2d7973a2020-10-02 15:01:03 -04001124 }
1125
1126 return iter->second;
1127}
1128
1129void Inliner::buildCandidateList(Program& program, InlineCandidateList* candidateList) {
1130 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1131 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1132 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1133 // `const T&`.
1134 InlineCandidateAnalyzer analyzer;
1135 analyzer.visit(program, candidateList);
1136
1137 // Remove candidates that are not safe to inline.
1138 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
1139 InlinabilityCache cache;
1140 candidates.erase(std::remove_if(candidates.begin(),
1141 candidates.end(),
1142 [&](const InlineCandidate& candidate) {
1143 return !this->candidateCanBeInlined(candidate, &cache);
1144 }),
1145 candidates.end());
1146
1147 // Determine whether each candidate function exceeds our inlining size threshold or not. These
1148 // can still be valid candidates if they are only called one time, so we don't remove them from
1149 // the candidate list, but they will not be inlined if they're called more than once.
1150 LargeFunctionCache largeFunctionCache;
1151 for (InlineCandidate& candidate : candidates) {
1152 candidate.fIsLargeFunction = this->isLargeFunction(candidate, &largeFunctionCache);
1153 }
1154}
1155
1156bool Inliner::analyze(Program& program) {
John Stilesd34d56e2020-10-12 12:04:47 -04001157 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1158 if (fSettings->fInlineThreshold <= 0) {
1159 return false;
1160 }
1161
John Stiles031a7672020-11-13 16:13:18 -05001162 // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1163 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1164 return false;
1165 }
1166
Brian Osman010ce6a2020-10-19 16:34:10 -04001167 ProgramUsage* usage = program.fUsage.get();
John Stiles2d7973a2020-10-02 15:01:03 -04001168 InlineCandidateList candidateList;
1169 this->buildCandidateList(program, &candidateList);
1170
John Stiles915a38c2020-09-14 09:38:13 -04001171 // Inline the candidates where we've determined that it's safe to do so.
1172 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1173 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001174 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001175 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
Brian Osman010ce6a2020-10-19 16:34:10 -04001176 const FunctionDeclaration& funcDecl = funcCall.function();
John Stiles915a38c2020-09-14 09:38:13 -04001177
John Stiles2d7973a2020-10-02 15:01:03 -04001178 // If the function is large, not marked `inline`, and is called more than once, it's a bad
1179 // idea to inline it.
1180 if (candidate.fIsLargeFunction &&
Brian Osman010ce6a2020-10-19 16:34:10 -04001181 !(funcDecl.modifiers().fFlags & Modifiers::kInline_Flag) && usage->get(funcDecl) > 1) {
John Stiles915a38c2020-09-14 09:38:13 -04001182 continue;
1183 }
1184
1185 // Inlining two expressions using the same enclosing statement in the same inlining pass
1186 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1187 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1188 if (!inserted) {
1189 continue;
1190 }
1191
1192 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001193 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001194 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001195 if (inlinedCall.fInlinedBody) {
1196 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001197 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001198
Brian Osman010ce6a2020-10-19 16:34:10 -04001199 // Add references within the inlined body
1200 usage->add(inlinedCall.fInlinedBody.get());
1201
John Stiles915a38c2020-09-14 09:38:13 -04001202 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1203 // function, then replace the enclosing statement with that Block.
1204 // Before:
1205 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1206 // fEnclosingStmt = stmt4
1207 // After:
1208 // fInlinedBody = null
1209 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001210 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001211 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1212 }
1213
1214 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001215 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001216 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1217 madeChanges = true;
1218
John Stiles031a7672020-11-13 16:13:18 -05001219 // Stop inlining if we've reached our hard cap on new statements.
1220 if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1221 break;
1222 }
1223
John Stiles915a38c2020-09-14 09:38:13 -04001224 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1225 // remain valid.
1226 }
1227
1228 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001229}
1230
John Stiles44e96be2020-08-31 13:16:04 -04001231} // namespace SkSL