blob: a3d4b6c8711614c92bb73189a711ae60bb6b3578 [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 Stiles44dff4f2020-09-21 12:28:01 -040059static bool contains_returns_above_limit(const FunctionDefinition& funcDef, int limit) {
60 class CountReturnsWithLimit : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040061 public:
John Stiles44dff4f2020-09-21 12:28:01 -040062 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
John Stiles44e96be2020-08-31 13:16:04 -040063 this->visitProgramElement(funcDef);
64 }
65
66 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040067 switch (stmt.kind()) {
68 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040069 ++fNumReturns;
John Stiles44dff4f2020-09-21 12:28:01 -040070 return (fNumReturns > fLimit) || INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040071
72 default:
John Stiles93442622020-09-11 12:11:27 -040073 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040074 }
75 }
76
77 int fNumReturns = 0;
John Stiles44dff4f2020-09-21 12:28:01 -040078 int fLimit = 0;
John Stiles44e96be2020-08-31 13:16:04 -040079 using INHERITED = ProgramVisitor;
80 };
81
John Stiles44dff4f2020-09-21 12:28:01 -040082 return CountReturnsWithLimit{funcDef, limit}.fNumReturns > limit;
John Stiles44e96be2020-08-31 13:16:04 -040083}
84
85static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
86 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
87 public:
88 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
89 this->visitProgramElement(funcDef);
90 }
91
92 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040093 switch (stmt.kind()) {
94 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040095 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040096 const auto& block = stmt.as<Block>();
97 return block.children().size() &&
98 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -040099 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400100 case Statement::Kind::kSwitch:
101 case Statement::Kind::kWhile:
102 case Statement::Kind::kDo:
103 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -0400104 // Don't introspect switches or loop structures at all.
105 return false;
106
Ethan Nicholase6592142020-09-08 10:22:09 -0400107 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400108 ++fNumReturns;
109 [[fallthrough]];
110
111 default:
John Stiles93442622020-09-11 12:11:27 -0400112 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400113 }
114 }
115
116 int fNumReturns = 0;
117 using INHERITED = ProgramVisitor;
118 };
119
120 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
121}
122
123static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
124 class CountReturnsInBreakableConstructs : public ProgramVisitor {
125 public:
126 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
127 this->visitProgramElement(funcDef);
128 }
129
130 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400131 switch (stmt.kind()) {
132 case Statement::Kind::kSwitch:
133 case Statement::Kind::kWhile:
134 case Statement::Kind::kDo:
135 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400136 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400137 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400138 --fInsideBreakableConstruct;
139 return result;
140 }
141
Ethan Nicholase6592142020-09-08 10:22:09 -0400142 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400143 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
144 [[fallthrough]];
145
146 default:
John Stiles93442622020-09-11 12:11:27 -0400147 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400148 }
149 }
150
151 int fNumReturns = 0;
152 int fInsideBreakableConstruct = 0;
153 using INHERITED = ProgramVisitor;
154 };
155
156 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
157}
158
159static bool has_early_return(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400160 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
John Stiles44dff4f2020-09-21 12:28:01 -0400161 return contains_returns_above_limit(funcDef, returnsAtEndOfControlFlow);
John Stiles44e96be2020-08-31 13:16:04 -0400162}
163
John Stiles991b09d2020-09-10 13:33:40 -0400164static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
165 class ContainsRecursiveCall : public ProgramVisitor {
166 public:
167 bool visit(const FunctionDeclaration& funcDecl) {
168 fFuncDecl = &funcDecl;
Ethan Nicholased84b732020-10-08 11:45:44 -0400169 return funcDecl.definition() ? this->visitProgramElement(*funcDecl.definition())
170 : false;
John Stiles991b09d2020-09-10 13:33:40 -0400171 }
172
173 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400174 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400175 return true;
176 }
177 return INHERITED::visitExpression(expr);
178 }
179
180 bool visitStatement(const Statement& stmt) override {
Ethan Nicholasceb62142020-10-09 16:51:18 -0400181 if (stmt.is<InlineMarker>() &&
182 stmt.as<InlineMarker>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400183 return true;
184 }
185 return INHERITED::visitStatement(stmt);
186 }
187
188 const FunctionDeclaration* fFuncDecl;
189 using INHERITED = ProgramVisitor;
190 };
191
192 return ContainsRecursiveCall{}.visit(funcDecl);
193}
194
John Stiles44e96be2020-08-31 13:16:04 -0400195static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400196 if (src->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400197 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(src->name(),
198 src->typeKind(),
199 src->componentType(),
200 src->columns()));
John Stiles44e96be2020-08-31 13:16:04 -0400201 }
202 return src;
203}
204
John Stiles6d696082020-10-01 10:18:54 -0400205static std::unique_ptr<Statement>* find_parent_statement(
206 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400207 SkASSERT(!stmtStack.empty());
208
209 // Walk the statement stack from back to front, ignoring the last element (which is the
210 // enclosing statement).
211 auto iter = stmtStack.rbegin();
212 ++iter;
213
214 // Anything counts as a parent statement other than a scopeless Block.
215 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400216 std::unique_ptr<Statement>* stmt = *iter;
217 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400218 return stmt;
219 }
220 }
221
222 // There wasn't any parent statement to be found.
223 return nullptr;
224}
225
John Stilese41b4ee2020-09-28 12:28:16 -0400226std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
227 VariableReference::RefKind refKind) {
228 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400229 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400230 public:
231 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400232 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400233 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400234 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400235 }
236 return INHERITED::visitExpression(expr);
237 }
238
239 private:
240 VariableReference::RefKind fRefKind;
241
John Stiles70b82422020-09-30 10:55:12 -0400242 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400243 };
244
245 SetRefKindInExpression{refKind}.visitExpression(*clone);
246 return clone;
247}
248
John Stiles44733aa2020-09-29 17:42:23 -0400249bool is_trivial_argument(const Expression& argument) {
250 return argument.is<VariableReference>() ||
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400251 (argument.is<Swizzle>() && is_trivial_argument(*argument.as<Swizzle>().base())) ||
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400252 (argument.is<FieldAccess>() &&
253 is_trivial_argument(*argument.as<FieldAccess>().base())) ||
John Stiles80ccdbd2020-09-30 11:58:16 -0400254 (argument.is<Constructor>() &&
255 argument.as<Constructor>().arguments().size() == 1 &&
256 is_trivial_argument(*argument.as<Constructor>().arguments().front())) ||
John Stiles44733aa2020-09-29 17:42:23 -0400257 (argument.is<IndexExpression>() &&
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400258 argument.as<IndexExpression>().index()->is<IntLiteral>() &&
259 is_trivial_argument(*argument.as<IndexExpression>().base()));
John Stiles44733aa2020-09-29 17:42:23 -0400260}
261
John Stiles44e96be2020-08-31 13:16:04 -0400262} // namespace
263
John Stilesb61ee902020-09-21 12:26:59 -0400264void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
265 // No changes necessary if this statement isn't actually a block.
266 if (!inlinedBody || !inlinedBody->is<Block>()) {
267 return;
268 }
269
270 // No changes necessary if the parent statement doesn't require a scope.
271 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
272 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
273 return;
274 }
275
276 Block& block = inlinedBody->as<Block>();
277
278 // The inliner will create inlined function bodies as a Block containing multiple statements,
279 // but no scope. Normally, this is fine, but if this block is used as the statement for a
280 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
281 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
282 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
283 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
284 // absorbing the following statement into our loop--so we also add a scope to these.
285 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400286 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400287 // We found an explicit scope; all is well.
288 return;
289 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400290 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400291 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
292 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400293 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400294 return;
295 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400296 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400297 // This block has exactly one thing inside, and it's not another block. No need to scope
298 // it.
299 return;
300 }
301 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400302 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400303 }
304}
305
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400306void Inliner::reset(const Context* context, ModifiersPool* modifiers,
Brian Osmand7e76592020-11-02 12:26:22 -0500307 const Program::Settings* settings, const ShaderCapsClass* caps) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400308 fContext = context;
309 fModifiers = modifiers;
310 fSettings = settings;
Brian Osmand7e76592020-11-02 12:26:22 -0500311 fCaps = caps;
John Stiles44e96be2020-08-31 13:16:04 -0400312 fInlineVarCounter = 0;
313}
314
John Stilesc75abb82020-09-14 18:24:12 -0400315String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
316 // If the base name starts with an underscore, like "_coords", we can't append another
317 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
318 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
319 // putting in this special case.
320 const char* splitter = baseName.startsWith("_") ? "" : "_";
321
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 (;;) {
327 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
328 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,
339 const Expression& expression) {
340 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
341 if (e) {
342 return this->inlineExpression(offset, varMap, *e);
343 }
344 return nullptr;
345 };
John Stiles8e3b6be2020-10-13 11:14:08 -0400346 auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
347 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400348 args.reserve_back(originalArgs.size());
John Stiles44e96be2020-08-31 13:16:04 -0400349 for (const std::unique_ptr<Expression>& arg : originalArgs) {
350 args.push_back(expr(arg));
351 }
352 return args;
353 };
354
Ethan Nicholase6592142020-09-08 10:22:09 -0400355 switch (expression.kind()) {
356 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400357 const BinaryExpression& b = expression.as<BinaryExpression>();
358 return std::make_unique<BinaryExpression>(offset,
John Stiles2d4f9592020-10-30 10:29:12 -0400359 expr(b.left()),
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400360 b.getOperator(),
John Stiles2d4f9592020-10-30 10:29:12 -0400361 expr(b.right()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400362 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400363 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400364 case Expression::Kind::kBoolLiteral:
365 case Expression::Kind::kIntLiteral:
366 case Expression::Kind::kFloatLiteral:
367 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400368 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400369 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400370 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400371 return std::make_unique<Constructor>(offset, &constructor.type(),
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400372 argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400373 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400374 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400375 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400376 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.function(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400377 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400378 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400379 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400380 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400381 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400382 const FieldAccess& f = expression.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400383 return std::make_unique<FieldAccess>(expr(f.base()), f.fieldIndex(), f.ownerKind());
John Stiles44e96be2020-08-31 13:16:04 -0400384 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400385 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400386 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400387 return std::make_unique<FunctionCall>(offset, &funcCall.type(), &funcCall.function(),
388 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400389 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400390 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400391 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400392 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400393 const IndexExpression& idx = expression.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400394 return std::make_unique<IndexExpression>(*fContext, expr(idx.base()),
395 expr(idx.index()));
John Stiles44e96be2020-08-31 13:16:04 -0400396 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400397 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400398 const PrefixExpression& p = expression.as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400399 return std::make_unique<PrefixExpression>(p.getOperator(), expr(p.operand()));
John Stiles44e96be2020-08-31 13:16:04 -0400400 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400401 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400402 const PostfixExpression& p = expression.as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400403 return std::make_unique<PostfixExpression>(expr(p.operand()), p.getOperator());
John Stiles44e96be2020-08-31 13:16:04 -0400404 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400405 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400406 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400407 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400408 const Swizzle& s = expression.as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400409 return std::make_unique<Swizzle>(*fContext, expr(s.base()), s.components());
John Stiles44e96be2020-08-31 13:16:04 -0400410 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400411 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400412 const TernaryExpression& t = expression.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400413 return std::make_unique<TernaryExpression>(offset, expr(t.test()),
414 expr(t.ifTrue()), expr(t.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400415 }
Brian Osman83ba9302020-09-11 13:33:46 -0400416 case Expression::Kind::kTypeReference:
417 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400418 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400419 const VariableReference& v = expression.as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400420 auto varMapIter = varMap->find(v.variable());
John Stilese41b4ee2020-09-28 12:28:16 -0400421 if (varMapIter != varMap->end()) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400422 return clone_with_ref_kind(*varMapIter->second, v.refKind());
John Stiles44e96be2020-08-31 13:16:04 -0400423 }
424 return v.clone();
425 }
426 default:
427 SkASSERT(false);
428 return nullptr;
429 }
430}
431
432std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
433 VariableRewriteMap* varMap,
434 SymbolTable* symbolTableForStatement,
John Stilese41b4ee2020-09-28 12:28:16 -0400435 const Expression* resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400436 bool haveEarlyReturns,
Brian Osman3887a012020-09-30 13:22:27 -0400437 const Statement& statement,
438 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400439 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
440 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400441 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
Brian Osman3887a012020-09-30 13:22:27 -0400442 haveEarlyReturns, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400443 }
444 return nullptr;
445 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400446 auto blockStmts = [&](const Block& block) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400447 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400448 result.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400449 for (const std::unique_ptr<Statement>& child : block.children()) {
450 result.push_back(stmt(child));
451 }
452 return result;
453 };
John Stiles8f2a0cf2020-10-13 12:48:21 -0400454 auto stmts = [&](const StatementArray& ss) {
455 StatementArray result;
John Stilesf4bda742020-10-14 16:57:41 -0400456 result.reserve_back(ss.size());
John Stiles44e96be2020-08-31 13:16:04 -0400457 for (const auto& s : ss) {
458 result.push_back(stmt(s));
459 }
460 return result;
461 };
462 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
463 if (e) {
464 return this->inlineExpression(offset, varMap, *e);
465 }
466 return nullptr;
467 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400468 switch (statement.kind()) {
469 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400470 const Block& b = statement.as<Block>();
John Stilesa1e2b412020-10-20 14:51:28 -0400471 return std::make_unique<Block>(offset, blockStmts(b),
472 SymbolTable::WrapIfBuiltin(b.symbolTable()),
473 b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400474 }
475
Ethan Nicholase6592142020-09-08 10:22:09 -0400476 case Statement::Kind::kBreak:
477 case Statement::Kind::kContinue:
478 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400479 return statement.clone();
480
Ethan Nicholase6592142020-09-08 10:22:09 -0400481 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400482 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400483 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400484 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400485 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400486 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400487 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400488 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400489 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400490 const ForStatement& f = statement.as<ForStatement>();
491 // need to ensure initializer is evaluated first so that we've already remapped its
492 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400493 std::unique_ptr<Statement> initializer = stmt(f.initializer());
494 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
John Stilesa1e2b412020-10-20 14:51:28 -0400495 expr(f.next()), stmt(f.statement()),
496 SymbolTable::WrapIfBuiltin(f.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400497 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400498 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400499 const IfStatement& i = statement.as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400500 return std::make_unique<IfStatement>(offset, i.isStatic(), expr(i.test()),
501 stmt(i.ifTrue()), stmt(i.ifFalse()));
John Stiles44e96be2020-08-31 13:16:04 -0400502 }
John Stiles98c1f822020-09-09 14:18:53 -0400503 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400504 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400505 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400506 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400507 const ReturnStatement& r = statement.as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400508 if (r.expression()) {
John Stilese41b4ee2020-09-28 12:28:16 -0400509 SkASSERT(resultExpr);
John Stilesa5f3c312020-09-22 12:05:16 -0400510 auto assignment =
511 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
512 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400513 clone_with_ref_kind(*resultExpr,
514 VariableReference::RefKind::kWrite),
John Stilesa5f3c312020-09-22 12:05:16 -0400515 Token::Kind::TK_EQ,
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400516 expr(r.expression()),
John Stilese41b4ee2020-09-28 12:28:16 -0400517 &resultExpr->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400518 if (haveEarlyReturns) {
John Stiles8f2a0cf2020-10-13 12:48:21 -0400519 StatementArray block;
John Stilesf4bda742020-10-14 16:57:41 -0400520 block.reserve_back(2);
John Stiles44e96be2020-08-31 13:16:04 -0400521 block.push_back(std::move(assignment));
John Stiles8f2a0cf2020-10-13 12:48:21 -0400522 block.push_back(std::make_unique<BreakStatement>(offset));
John Stiles44e96be2020-08-31 13:16:04 -0400523 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
524 /*isScope=*/true);
525 } else {
526 return std::move(assignment);
527 }
528 } else {
529 if (haveEarlyReturns) {
530 return std::make_unique<BreakStatement>(offset);
531 } else {
532 return std::make_unique<Nop>();
533 }
534 }
535 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400536 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400537 const SwitchStatement& ss = statement.as<SwitchStatement>();
538 std::vector<std::unique_ptr<SwitchCase>> cases;
John Stiles2d4f9592020-10-30 10:29:12 -0400539 cases.reserve(ss.cases().size());
540 for (const std::unique_ptr<SwitchCase>& sc : ss.cases()) {
541 cases.push_back(std::make_unique<SwitchCase>(offset, expr(sc->value()),
542 stmts(sc->statements())));
John Stiles44e96be2020-08-31 13:16:04 -0400543 }
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400544 return std::make_unique<SwitchStatement>(offset, ss.isStatic(), expr(ss.value()),
John Stilesa1e2b412020-10-20 14:51:28 -0400545 std::move(cases),
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400546 SymbolTable::WrapIfBuiltin(ss.symbols()));
John Stiles44e96be2020-08-31 13:16:04 -0400547 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400548 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400549 const VarDeclaration& decl = statement.as<VarDeclaration>();
John Stiles87ae34e2020-10-13 12:50:11 -0400550 ExpressionArray sizes;
John Stiles2d4f9592020-10-30 10:29:12 -0400551 sizes.reserve_back(decl.sizes().count());
552 for (const std::unique_ptr<Expression>& size : decl.sizes()) {
553 sizes.push_back(expr(size));
John Stiles44e96be2020-08-31 13:16:04 -0400554 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400555 std::unique_ptr<Expression> initialValue = expr(decl.value());
556 const Variable& old = decl.var();
John Stilesc75abb82020-09-14 18:24:12 -0400557 // 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>(
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400561 this->uniqueNameForInlineVar(String(old.name()), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400562 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400563 const Type* baseTypePtr = copy_if_needed(&decl.baseType(), *symbolTableForStatement);
564 const Type* typePtr = copy_if_needed(&old.type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400565 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
566 std::make_unique<Variable>(offset,
John Stiles586df952020-11-12 18:27:13 -0500567 &old.modifiers(),
John Stiles44e96be2020-08-31 13:16:04 -0400568 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400569 typePtr,
Brian Osman3887a012020-09-30 13:22:27 -0400570 isBuiltinCode,
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400571 old.storage(),
John Stiles44e96be2020-08-31 13:16:04 -0400572 initialValue.get()));
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400573 (*varMap)[&old] = std::make_unique<VariableReference>(offset, clone);
Brian Osmanc0213602020-10-06 14:43:32 -0400574 return std::make_unique<VarDeclaration>(clone, baseTypePtr, std::move(sizes),
John Stiles44e96be2020-08-31 13:16:04 -0400575 std::move(initialValue));
576 }
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,
Brian Osman3887a012020-09-30 13:22:27 -0400588 SymbolTable* symbolTableForCall,
589 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 Stilesa1e2b412020-10-20 14:51:28 -0400603 SkASSERT(!symbolTableForCall->isBuiltin());
John Stiles44e96be2020-08-31 13:16:04 -0400604
John Stiles8e3b6be2020-10-13 11:14:08 -0400605 ExpressionArray& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400606 const int offset = call->fOffset;
Ethan Nicholased84b732020-10-08 11:45:44 -0400607 const FunctionDefinition& function = *call->function().definition();
John Stiles6eadf132020-09-08 10:16:10 -0400608 const bool hasEarlyReturn = has_early_return(function);
609
John Stiles44e96be2020-08-31 13:16:04 -0400610 InlinedCall inlinedCall;
John Stiles8f2a0cf2020-10-13 12:48:21 -0400611 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, StatementArray{},
John Stiles6eadf132020-09-08 10:16:10 -0400612 /*symbols=*/nullptr,
613 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400614
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400615 Block& inlinedBody = *inlinedCall.fInlinedBody;
John Stiles82f373c2020-10-20 13:58:05 -0400616 inlinedBody.children().reserve_back(
617 1 + // Inline marker
618 1 + // Result variable
619 arguments.size() + // Function arguments (passing in)
620 arguments.size() + // Function arguments (copy out-params back)
621 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400622
Ethan Nicholasceb62142020-10-09 16:51:18 -0400623 inlinedBody.children().push_back(std::make_unique<InlineMarker>(&call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400624
John Stilese41b4ee2020-09-28 12:28:16 -0400625 auto makeInlineVar =
626 [&](const String& baseName, const Type* type, Modifiers modifiers,
627 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400628 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
629 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
630 // somewhere during compilation.
631 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400632 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400633 type = fContext->fFloat_Type.get();
634 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400635 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400636 type = fContext->fInt_Type.get();
637 }
638
John Stilesc75abb82020-09-14 18:24:12 -0400639 // Provide our new variable with a unique name, and add it to our symbol table.
640 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400641 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
642 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400643 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
644
645 // Add our new variable to the symbol table.
John Stilesb8cc6652020-10-08 09:12:07 -0400646 const Variable* variableSymbol = symbolTableForCall->add(std::make_unique<Variable>(
John Stiles586df952020-11-12 18:27:13 -0500647 /*offset=*/-1, fModifiers->addToPool(Modifiers()),
Ethan Nicholased84b732020-10-08 11:45:44 -0400648 nameFrag, type, caller->isBuiltin(),
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400649 Variable::Storage::kLocal, initialValue->get()));
John Stiles44e96be2020-08-31 13:16:04 -0400650
651 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
652 // initial value).
Brian Osmanc0213602020-10-06 14:43:32 -0400653 std::unique_ptr<Statement> variable;
John Stiles44e96be2020-08-31 13:16:04 -0400654 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -0400655 variable = std::make_unique<VarDeclaration>(
John Stiles87ae34e2020-10-13 12:50:11 -0400656 variableSymbol, type, /*sizes=*/ExpressionArray{}, (*initialValue)->clone());
John Stiles44e96be2020-08-31 13:16:04 -0400657 } else {
Brian Osmanc0213602020-10-06 14:43:32 -0400658 variable = std::make_unique<VarDeclaration>(
John Stiles87ae34e2020-10-13 12:50:11 -0400659 variableSymbol, type, /*sizes=*/ExpressionArray{}, std::move(*initialValue));
John Stiles44e96be2020-08-31 13:16:04 -0400660 }
661
662 // Add the new variable-declaration statement to our block of extra statements.
Brian Osmanc0213602020-10-06 14:43:32 -0400663 inlinedBody.children().push_back(std::move(variable));
John Stiles44e96be2020-08-31 13:16:04 -0400664
John Stilese41b4ee2020-09-28 12:28:16 -0400665 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400666 };
667
668 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400669 std::unique_ptr<Expression> resultExpr;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400670 if (function.declaration().returnType() != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400671 std::unique_ptr<Expression> noInitialValue;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400672 resultExpr = makeInlineVar(String(function.declaration().name()),
673 &function.declaration().returnType(),
John Stilese41b4ee2020-09-28 12:28:16 -0400674 Modifiers{}, &noInitialValue);
675 }
John Stiles44e96be2020-08-31 13:16:04 -0400676
677 // Create variables in the extra statements to hold the arguments, and assign the arguments to
678 // them.
679 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400680 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400681 for (int i = 0; i < (int) arguments.size(); ++i) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400682 const Variable* param = function.declaration().parameters()[i];
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400683 bool isOutParam = param->modifiers().fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400684
John Stiles44733aa2020-09-29 17:42:23 -0400685 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
686 if (is_trivial_argument(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400687 // ... and it's an `out` param, or it isn't written to within the inline function...
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400688 if (isOutParam || !Analysis::StatementWritesToVariable(*function.body(), *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400689 // ... we don't need to copy it at all! We can just use the existing expression.
690 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400691 continue;
692 }
693 }
694
John Stilese41b4ee2020-09-28 12:28:16 -0400695 if (isOutParam) {
696 argsToCopyBack.push_back(i);
697 }
698
Ethan Nicholase2c49992020-10-05 11:49:11 -0400699 varMap[param] = makeInlineVar(String(param->name()), &arguments[i]->type(),
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400700 param->modifiers(), &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400701 }
702
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400703 const Block& body = function.body()->as<Block>();
John Stiles8f2a0cf2020-10-13 12:48:21 -0400704 auto inlineBlock = std::make_unique<Block>(offset, StatementArray{});
John Stilesf4bda742020-10-14 16:57:41 -0400705 inlineBlock->children().reserve_back(body.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400706 for (const std::unique_ptr<Statement>& stmt : body.children()) {
Brian Osman3887a012020-09-30 13:22:27 -0400707 inlineBlock->children().push_back(this->inlineStatement(offset, &varMap, symbolTableForCall,
708 resultExpr.get(), hasEarlyReturn,
Ethan Nicholased84b732020-10-08 11:45:44 -0400709 *stmt, caller->isBuiltin()));
John Stiles44e96be2020-08-31 13:16:04 -0400710 }
711 if (hasEarlyReturn) {
712 // Since we output to backends that don't have a goto statement (which would normally be
713 // used to perform an early return), we fake it by wrapping the function in a
714 // do { } while (false); and then use break statements to jump to the end in order to
715 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400716 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400717 /*offset=*/-1,
718 std::move(inlineBlock),
719 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
720 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400721 // No early returns, so we can just dump the code in. We still need to keep the block so we
722 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400723 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400724 }
725
John Stilese41b4ee2020-09-28 12:28:16 -0400726 // Copy back the values of `out` parameters into their real destinations.
727 for (int i : argsToCopyBack) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400728 const Variable* p = function.declaration().parameters()[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400729 SkASSERT(varMap.find(p) != varMap.end());
730 inlinedBody.children().push_back(
731 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
732 offset,
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400733 clone_with_ref_kind(*arguments[i], VariableReference::RefKind::kWrite),
John Stilese41b4ee2020-09-28 12:28:16 -0400734 Token::Kind::TK_EQ,
735 std::move(varMap[p]),
736 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400737 }
738
John Stilese41b4ee2020-09-28 12:28:16 -0400739 if (resultExpr != nullptr) {
740 // Return our result variable as our replacement expression.
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400741 SkASSERT(resultExpr->as<VariableReference>().refKind() ==
742 VariableReference::RefKind::kRead);
John Stilese41b4ee2020-09-28 12:28:16 -0400743 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400744 } else {
745 // It's a void function, so it doesn't actually result in anything, but we have to return
746 // something non-null as a standin.
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400747 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext,
748 offset,
John Stiles44e96be2020-08-31 13:16:04 -0400749 /*value=*/false);
750 }
751
John Stiles44e96be2020-08-31 13:16:04 -0400752 return inlinedCall;
753}
754
John Stiles2d7973a2020-10-02 15:01:03 -0400755bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400756 SkASSERT(fSettings);
757
John Stiles1c03d332020-10-13 10:30:23 -0400758 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
759 if (fSettings->fInlineThreshold <= 0) {
760 return false;
761 }
762
John Stiles2d7973a2020-10-02 15:01:03 -0400763 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400764 // Can't inline something if we don't actually have its definition.
765 return false;
766 }
John Stiles2d7973a2020-10-02 15:01:03 -0400767
Brian Osmand7e76592020-11-02 12:26:22 -0500768 if (!fCaps || !fCaps->canUseDoLoops()) {
John Stiles44e96be2020-08-31 13:16:04 -0400769 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
770 // can't inline functions that have an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400771 bool hasEarlyReturn = has_early_return(*functionDef);
John Stiles44e96be2020-08-31 13:16:04 -0400772
773 // If we didn't detect an early return, there shouldn't be any returns in breakable
774 // constructs either.
John Stiles2d7973a2020-10-02 15:01:03 -0400775 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(*functionDef) == 0);
John Stiles44e96be2020-08-31 13:16:04 -0400776 return !hasEarlyReturn;
777 }
778 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
779 // 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 -0400780 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(*functionDef) > 0);
John Stiles44e96be2020-08-31 13:16:04 -0400781
782 // If we detected returns in breakable constructs, we should also detect an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400783 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(*functionDef));
John Stiles44e96be2020-08-31 13:16:04 -0400784 return !hasReturnInBreakableConstruct;
785}
786
John Stiles2d7973a2020-10-02 15:01:03 -0400787// A candidate function for inlining, containing everything that `inlineCall` needs.
788struct InlineCandidate {
789 SymbolTable* fSymbols; // the SymbolTable of the candidate
790 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
791 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
792 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
793 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
794 bool fIsLargeFunction; // does candidate exceed the inline threshold?
795};
John Stiles93442622020-09-11 12:11:27 -0400796
John Stiles2d7973a2020-10-02 15:01:03 -0400797struct InlineCandidateList {
798 std::vector<InlineCandidate> fCandidates;
799};
800
801class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400802public:
803 // A list of all the inlining candidates we found during analysis.
804 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400805
John Stiles70957c82020-10-02 16:42:10 -0400806 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
807 // the enclosing-statement stack.
808 std::vector<SymbolTable*> fSymbolTableStack;
809 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
810 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
811 // inliner might replace a statement with a block containing the statement.
812 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
813 // The function that we're currently processing (i.e. inlining into).
814 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400815
John Stiles70957c82020-10-02 16:42:10 -0400816 void visit(Program& program, InlineCandidateList* candidateList) {
817 fCandidateList = candidateList;
818 fSymbolTableStack.push_back(program.fSymbols.get());
John Stiles93442622020-09-11 12:11:27 -0400819
Brian Osman1179fcf2020-10-08 16:04:40 -0400820 for (const auto& pe : program.elements()) {
821 this->visitProgramElement(pe.get());
John Stiles93442622020-09-11 12:11:27 -0400822 }
823
John Stiles70957c82020-10-02 16:42:10 -0400824 fSymbolTableStack.pop_back();
825 fCandidateList = nullptr;
826 }
827
828 void visitProgramElement(ProgramElement* pe) {
829 switch (pe->kind()) {
830 case ProgramElement::Kind::kFunction: {
831 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
John Stilesa1e2b412020-10-20 14:51:28 -0400832 // Don't attempt to mutate any builtin functions. (If we stop cloning builtins into
833 // the program, this check can become an assertion.)
John Stiles607d36b2020-10-19 15:00:01 -0400834 if (!funcDef.isBuiltin()) {
835 fEnclosingFunction = &funcDef;
836 this->visitStatement(&funcDef.body());
837 }
John Stiles70957c82020-10-02 16:42:10 -0400838 break;
John Stiles93442622020-09-11 12:11:27 -0400839 }
John Stiles70957c82020-10-02 16:42:10 -0400840 default:
841 // The inliner can't operate outside of a function's scope.
842 break;
843 }
844 }
845
846 void visitStatement(std::unique_ptr<Statement>* stmt,
847 bool isViableAsEnclosingStatement = true) {
848 if (!*stmt) {
849 return;
John Stiles93442622020-09-11 12:11:27 -0400850 }
851
John Stiles70957c82020-10-02 16:42:10 -0400852 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
853 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400854
John Stiles70957c82020-10-02 16:42:10 -0400855 if (isViableAsEnclosingStatement) {
856 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400857 }
858
John Stiles70957c82020-10-02 16:42:10 -0400859 switch ((*stmt)->kind()) {
860 case Statement::Kind::kBreak:
861 case Statement::Kind::kContinue:
862 case Statement::Kind::kDiscard:
863 case Statement::Kind::kInlineMarker:
864 case Statement::Kind::kNop:
865 break;
866
867 case Statement::Kind::kBlock: {
868 Block& block = (*stmt)->as<Block>();
869 if (block.symbolTable()) {
870 fSymbolTableStack.push_back(block.symbolTable().get());
871 }
872
873 for (std::unique_ptr<Statement>& stmt : block.children()) {
874 this->visitStatement(&stmt);
875 }
876 break;
John Stiles93442622020-09-11 12:11:27 -0400877 }
John Stiles70957c82020-10-02 16:42:10 -0400878 case Statement::Kind::kDo: {
879 DoStatement& doStmt = (*stmt)->as<DoStatement>();
880 // The loop body is a candidate for inlining.
881 this->visitStatement(&doStmt.statement());
882 // The inliner isn't smart enough to inline the test-expression for a do-while
883 // loop at this time. There are two limitations:
884 // - We would need to insert the inlined-body block at the very end of the do-
885 // statement's inner fStatement. We don't support that today, but it's doable.
886 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
887 // would skip over the inlined block that evaluates the test expression. There
888 // isn't a good fix for this--any workaround would be more complex than the cost
889 // of a function call. However, loops that don't use `continue` would still be
890 // viable candidates for inlining.
891 break;
John Stiles93442622020-09-11 12:11:27 -0400892 }
John Stiles70957c82020-10-02 16:42:10 -0400893 case Statement::Kind::kExpression: {
894 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
895 this->visitExpression(&expr.expression());
896 break;
897 }
898 case Statement::Kind::kFor: {
899 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400900 if (forStmt.symbols()) {
901 fSymbolTableStack.push_back(forStmt.symbols().get());
John Stiles70957c82020-10-02 16:42:10 -0400902 }
903
904 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400905 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400906 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400907 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400908
909 // The inliner isn't smart enough to inline the test- or increment-expressions
910 // of a for loop loop at this time. There are a handful of limitations:
911 // - We would need to insert the test-expression block at the very beginning of the
912 // for-loop's inner fStatement, and the increment-expression block at the very
913 // end. We don't support that today, but it's doable.
914 // - The for-loop's built-in test-expression would need to be dropped entirely,
915 // and the loop would be halted via a break statement at the end of the inlined
916 // test-expression. This is again something we don't support today, but it could
917 // be implemented.
918 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
919 // that would skip over the inlined block that evaluates the increment expression.
920 // There isn't a good fix for this--any workaround would be more complex than the
921 // cost of a function call. However, loops that don't use `continue` would still
922 // be viable candidates for increment-expression inlining.
923 break;
924 }
925 case Statement::Kind::kIf: {
926 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -0400927 this->visitExpression(&ifStmt.test());
928 this->visitStatement(&ifStmt.ifTrue());
929 this->visitStatement(&ifStmt.ifFalse());
John Stiles70957c82020-10-02 16:42:10 -0400930 break;
931 }
932 case Statement::Kind::kReturn: {
933 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400934 this->visitExpression(&returnStmt.expression());
John Stiles70957c82020-10-02 16:42:10 -0400935 break;
936 }
937 case Statement::Kind::kSwitch: {
938 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400939 if (switchStmt.symbols()) {
940 fSymbolTableStack.push_back(switchStmt.symbols().get());
John Stiles70957c82020-10-02 16:42:10 -0400941 }
942
Ethan Nicholas01b05e52020-10-22 15:53:41 -0400943 this->visitExpression(&switchStmt.value());
John Stiles2d4f9592020-10-30 10:29:12 -0400944 for (const std::unique_ptr<SwitchCase>& switchCase : switchStmt.cases()) {
John Stiles70957c82020-10-02 16:42:10 -0400945 // The switch-case's fValue cannot be a FunctionCall; skip it.
John Stiles2d4f9592020-10-30 10:29:12 -0400946 for (std::unique_ptr<Statement>& caseBlock : switchCase->statements()) {
John Stiles70957c82020-10-02 16:42:10 -0400947 this->visitStatement(&caseBlock);
948 }
949 }
950 break;
951 }
952 case Statement::Kind::kVarDeclaration: {
953 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
954 // Don't need to scan the declaration's sizes; those are always IntLiterals.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400955 this->visitExpression(&varDeclStmt.value());
John Stiles70957c82020-10-02 16:42:10 -0400956 break;
957 }
John Stiles70957c82020-10-02 16:42:10 -0400958 case Statement::Kind::kWhile: {
959 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
960 // The loop body is a candidate for inlining.
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400961 this->visitStatement(&whileStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400962 // The inliner isn't smart enough to inline the test-expression for a while loop at
963 // this time. There are two limitations:
964 // - We would need to insert the inlined-body block at the very beginning of the
965 // while loop's inner fStatement. We don't support that today, but it's doable.
966 // - The while-loop's built-in test-expression would need to be replaced with a
967 // `true` BoolLiteral, and the loop would be halted via a break statement at the
968 // end of the inlined test-expression. This is again something we don't support
969 // today, but it could be implemented.
970 break;
971 }
972 default:
973 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400974 }
975
John Stiles70957c82020-10-02 16:42:10 -0400976 // Pop our symbol and enclosing-statement stacks.
977 fSymbolTableStack.resize(oldSymbolStackSize);
978 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
979 }
980
981 void visitExpression(std::unique_ptr<Expression>* expr) {
982 if (!*expr) {
983 return;
John Stiles93442622020-09-11 12:11:27 -0400984 }
John Stiles70957c82020-10-02 16:42:10 -0400985
986 switch ((*expr)->kind()) {
987 case Expression::Kind::kBoolLiteral:
988 case Expression::Kind::kDefined:
989 case Expression::Kind::kExternalValue:
990 case Expression::Kind::kFieldAccess:
991 case Expression::Kind::kFloatLiteral:
992 case Expression::Kind::kFunctionReference:
993 case Expression::Kind::kIntLiteral:
994 case Expression::Kind::kNullLiteral:
995 case Expression::Kind::kSetting:
996 case Expression::Kind::kTypeReference:
997 case Expression::Kind::kVariableReference:
998 // Nothing to scan here.
999 break;
1000
1001 case Expression::Kind::kBinary: {
1002 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001003 this->visitExpression(&binaryExpr.left());
John Stiles70957c82020-10-02 16:42:10 -04001004
1005 // Logical-and and logical-or binary expressions do not inline the right side,
1006 // because that would invalidate short-circuiting. That is, when evaluating
1007 // expressions like these:
1008 // (false && x()) // always false
1009 // (true || y()) // always true
1010 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1011 // enforce that rule is to avoid inlining the right side entirely. However, it is
1012 // safe for other types of binary expression to inline both sides.
1013 Token::Kind op = binaryExpr.getOperator();
1014 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1015 op == Token::Kind::TK_LOGICALOR);
1016 if (!shortCircuitable) {
John Stiles2d4f9592020-10-30 10:29:12 -04001017 this->visitExpression(&binaryExpr.right());
John Stiles70957c82020-10-02 16:42:10 -04001018 }
1019 break;
1020 }
1021 case Expression::Kind::kConstructor: {
1022 Constructor& constructorExpr = (*expr)->as<Constructor>();
1023 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1024 this->visitExpression(&arg);
1025 }
1026 break;
1027 }
1028 case Expression::Kind::kExternalFunctionCall: {
1029 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1030 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1031 this->visitExpression(&arg);
1032 }
1033 break;
1034 }
1035 case Expression::Kind::kFunctionCall: {
1036 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001037 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001038 this->visitExpression(&arg);
1039 }
1040 this->addInlineCandidate(expr);
1041 break;
1042 }
1043 case Expression::Kind::kIndex:{
1044 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001045 this->visitExpression(&indexExpr.base());
1046 this->visitExpression(&indexExpr.index());
John Stiles70957c82020-10-02 16:42:10 -04001047 break;
1048 }
1049 case Expression::Kind::kPostfix: {
1050 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001051 this->visitExpression(&postfixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001052 break;
1053 }
1054 case Expression::Kind::kPrefix: {
1055 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001056 this->visitExpression(&prefixExpr.operand());
John Stiles70957c82020-10-02 16:42:10 -04001057 break;
1058 }
1059 case Expression::Kind::kSwizzle: {
1060 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001061 this->visitExpression(&swizzleExpr.base());
John Stiles70957c82020-10-02 16:42:10 -04001062 break;
1063 }
1064 case Expression::Kind::kTernary: {
1065 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1066 // The test expression is a candidate for inlining.
Ethan Nicholasdd218162020-10-08 05:48:01 -04001067 this->visitExpression(&ternaryExpr.test());
John Stiles70957c82020-10-02 16:42:10 -04001068 // The true- and false-expressions cannot be inlined, because we are only allowed to
1069 // evaluate one side.
1070 break;
1071 }
1072 default:
1073 SkUNREACHABLE;
1074 }
1075 }
1076
1077 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1078 fCandidateList->fCandidates.push_back(
1079 InlineCandidate{fSymbolTableStack.back(),
1080 find_parent_statement(fEnclosingStmtStack),
1081 fEnclosingStmtStack.back(),
1082 candidate,
1083 fEnclosingFunction,
1084 /*isLargeFunction=*/false});
1085 }
John Stiles2d7973a2020-10-02 15:01:03 -04001086};
John Stiles93442622020-09-11 12:11:27 -04001087
John Stiles2d7973a2020-10-02 15:01:03 -04001088bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
John Stiles1c03d332020-10-13 10:30:23 -04001089 const FunctionDeclaration& funcDecl =
1090 (*candidate.fCandidateExpr)->as<FunctionCall>().function();
John Stiles915a38c2020-09-14 09:38:13 -04001091
John Stiles1c03d332020-10-13 10:30:23 -04001092 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001093 if (wasInserted) {
1094 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
John Stiles1c03d332020-10-13 10:30:23 -04001095 iter->second = this->isSafeToInline(funcDecl.definition()) &&
1096 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001097 }
1098
John Stiles2d7973a2020-10-02 15:01:03 -04001099 return iter->second;
1100}
1101
John Stiles1c03d332020-10-13 10:30:23 -04001102bool Inliner::isLargeFunction(const FunctionDefinition* functionDef) {
1103 return Analysis::NodeCountExceeds(*functionDef, fSettings->fInlineThreshold);
1104}
John Stiles2d7973a2020-10-02 15:01:03 -04001105
John Stiles1c03d332020-10-13 10:30:23 -04001106bool Inliner::isLargeFunction(const InlineCandidate& candidate, LargeFunctionCache* cache) {
1107 const FunctionDeclaration& funcDecl =
1108 (*candidate.fCandidateExpr)->as<FunctionCall>().function();
1109
1110 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
John Stiles2d7973a2020-10-02 15:01:03 -04001111 if (wasInserted) {
John Stiles1c03d332020-10-13 10:30:23 -04001112 iter->second = this->isLargeFunction(funcDecl.definition());
John Stiles2d7973a2020-10-02 15:01:03 -04001113 }
1114
1115 return iter->second;
1116}
1117
1118void Inliner::buildCandidateList(Program& program, InlineCandidateList* candidateList) {
1119 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1120 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1121 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1122 // `const T&`.
1123 InlineCandidateAnalyzer analyzer;
1124 analyzer.visit(program, candidateList);
1125
1126 // Remove candidates that are not safe to inline.
1127 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
1128 InlinabilityCache cache;
1129 candidates.erase(std::remove_if(candidates.begin(),
1130 candidates.end(),
1131 [&](const InlineCandidate& candidate) {
1132 return !this->candidateCanBeInlined(candidate, &cache);
1133 }),
1134 candidates.end());
1135
1136 // Determine whether each candidate function exceeds our inlining size threshold or not. These
1137 // can still be valid candidates if they are only called one time, so we don't remove them from
1138 // the candidate list, but they will not be inlined if they're called more than once.
1139 LargeFunctionCache largeFunctionCache;
1140 for (InlineCandidate& candidate : candidates) {
1141 candidate.fIsLargeFunction = this->isLargeFunction(candidate, &largeFunctionCache);
1142 }
1143}
1144
1145bool Inliner::analyze(Program& program) {
John Stilesd34d56e2020-10-12 12:04:47 -04001146 // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1147 if (fSettings->fInlineThreshold <= 0) {
1148 return false;
1149 }
1150
Brian Osman010ce6a2020-10-19 16:34:10 -04001151 ProgramUsage* usage = program.fUsage.get();
John Stiles2d7973a2020-10-02 15:01:03 -04001152 InlineCandidateList candidateList;
1153 this->buildCandidateList(program, &candidateList);
1154
John Stiles915a38c2020-09-14 09:38:13 -04001155 // Inline the candidates where we've determined that it's safe to do so.
1156 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1157 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001158 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001159 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
Brian Osman010ce6a2020-10-19 16:34:10 -04001160 const FunctionDeclaration& funcDecl = funcCall.function();
John Stiles915a38c2020-09-14 09:38:13 -04001161
John Stiles2d7973a2020-10-02 15:01:03 -04001162 // If the function is large, not marked `inline`, and is called more than once, it's a bad
1163 // idea to inline it.
1164 if (candidate.fIsLargeFunction &&
Brian Osman010ce6a2020-10-19 16:34:10 -04001165 !(funcDecl.modifiers().fFlags & Modifiers::kInline_Flag) && usage->get(funcDecl) > 1) {
John Stiles915a38c2020-09-14 09:38:13 -04001166 continue;
1167 }
1168
1169 // Inlining two expressions using the same enclosing statement in the same inlining pass
1170 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1171 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1172 if (!inserted) {
1173 continue;
1174 }
1175
1176 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001177 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001178 &candidate.fEnclosingFunction->declaration());
John Stiles915a38c2020-09-14 09:38:13 -04001179 if (inlinedCall.fInlinedBody) {
1180 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001181 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001182
Brian Osman010ce6a2020-10-19 16:34:10 -04001183 // Add references within the inlined body
1184 usage->add(inlinedCall.fInlinedBody.get());
1185
John Stiles915a38c2020-09-14 09:38:13 -04001186 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1187 // function, then replace the enclosing statement with that Block.
1188 // Before:
1189 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1190 // fEnclosingStmt = stmt4
1191 // After:
1192 // fInlinedBody = null
1193 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001194 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001195 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1196 }
1197
1198 // Replace the candidate function call with our replacement expression.
Brian Osman010ce6a2020-10-19 16:34:10 -04001199 usage->replace(candidate.fCandidateExpr->get(), inlinedCall.fReplacementExpr.get());
John Stiles915a38c2020-09-14 09:38:13 -04001200 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1201 madeChanges = true;
1202
1203 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1204 // remain valid.
1205 }
1206
1207 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001208}
1209
John Stiles44e96be2020-08-31 13:16:04 -04001210} // namespace SkSL