blob: 26e6e98d988d5a475053544a1b59cbc0d3bc257b [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"
52#include "src/sksl/ir/SkSLVarDeclarationsStatement.h"
53#include "src/sksl/ir/SkSLVariable.h"
54#include "src/sksl/ir/SkSLVariableReference.h"
55#include "src/sksl/ir/SkSLWhileStatement.h"
56
57namespace SkSL {
58namespace {
59
John Stiles44dff4f2020-09-21 12:28:01 -040060static bool contains_returns_above_limit(const FunctionDefinition& funcDef, int limit) {
61 class CountReturnsWithLimit : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040062 public:
John Stiles44dff4f2020-09-21 12:28:01 -040063 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
John Stiles44e96be2020-08-31 13:16:04 -040064 this->visitProgramElement(funcDef);
65 }
66
67 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040068 switch (stmt.kind()) {
69 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040070 ++fNumReturns;
John Stiles44dff4f2020-09-21 12:28:01 -040071 return (fNumReturns > fLimit) || INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040072
73 default:
John Stiles93442622020-09-11 12:11:27 -040074 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040075 }
76 }
77
78 int fNumReturns = 0;
John Stiles44dff4f2020-09-21 12:28:01 -040079 int fLimit = 0;
John Stiles44e96be2020-08-31 13:16:04 -040080 using INHERITED = ProgramVisitor;
81 };
82
John Stiles44dff4f2020-09-21 12:28:01 -040083 return CountReturnsWithLimit{funcDef, limit}.fNumReturns > limit;
John Stiles44e96be2020-08-31 13:16:04 -040084}
85
86static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
87 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
88 public:
89 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
90 this->visitProgramElement(funcDef);
91 }
92
93 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040094 switch (stmt.kind()) {
95 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040096 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040097 const auto& block = stmt.as<Block>();
98 return block.children().size() &&
99 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -0400100 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400101 case Statement::Kind::kSwitch:
102 case Statement::Kind::kWhile:
103 case Statement::Kind::kDo:
104 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -0400105 // Don't introspect switches or loop structures at all.
106 return false;
107
Ethan Nicholase6592142020-09-08 10:22:09 -0400108 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400109 ++fNumReturns;
110 [[fallthrough]];
111
112 default:
John Stiles93442622020-09-11 12:11:27 -0400113 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400114 }
115 }
116
117 int fNumReturns = 0;
118 using INHERITED = ProgramVisitor;
119 };
120
121 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
122}
123
124static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
125 class CountReturnsInBreakableConstructs : public ProgramVisitor {
126 public:
127 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
128 this->visitProgramElement(funcDef);
129 }
130
131 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400132 switch (stmt.kind()) {
133 case Statement::Kind::kSwitch:
134 case Statement::Kind::kWhile:
135 case Statement::Kind::kDo:
136 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400137 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400138 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400139 --fInsideBreakableConstruct;
140 return result;
141 }
142
Ethan Nicholase6592142020-09-08 10:22:09 -0400143 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400144 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
145 [[fallthrough]];
146
147 default:
John Stiles93442622020-09-11 12:11:27 -0400148 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400149 }
150 }
151
152 int fNumReturns = 0;
153 int fInsideBreakableConstruct = 0;
154 using INHERITED = ProgramVisitor;
155 };
156
157 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
158}
159
160static bool has_early_return(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400161 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
John Stiles44dff4f2020-09-21 12:28:01 -0400162 return contains_returns_above_limit(funcDef, returnsAtEndOfControlFlow);
John Stiles44e96be2020-08-31 13:16:04 -0400163}
164
John Stiles991b09d2020-09-10 13:33:40 -0400165static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
166 class ContainsRecursiveCall : public ProgramVisitor {
167 public:
168 bool visit(const FunctionDeclaration& funcDecl) {
169 fFuncDecl = &funcDecl;
170 return funcDecl.fDefinition ? this->visitProgramElement(*funcDecl.fDefinition)
171 : false;
172 }
173
174 bool visitExpression(const Expression& expr) override {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400175 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().function().matches(*fFuncDecl)) {
John Stiles991b09d2020-09-10 13:33:40 -0400176 return true;
177 }
178 return INHERITED::visitExpression(expr);
179 }
180
181 bool visitStatement(const Statement& stmt) override {
182 if (stmt.is<InlineMarker>() && stmt.as<InlineMarker>().fFuncDecl->matches(*fFuncDecl)) {
183 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>() ||
251 (argument.is<Swizzle>() && is_trivial_argument(*argument.as<Swizzle>().fBase)) ||
252 (argument.is<FieldAccess>() && is_trivial_argument(*argument.as<FieldAccess>().fBase)) ||
John Stiles80ccdbd2020-09-30 11:58:16 -0400253 (argument.is<Constructor>() &&
254 argument.as<Constructor>().arguments().size() == 1 &&
255 is_trivial_argument(*argument.as<Constructor>().arguments().front())) ||
John Stiles44733aa2020-09-29 17:42:23 -0400256 (argument.is<IndexExpression>() &&
257 argument.as<IndexExpression>().fIndex->is<IntLiteral>() &&
258 is_trivial_argument(*argument.as<IndexExpression>().fBase));
259}
260
John Stiles44e96be2020-08-31 13:16:04 -0400261} // namespace
262
John Stilesb61ee902020-09-21 12:26:59 -0400263void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
264 // No changes necessary if this statement isn't actually a block.
265 if (!inlinedBody || !inlinedBody->is<Block>()) {
266 return;
267 }
268
269 // No changes necessary if the parent statement doesn't require a scope.
270 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
271 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
272 return;
273 }
274
275 Block& block = inlinedBody->as<Block>();
276
277 // The inliner will create inlined function bodies as a Block containing multiple statements,
278 // but no scope. Normally, this is fine, but if this block is used as the statement for a
279 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
280 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
281 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
282 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
283 // absorbing the following statement into our loop--so we also add a scope to these.
284 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400285 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400286 // We found an explicit scope; all is well.
287 return;
288 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400289 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400290 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
291 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400292 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400293 return;
294 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400295 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400296 // This block has exactly one thing inside, and it's not another block. No need to scope
297 // it.
298 return;
299 }
300 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400301 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400302 }
303}
304
John Stiles44e96be2020-08-31 13:16:04 -0400305void Inliner::reset(const Context& context, const Program::Settings& settings) {
306 fContext = &context;
307 fSettings = &settings;
308 fInlineVarCounter = 0;
309}
310
John Stilesc75abb82020-09-14 18:24:12 -0400311String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
312 // If the base name starts with an underscore, like "_coords", we can't append another
313 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
314 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
315 // putting in this special case.
316 const char* splitter = baseName.startsWith("_") ? "" : "_";
317
318 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
319 // we're not reusing an existing name. (Note that within a single compilation pass, this check
320 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
321 String uniqueName;
322 for (;;) {
323 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
324 StringFragment frag{uniqueName.data(), uniqueName.length()};
325 if ((*symbolTable)[frag] == nullptr) {
326 break;
327 }
328 }
329
330 return uniqueName;
331}
332
John Stiles44e96be2020-08-31 13:16:04 -0400333std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
334 VariableRewriteMap* varMap,
335 const Expression& expression) {
336 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
337 if (e) {
338 return this->inlineExpression(offset, varMap, *e);
339 }
340 return nullptr;
341 };
342 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
343 -> std::vector<std::unique_ptr<Expression>> {
344 std::vector<std::unique_ptr<Expression>> args;
345 args.reserve(originalArgs.size());
346 for (const std::unique_ptr<Expression>& arg : originalArgs) {
347 args.push_back(expr(arg));
348 }
349 return args;
350 };
351
Ethan Nicholase6592142020-09-08 10:22:09 -0400352 switch (expression.kind()) {
353 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400354 const BinaryExpression& b = expression.as<BinaryExpression>();
355 return std::make_unique<BinaryExpression>(offset,
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400356 expr(b.leftPointer()),
357 b.getOperator(),
358 expr(b.rightPointer()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400359 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400360 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400361 case Expression::Kind::kBoolLiteral:
362 case Expression::Kind::kIntLiteral:
363 case Expression::Kind::kFloatLiteral:
364 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400365 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400366 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400367 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400368 return std::make_unique<Constructor>(offset, &constructor.type(),
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400369 argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400370 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400371 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400372 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400373 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.type(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400374 externalCall.function(),
375 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400376 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400377 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400378 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400379 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400380 const FieldAccess& f = expression.as<FieldAccess>();
381 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
382 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400383 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400384 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400385 return std::make_unique<FunctionCall>(offset, &funcCall.type(), &funcCall.function(),
386 argList(funcCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400387 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400388 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400389 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400390 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400391 const IndexExpression& idx = expression.as<IndexExpression>();
392 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
393 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400394 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400395 const PrefixExpression& p = expression.as<PrefixExpression>();
396 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
397 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400398 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400399 const PostfixExpression& p = expression.as<PostfixExpression>();
400 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
401 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400402 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400403 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400404 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400405 const Swizzle& s = expression.as<Swizzle>();
406 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
407 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400408 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400409 const TernaryExpression& t = expression.as<TernaryExpression>();
410 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
411 expr(t.fIfTrue), expr(t.fIfFalse));
412 }
Brian Osman83ba9302020-09-11 13:33:46 -0400413 case Expression::Kind::kTypeReference:
414 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400415 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400416 const VariableReference& v = expression.as<VariableReference>();
John Stilese41b4ee2020-09-28 12:28:16 -0400417 auto varMapIter = varMap->find(v.fVariable);
418 if (varMapIter != varMap->end()) {
419 return clone_with_ref_kind(*varMapIter->second, v.fRefKind);
John Stiles44e96be2020-08-31 13:16:04 -0400420 }
421 return v.clone();
422 }
423 default:
424 SkASSERT(false);
425 return nullptr;
426 }
427}
428
429std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
430 VariableRewriteMap* varMap,
431 SymbolTable* symbolTableForStatement,
John Stilese41b4ee2020-09-28 12:28:16 -0400432 const Expression* resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400433 bool haveEarlyReturns,
Brian Osman3887a012020-09-30 13:22:27 -0400434 const Statement& statement,
435 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400436 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
437 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400438 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
Brian Osman3887a012020-09-30 13:22:27 -0400439 haveEarlyReturns, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400440 }
441 return nullptr;
442 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400443 auto blockStmts = [&](const Block& block) {
444 std::vector<std::unique_ptr<Statement>> result;
445 for (const std::unique_ptr<Statement>& child : block.children()) {
446 result.push_back(stmt(child));
447 }
448 return result;
449 };
John Stiles44e96be2020-08-31 13:16:04 -0400450 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
451 std::vector<std::unique_ptr<Statement>> result;
452 for (const auto& s : ss) {
453 result.push_back(stmt(s));
454 }
455 return result;
456 };
457 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
458 if (e) {
459 return this->inlineExpression(offset, varMap, *e);
460 }
461 return nullptr;
462 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400463 switch (statement.kind()) {
464 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400465 const Block& b = statement.as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400466 return std::make_unique<Block>(offset, blockStmts(b), b.symbolTable(), b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400467 }
468
Ethan Nicholase6592142020-09-08 10:22:09 -0400469 case Statement::Kind::kBreak:
470 case Statement::Kind::kContinue:
471 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400472 return statement.clone();
473
Ethan Nicholase6592142020-09-08 10:22:09 -0400474 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400475 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400476 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400477 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400478 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400479 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400480 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400481 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400482 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400483 const ForStatement& f = statement.as<ForStatement>();
484 // need to ensure initializer is evaluated first so that we've already remapped its
485 // declarations by the time we evaluate test & next
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400486 std::unique_ptr<Statement> initializer = stmt(f.initializer());
487 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.test()),
488 expr(f.next()), stmt(f.statement()), f.symbols());
John Stiles44e96be2020-08-31 13:16:04 -0400489 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400490 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400491 const IfStatement& i = statement.as<IfStatement>();
492 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
493 stmt(i.fIfTrue), stmt(i.fIfFalse));
494 }
John Stiles98c1f822020-09-09 14:18:53 -0400495 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400496 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400497 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400498 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400499 const ReturnStatement& r = statement.as<ReturnStatement>();
500 if (r.fExpression) {
John Stilese41b4ee2020-09-28 12:28:16 -0400501 SkASSERT(resultExpr);
John Stilesa5f3c312020-09-22 12:05:16 -0400502 auto assignment =
503 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
504 offset,
John Stilese41b4ee2020-09-28 12:28:16 -0400505 clone_with_ref_kind(*resultExpr, VariableReference::kWrite_RefKind),
John Stilesa5f3c312020-09-22 12:05:16 -0400506 Token::Kind::TK_EQ,
507 expr(r.fExpression),
John Stilese41b4ee2020-09-28 12:28:16 -0400508 &resultExpr->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400509 if (haveEarlyReturns) {
510 std::vector<std::unique_ptr<Statement>> block;
511 block.push_back(std::move(assignment));
512 block.emplace_back(new BreakStatement(offset));
513 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
514 /*isScope=*/true);
515 } else {
516 return std::move(assignment);
517 }
518 } else {
519 if (haveEarlyReturns) {
520 return std::make_unique<BreakStatement>(offset);
521 } else {
522 return std::make_unique<Nop>();
523 }
524 }
525 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400526 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400527 const SwitchStatement& ss = statement.as<SwitchStatement>();
528 std::vector<std::unique_ptr<SwitchCase>> cases;
529 for (const auto& sc : ss.fCases) {
530 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
531 stmts(sc->fStatements)));
532 }
533 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
534 std::move(cases), ss.fSymbols);
535 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400536 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400537 const VarDeclaration& decl = statement.as<VarDeclaration>();
538 std::vector<std::unique_ptr<Expression>> sizes;
539 for (const auto& size : decl.fSizes) {
540 sizes.push_back(expr(size));
541 }
542 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
543 const Variable* old = decl.fVar;
John Stilesc75abb82020-09-14 18:24:12 -0400544 // We assign unique names to inlined variables--scopes hide most of the problems in this
545 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
546 // names are important.
547 auto name = std::make_unique<String>(
Ethan Nicholase2c49992020-10-05 11:49:11 -0400548 this->uniqueNameForInlineVar(String(old->name()), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400549 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas30d30222020-09-11 12:27:26 -0400550 const Type* typePtr = copy_if_needed(&old->type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400551 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
552 std::make_unique<Variable>(offset,
553 old->fModifiers,
554 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400555 typePtr,
Brian Osman3887a012020-09-30 13:22:27 -0400556 isBuiltinCode,
John Stiles44e96be2020-08-31 13:16:04 -0400557 old->fStorage,
558 initialValue.get()));
John Stilese41b4ee2020-09-28 12:28:16 -0400559 (*varMap)[old] = std::make_unique<VariableReference>(offset, clone);
John Stiles44e96be2020-08-31 13:16:04 -0400560 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
561 std::move(initialValue));
562 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400563 case Statement::Kind::kVarDeclarations: {
John Stiles44e96be2020-08-31 13:16:04 -0400564 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
Brian Osman347e5dc2020-10-05 15:56:44 -0400565 std::vector<std::unique_ptr<Statement>> vars;
566 vars.reserve(decls.fVars.size());
John Stiles44e96be2020-08-31 13:16:04 -0400567 for (const auto& var : decls.fVars) {
Brian Osman347e5dc2020-10-05 15:56:44 -0400568 vars.push_back(stmt(var));
John Stiles44e96be2020-08-31 13:16:04 -0400569 }
570 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
571 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
572 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
573 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400574 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400575 const WhileStatement& w = statement.as<WhileStatement>();
576 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
577 }
578 default:
579 SkASSERT(false);
580 return nullptr;
581 }
582}
583
John Stiles6eadf132020-09-08 10:16:10 -0400584Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
Brian Osman3887a012020-09-30 13:22:27 -0400585 SymbolTable* symbolTableForCall,
586 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400587 // Inlining is more complicated here than in a typical compiler, because we have to have a
588 // high-level IR and can't just drop statements into the middle of an expression or even use
589 // gotos.
590 //
591 // Since we can't insert statements into an expression, we run the inline function as extra
592 // statements before the statement we're currently processing, relying on a lack of execution
593 // order guarantees. Since we can't use gotos (which are normally used to replace return
594 // statements), we wrap the whole function in a loop and use break statements to jump to the
595 // end.
596 SkASSERT(fSettings);
597 SkASSERT(fContext);
598 SkASSERT(call);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400599 SkASSERT(this->isSafeToInline(call->function().fDefinition));
John Stiles44e96be2020-08-31 13:16:04 -0400600
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400601 std::vector<std::unique_ptr<Expression>>& arguments = call->arguments();
John Stiles6eadf132020-09-08 10:16:10 -0400602 const int offset = call->fOffset;
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400603 const FunctionDefinition& function = *call->function().fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400604 const bool hasEarlyReturn = has_early_return(function);
605
John Stiles44e96be2020-08-31 13:16:04 -0400606 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400607 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
608 std::vector<std::unique_ptr<Statement>>{},
609 /*symbols=*/nullptr,
610 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400611
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400612 Block& inlinedBody = *inlinedCall.fInlinedBody;
613 inlinedBody.children().reserve(1 + // Inline marker
614 1 + // Result variable
615 arguments.size() + // Function arguments (passing in)
John Stilese41b4ee2020-09-28 12:28:16 -0400616 arguments.size() + // Function arguments (copy out-params back)
617 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400618
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400619 inlinedBody.children().push_back(std::make_unique<InlineMarker>(call->function()));
John Stiles44e96be2020-08-31 13:16:04 -0400620
John Stilese41b4ee2020-09-28 12:28:16 -0400621 auto makeInlineVar =
622 [&](const String& baseName, const Type* type, Modifiers modifiers,
623 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400624 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
625 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
626 // somewhere during compilation.
627 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400628 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400629 type = fContext->fFloat_Type.get();
630 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400631 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400632 type = fContext->fInt_Type.get();
633 }
634
John Stilesc75abb82020-09-14 18:24:12 -0400635 // Provide our new variable with a unique name, and add it to our symbol table.
636 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400637 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
638 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400639 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
640
641 // Add our new variable to the symbol table.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400642 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
Brian Osman3887a012020-09-30 13:22:27 -0400643 caller->fBuiltin, Variable::kLocal_Storage,
644 initialValue->get());
John Stiles44e96be2020-08-31 13:16:04 -0400645 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
646
647 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
648 // initial value).
Brian Osman347e5dc2020-10-05 15:56:44 -0400649 std::vector<std::unique_ptr<Statement>> variables;
John Stiles44e96be2020-08-31 13:16:04 -0400650 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
651 variables.push_back(std::make_unique<VarDeclaration>(
652 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
653 (*initialValue)->clone()));
654 } else {
655 variables.push_back(std::make_unique<VarDeclaration>(
656 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
657 std::move(*initialValue)));
658 }
659
660 // Add the new variable-declaration statement to our block of extra statements.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400661 inlinedBody.children().push_back(std::make_unique<VarDeclarationsStatement>(
John Stilesa003e812020-09-11 09:43:49 -0400662 std::make_unique<VarDeclarations>(offset, type, std::move(variables))));
John Stiles44e96be2020-08-31 13:16:04 -0400663
John Stilese41b4ee2020-09-28 12:28:16 -0400664 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400665 };
666
667 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400668 std::unique_ptr<Expression> resultExpr;
John Stiles44e96be2020-08-31 13:16:04 -0400669 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400670 std::unique_ptr<Expression> noInitialValue;
Ethan Nicholase2c49992020-10-05 11:49:11 -0400671 resultExpr = makeInlineVar(String(function.fDeclaration.name()),
John Stilese41b4ee2020-09-28 12:28:16 -0400672 &function.fDeclaration.fReturnType,
673 Modifiers{}, &noInitialValue);
674 }
John Stiles44e96be2020-08-31 13:16:04 -0400675
676 // Create variables in the extra statements to hold the arguments, and assign the arguments to
677 // them.
678 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400679 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400680 for (int i = 0; i < (int) arguments.size(); ++i) {
681 const Variable* param = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400682 bool isOutParam = param->fModifiers.fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400683
John Stiles44733aa2020-09-29 17:42:23 -0400684 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
685 if (is_trivial_argument(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400686 // ... and it's an `out` param, or it isn't written to within the inline function...
687 if (isOutParam || !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400688 // ... we don't need to copy it at all! We can just use the existing expression.
689 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400690 continue;
691 }
692 }
693
John Stilese41b4ee2020-09-28 12:28:16 -0400694 if (isOutParam) {
695 argsToCopyBack.push_back(i);
696 }
697
Ethan Nicholase2c49992020-10-05 11:49:11 -0400698 varMap[param] = makeInlineVar(String(param->name()), &arguments[i]->type(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400699 param->fModifiers, &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400700 }
701
702 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400703 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400704 inlineBlock->children().reserve(body.children().size());
705 for (const std::unique_ptr<Statement>& stmt : body.children()) {
Brian Osman3887a012020-09-30 13:22:27 -0400706 inlineBlock->children().push_back(this->inlineStatement(offset, &varMap, symbolTableForCall,
707 resultExpr.get(), hasEarlyReturn,
708 *stmt, caller->fBuiltin));
John Stiles44e96be2020-08-31 13:16:04 -0400709 }
710 if (hasEarlyReturn) {
711 // Since we output to backends that don't have a goto statement (which would normally be
712 // used to perform an early return), we fake it by wrapping the function in a
713 // do { } while (false); and then use break statements to jump to the end in order to
714 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400715 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400716 /*offset=*/-1,
717 std::move(inlineBlock),
718 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
719 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400720 // No early returns, so we can just dump the code in. We still need to keep the block so we
721 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400722 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400723 }
724
John Stilese41b4ee2020-09-28 12:28:16 -0400725 // Copy back the values of `out` parameters into their real destinations.
726 for (int i : argsToCopyBack) {
John Stiles44e96be2020-08-31 13:16:04 -0400727 const Variable* p = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400728 SkASSERT(varMap.find(p) != varMap.end());
729 inlinedBody.children().push_back(
730 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
731 offset,
732 clone_with_ref_kind(*arguments[i], VariableReference::kWrite_RefKind),
733 Token::Kind::TK_EQ,
734 std::move(varMap[p]),
735 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400736 }
737
John Stilese41b4ee2020-09-28 12:28:16 -0400738 if (resultExpr != nullptr) {
739 // Return our result variable as our replacement expression.
740 SkASSERT(resultExpr->as<VariableReference>().fRefKind == VariableReference::kRead_RefKind);
741 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400742 } else {
743 // It's a void function, so it doesn't actually result in anything, but we have to return
744 // something non-null as a standin.
745 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
746 /*value=*/false);
747 }
748
John Stiles44e96be2020-08-31 13:16:04 -0400749 return inlinedCall;
750}
751
John Stiles2d7973a2020-10-02 15:01:03 -0400752bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400753 SkASSERT(fSettings);
754
John Stiles2d7973a2020-10-02 15:01:03 -0400755 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400756 // Can't inline something if we don't actually have its definition.
757 return false;
758 }
John Stiles2d7973a2020-10-02 15:01:03 -0400759
John Stiles44e96be2020-08-31 13:16:04 -0400760 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
761 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
762 // can't inline functions that have an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400763 bool hasEarlyReturn = has_early_return(*functionDef);
John Stiles44e96be2020-08-31 13:16:04 -0400764
765 // If we didn't detect an early return, there shouldn't be any returns in breakable
766 // constructs either.
John Stiles2d7973a2020-10-02 15:01:03 -0400767 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(*functionDef) == 0);
John Stiles44e96be2020-08-31 13:16:04 -0400768 return !hasEarlyReturn;
769 }
770 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
771 // 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 -0400772 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(*functionDef) > 0);
John Stiles44e96be2020-08-31 13:16:04 -0400773
774 // If we detected returns in breakable constructs, we should also detect an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400775 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(*functionDef));
John Stiles44e96be2020-08-31 13:16:04 -0400776 return !hasReturnInBreakableConstruct;
777}
778
John Stiles2d7973a2020-10-02 15:01:03 -0400779// A candidate function for inlining, containing everything that `inlineCall` needs.
780struct InlineCandidate {
781 SymbolTable* fSymbols; // the SymbolTable of the candidate
782 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
783 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
784 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
785 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
786 bool fIsLargeFunction; // does candidate exceed the inline threshold?
787};
John Stiles93442622020-09-11 12:11:27 -0400788
John Stiles2d7973a2020-10-02 15:01:03 -0400789struct InlineCandidateList {
790 std::vector<InlineCandidate> fCandidates;
791};
792
793class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400794public:
795 // A list of all the inlining candidates we found during analysis.
796 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400797
John Stiles70957c82020-10-02 16:42:10 -0400798 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
799 // the enclosing-statement stack.
800 std::vector<SymbolTable*> fSymbolTableStack;
801 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
802 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
803 // inliner might replace a statement with a block containing the statement.
804 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
805 // The function that we're currently processing (i.e. inlining into).
806 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400807
John Stiles70957c82020-10-02 16:42:10 -0400808 void visit(Program& program, InlineCandidateList* candidateList) {
809 fCandidateList = candidateList;
810 fSymbolTableStack.push_back(program.fSymbols.get());
John Stiles93442622020-09-11 12:11:27 -0400811
John Stiles70957c82020-10-02 16:42:10 -0400812 for (ProgramElement& pe : program) {
813 this->visitProgramElement(&pe);
John Stiles93442622020-09-11 12:11:27 -0400814 }
815
John Stiles70957c82020-10-02 16:42:10 -0400816 fSymbolTableStack.pop_back();
817 fCandidateList = nullptr;
818 }
819
820 void visitProgramElement(ProgramElement* pe) {
821 switch (pe->kind()) {
822 case ProgramElement::Kind::kFunction: {
823 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
824 fEnclosingFunction = &funcDef;
825 this->visitStatement(&funcDef.fBody);
826 break;
John Stiles93442622020-09-11 12:11:27 -0400827 }
John Stiles70957c82020-10-02 16:42:10 -0400828 default:
829 // The inliner can't operate outside of a function's scope.
830 break;
831 }
832 }
833
834 void visitStatement(std::unique_ptr<Statement>* stmt,
835 bool isViableAsEnclosingStatement = true) {
836 if (!*stmt) {
837 return;
John Stiles93442622020-09-11 12:11:27 -0400838 }
839
John Stiles70957c82020-10-02 16:42:10 -0400840 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
841 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400842
John Stiles70957c82020-10-02 16:42:10 -0400843 if (isViableAsEnclosingStatement) {
844 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400845 }
846
John Stiles70957c82020-10-02 16:42:10 -0400847 switch ((*stmt)->kind()) {
848 case Statement::Kind::kBreak:
849 case Statement::Kind::kContinue:
850 case Statement::Kind::kDiscard:
851 case Statement::Kind::kInlineMarker:
852 case Statement::Kind::kNop:
853 break;
854
855 case Statement::Kind::kBlock: {
856 Block& block = (*stmt)->as<Block>();
857 if (block.symbolTable()) {
858 fSymbolTableStack.push_back(block.symbolTable().get());
859 }
860
861 for (std::unique_ptr<Statement>& stmt : block.children()) {
862 this->visitStatement(&stmt);
863 }
864 break;
John Stiles93442622020-09-11 12:11:27 -0400865 }
John Stiles70957c82020-10-02 16:42:10 -0400866 case Statement::Kind::kDo: {
867 DoStatement& doStmt = (*stmt)->as<DoStatement>();
868 // The loop body is a candidate for inlining.
869 this->visitStatement(&doStmt.statement());
870 // The inliner isn't smart enough to inline the test-expression for a do-while
871 // loop at this time. There are two limitations:
872 // - We would need to insert the inlined-body block at the very end of the do-
873 // statement's inner fStatement. We don't support that today, but it's doable.
874 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
875 // would skip over the inlined block that evaluates the test expression. There
876 // isn't a good fix for this--any workaround would be more complex than the cost
877 // of a function call. However, loops that don't use `continue` would still be
878 // viable candidates for inlining.
879 break;
John Stiles93442622020-09-11 12:11:27 -0400880 }
John Stiles70957c82020-10-02 16:42:10 -0400881 case Statement::Kind::kExpression: {
882 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
883 this->visitExpression(&expr.expression());
884 break;
885 }
886 case Statement::Kind::kFor: {
887 ForStatement& forStmt = (*stmt)->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400888 if (forStmt.symbols()) {
889 fSymbolTableStack.push_back(forStmt.symbols().get());
John Stiles70957c82020-10-02 16:42:10 -0400890 }
891
892 // The initializer and loop body are candidates for inlining.
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400893 this->visitStatement(&forStmt.initializer(),
John Stiles70957c82020-10-02 16:42:10 -0400894 /*isViableAsEnclosingStatement=*/false);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -0400895 this->visitStatement(&forStmt.statement());
John Stiles70957c82020-10-02 16:42:10 -0400896
897 // The inliner isn't smart enough to inline the test- or increment-expressions
898 // of a for loop loop at this time. There are a handful of limitations:
899 // - We would need to insert the test-expression block at the very beginning of the
900 // for-loop's inner fStatement, and the increment-expression block at the very
901 // end. We don't support that today, but it's doable.
902 // - The for-loop's built-in test-expression would need to be dropped entirely,
903 // and the loop would be halted via a break statement at the end of the inlined
904 // test-expression. This is again something we don't support today, but it could
905 // be implemented.
906 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
907 // that would skip over the inlined block that evaluates the increment expression.
908 // There isn't a good fix for this--any workaround would be more complex than the
909 // cost of a function call. However, loops that don't use `continue` would still
910 // be viable candidates for increment-expression inlining.
911 break;
912 }
913 case Statement::Kind::kIf: {
914 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
915 this->visitExpression(&ifStmt.fTest);
916 this->visitStatement(&ifStmt.fIfTrue);
917 this->visitStatement(&ifStmt.fIfFalse);
918 break;
919 }
920 case Statement::Kind::kReturn: {
921 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
922 this->visitExpression(&returnStmt.fExpression);
923 break;
924 }
925 case Statement::Kind::kSwitch: {
926 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
927 if (switchStmt.fSymbols) {
928 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
929 }
930
931 this->visitExpression(&switchStmt.fValue);
932 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
933 // The switch-case's fValue cannot be a FunctionCall; skip it.
934 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
935 this->visitStatement(&caseBlock);
936 }
937 }
938 break;
939 }
940 case Statement::Kind::kVarDeclaration: {
941 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
942 // Don't need to scan the declaration's sizes; those are always IntLiterals.
943 this->visitExpression(&varDeclStmt.fValue);
944 break;
945 }
946 case Statement::Kind::kVarDeclarations: {
947 VarDeclarationsStatement& varDecls = (*stmt)->as<VarDeclarationsStatement>();
948 for (std::unique_ptr<Statement>& varDecl : varDecls.fDeclaration->fVars) {
949 this->visitStatement(&varDecl, /*isViableAsEnclosingStatement=*/false);
950 }
951 break;
952 }
953 case Statement::Kind::kWhile: {
954 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
955 // The loop body is a candidate for inlining.
956 this->visitStatement(&whileStmt.fStatement);
957 // The inliner isn't smart enough to inline the test-expression for a while loop at
958 // this time. There are two limitations:
959 // - We would need to insert the inlined-body block at the very beginning of the
960 // while loop's inner fStatement. We don't support that today, but it's doable.
961 // - The while-loop's built-in test-expression would need to be replaced with a
962 // `true` BoolLiteral, and the loop would be halted via a break statement at the
963 // end of the inlined test-expression. This is again something we don't support
964 // today, but it could be implemented.
965 break;
966 }
967 default:
968 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400969 }
970
John Stiles70957c82020-10-02 16:42:10 -0400971 // Pop our symbol and enclosing-statement stacks.
972 fSymbolTableStack.resize(oldSymbolStackSize);
973 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
974 }
975
976 void visitExpression(std::unique_ptr<Expression>* expr) {
977 if (!*expr) {
978 return;
John Stiles93442622020-09-11 12:11:27 -0400979 }
John Stiles70957c82020-10-02 16:42:10 -0400980
981 switch ((*expr)->kind()) {
982 case Expression::Kind::kBoolLiteral:
983 case Expression::Kind::kDefined:
984 case Expression::Kind::kExternalValue:
985 case Expression::Kind::kFieldAccess:
986 case Expression::Kind::kFloatLiteral:
987 case Expression::Kind::kFunctionReference:
988 case Expression::Kind::kIntLiteral:
989 case Expression::Kind::kNullLiteral:
990 case Expression::Kind::kSetting:
991 case Expression::Kind::kTypeReference:
992 case Expression::Kind::kVariableReference:
993 // Nothing to scan here.
994 break;
995
996 case Expression::Kind::kBinary: {
997 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
998 this->visitExpression(&binaryExpr.leftPointer());
999
1000 // Logical-and and logical-or binary expressions do not inline the right side,
1001 // because that would invalidate short-circuiting. That is, when evaluating
1002 // expressions like these:
1003 // (false && x()) // always false
1004 // (true || y()) // always true
1005 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1006 // enforce that rule is to avoid inlining the right side entirely. However, it is
1007 // safe for other types of binary expression to inline both sides.
1008 Token::Kind op = binaryExpr.getOperator();
1009 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1010 op == Token::Kind::TK_LOGICALOR);
1011 if (!shortCircuitable) {
1012 this->visitExpression(&binaryExpr.rightPointer());
1013 }
1014 break;
1015 }
1016 case Expression::Kind::kConstructor: {
1017 Constructor& constructorExpr = (*expr)->as<Constructor>();
1018 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1019 this->visitExpression(&arg);
1020 }
1021 break;
1022 }
1023 case Expression::Kind::kExternalFunctionCall: {
1024 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1025 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1026 this->visitExpression(&arg);
1027 }
1028 break;
1029 }
1030 case Expression::Kind::kFunctionCall: {
1031 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001032 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles70957c82020-10-02 16:42:10 -04001033 this->visitExpression(&arg);
1034 }
1035 this->addInlineCandidate(expr);
1036 break;
1037 }
1038 case Expression::Kind::kIndex:{
1039 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
1040 this->visitExpression(&indexExpr.fBase);
1041 this->visitExpression(&indexExpr.fIndex);
1042 break;
1043 }
1044 case Expression::Kind::kPostfix: {
1045 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
1046 this->visitExpression(&postfixExpr.fOperand);
1047 break;
1048 }
1049 case Expression::Kind::kPrefix: {
1050 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
1051 this->visitExpression(&prefixExpr.fOperand);
1052 break;
1053 }
1054 case Expression::Kind::kSwizzle: {
1055 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
1056 this->visitExpression(&swizzleExpr.fBase);
1057 break;
1058 }
1059 case Expression::Kind::kTernary: {
1060 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1061 // The test expression is a candidate for inlining.
1062 this->visitExpression(&ternaryExpr.fTest);
1063 // The true- and false-expressions cannot be inlined, because we are only allowed to
1064 // evaluate one side.
1065 break;
1066 }
1067 default:
1068 SkUNREACHABLE;
1069 }
1070 }
1071
1072 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1073 fCandidateList->fCandidates.push_back(
1074 InlineCandidate{fSymbolTableStack.back(),
1075 find_parent_statement(fEnclosingStmtStack),
1076 fEnclosingStmtStack.back(),
1077 candidate,
1078 fEnclosingFunction,
1079 /*isLargeFunction=*/false});
1080 }
John Stiles2d7973a2020-10-02 15:01:03 -04001081};
John Stiles93442622020-09-11 12:11:27 -04001082
John Stiles2d7973a2020-10-02 15:01:03 -04001083bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001084 const FunctionDeclaration& funcDecl =
1085 (*candidate.fCandidateExpr)->as<FunctionCall>().function();
John Stiles915a38c2020-09-14 09:38:13 -04001086
John Stiles2d7973a2020-10-02 15:01:03 -04001087 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
1088 if (wasInserted) {
1089 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
1090 iter->second = this->isSafeToInline(funcDecl.fDefinition) &&
1091 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001092 }
1093
John Stiles2d7973a2020-10-02 15:01:03 -04001094 return iter->second;
1095}
1096
1097bool Inliner::isLargeFunction(const FunctionDefinition* functionDef) {
1098 return Analysis::NodeCountExceeds(*functionDef, fSettings->fInlineThreshold);
1099}
1100
1101bool Inliner::isLargeFunction(const InlineCandidate& candidate, LargeFunctionCache* cache) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001102 const FunctionDeclaration& funcDecl =
1103 (*candidate.fCandidateExpr)->as<FunctionCall>().function();
John Stiles2d7973a2020-10-02 15:01:03 -04001104
1105 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
1106 if (wasInserted) {
1107 iter->second = this->isLargeFunction(funcDecl.fDefinition);
1108 }
1109
1110 return iter->second;
1111}
1112
1113void Inliner::buildCandidateList(Program& program, InlineCandidateList* candidateList) {
1114 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1115 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1116 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1117 // `const T&`.
1118 InlineCandidateAnalyzer analyzer;
1119 analyzer.visit(program, candidateList);
1120
1121 // Remove candidates that are not safe to inline.
1122 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
1123 InlinabilityCache cache;
1124 candidates.erase(std::remove_if(candidates.begin(),
1125 candidates.end(),
1126 [&](const InlineCandidate& candidate) {
1127 return !this->candidateCanBeInlined(candidate, &cache);
1128 }),
1129 candidates.end());
1130
1131 // Determine whether each candidate function exceeds our inlining size threshold or not. These
1132 // can still be valid candidates if they are only called one time, so we don't remove them from
1133 // the candidate list, but they will not be inlined if they're called more than once.
1134 LargeFunctionCache largeFunctionCache;
1135 for (InlineCandidate& candidate : candidates) {
1136 candidate.fIsLargeFunction = this->isLargeFunction(candidate, &largeFunctionCache);
1137 }
1138}
1139
1140bool Inliner::analyze(Program& program) {
1141 InlineCandidateList candidateList;
1142 this->buildCandidateList(program, &candidateList);
1143
John Stiles915a38c2020-09-14 09:38:13 -04001144 // Inline the candidates where we've determined that it's safe to do so.
1145 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1146 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001147 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001148 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001149 const FunctionDeclaration* funcDecl = &funcCall.function();
John Stiles915a38c2020-09-14 09:38:13 -04001150
John Stiles2d7973a2020-10-02 15:01:03 -04001151 // If the function is large, not marked `inline`, and is called more than once, it's a bad
1152 // idea to inline it.
1153 if (candidate.fIsLargeFunction &&
1154 !(funcDecl->fModifiers.fFlags & Modifiers::kInline_Flag) &&
1155 funcDecl->fCallCount.load() > 1) {
John Stiles915a38c2020-09-14 09:38:13 -04001156 continue;
1157 }
1158
1159 // Inlining two expressions using the same enclosing statement in the same inlining pass
1160 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1161 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1162 if (!inserted) {
1163 continue;
1164 }
1165
1166 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001167 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
1168 &candidate.fEnclosingFunction->fDeclaration);
John Stiles915a38c2020-09-14 09:38:13 -04001169 if (inlinedCall.fInlinedBody) {
1170 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001171 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001172
1173 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1174 // function, then replace the enclosing statement with that Block.
1175 // Before:
1176 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1177 // fEnclosingStmt = stmt4
1178 // After:
1179 // fInlinedBody = null
1180 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001181 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001182 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1183 }
1184
1185 // Replace the candidate function call with our replacement expression.
1186 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1187 madeChanges = true;
1188
1189 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1190 // remain valid.
1191 }
1192
1193 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001194}
1195
John Stiles44e96be2020-08-31 13:16:04 -04001196} // namespace SkSL