blob: f3ac718836eff3317bf8bc9ad51efb6ecddca65c [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
10#include "limits.h"
11#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"
36#include "src/sksl/ir/SkSLIntLiteral.h"
37#include "src/sksl/ir/SkSLInterfaceBlock.h"
38#include "src/sksl/ir/SkSLLayout.h"
39#include "src/sksl/ir/SkSLNop.h"
40#include "src/sksl/ir/SkSLNullLiteral.h"
41#include "src/sksl/ir/SkSLPostfixExpression.h"
42#include "src/sksl/ir/SkSLPrefixExpression.h"
43#include "src/sksl/ir/SkSLReturnStatement.h"
44#include "src/sksl/ir/SkSLSetting.h"
45#include "src/sksl/ir/SkSLSwitchCase.h"
46#include "src/sksl/ir/SkSLSwitchStatement.h"
47#include "src/sksl/ir/SkSLSwizzle.h"
48#include "src/sksl/ir/SkSLTernaryExpression.h"
49#include "src/sksl/ir/SkSLUnresolvedFunction.h"
50#include "src/sksl/ir/SkSLVarDeclarations.h"
51#include "src/sksl/ir/SkSLVarDeclarationsStatement.h"
52#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
59static int count_all_returns(const FunctionDefinition& funcDef) {
60 class CountAllReturns : public ProgramVisitor {
61 public:
62 CountAllReturns(const FunctionDefinition& funcDef) {
63 this->visitProgramElement(funcDef);
64 }
65
66 bool visitStatement(const Statement& stmt) override {
67 switch (stmt.fKind) {
68 case Statement::kReturn_Kind:
69 ++fNumReturns;
70 [[fallthrough]];
71
72 default:
73 return this->INHERITED::visitStatement(stmt);
74 }
75 }
76
77 int fNumReturns = 0;
78 using INHERITED = ProgramVisitor;
79 };
80
81 return CountAllReturns{funcDef}.fNumReturns;
82}
83
84static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
85 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
86 public:
87 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
88 this->visitProgramElement(funcDef);
89 }
90
91 bool visitStatement(const Statement& stmt) override {
92 switch (stmt.fKind) {
93 case Statement::kBlock_Kind: {
94 // Check only the last statement of a block.
95 const auto& blockStmts = stmt.as<Block>().fStatements;
96 return (blockStmts.size() > 0) ? this->visitStatement(*blockStmts.back())
97 : false;
98 }
99 case Statement::kSwitch_Kind:
100 case Statement::kWhile_Kind:
101 case Statement::kDo_Kind:
102 case Statement::kFor_Kind:
103 // Don't introspect switches or loop structures at all.
104 return false;
105
106 case Statement::kReturn_Kind:
107 ++fNumReturns;
108 [[fallthrough]];
109
110 default:
111 return this->INHERITED::visitStatement(stmt);
112 }
113 }
114
115 int fNumReturns = 0;
116 using INHERITED = ProgramVisitor;
117 };
118
119 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
120}
121
122static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
123 class CountReturnsInBreakableConstructs : public ProgramVisitor {
124 public:
125 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
126 this->visitProgramElement(funcDef);
127 }
128
129 bool visitStatement(const Statement& stmt) override {
130 switch (stmt.fKind) {
131 case Statement::kSwitch_Kind:
132 case Statement::kWhile_Kind:
133 case Statement::kDo_Kind:
134 case Statement::kFor_Kind: {
135 ++fInsideBreakableConstruct;
136 bool result = this->INHERITED::visitStatement(stmt);
137 --fInsideBreakableConstruct;
138 return result;
139 }
140
141 case Statement::kReturn_Kind:
142 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
143 [[fallthrough]];
144
145 default:
146 return this->INHERITED::visitStatement(stmt);
147 }
148 }
149
150 int fNumReturns = 0;
151 int fInsideBreakableConstruct = 0;
152 using INHERITED = ProgramVisitor;
153 };
154
155 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
156}
157
158static bool has_early_return(const FunctionDefinition& funcDef) {
159 int returnCount = count_all_returns(funcDef);
160 if (returnCount == 0) {
161 return false;
162 }
163
164 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
165 return returnCount > returnsAtEndOfControlFlow;
166}
167
168static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
169 if (src->kind() == Type::kArray_Kind) {
170 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(*src));
171 }
172 return src;
173}
174
175} // namespace
176
177void Inliner::reset(const Context& context, const Program::Settings& settings) {
178 fContext = &context;
179 fSettings = &settings;
180 fInlineVarCounter = 0;
181}
182
183std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
184 VariableRewriteMap* varMap,
185 const Expression& expression) {
186 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
187 if (e) {
188 return this->inlineExpression(offset, varMap, *e);
189 }
190 return nullptr;
191 };
192 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
193 -> std::vector<std::unique_ptr<Expression>> {
194 std::vector<std::unique_ptr<Expression>> args;
195 args.reserve(originalArgs.size());
196 for (const std::unique_ptr<Expression>& arg : originalArgs) {
197 args.push_back(expr(arg));
198 }
199 return args;
200 };
201
202 switch (expression.fKind) {
203 case Expression::kBinary_Kind: {
204 const BinaryExpression& b = expression.as<BinaryExpression>();
205 return std::make_unique<BinaryExpression>(offset,
206 expr(b.fLeft),
207 b.fOperator,
208 expr(b.fRight),
209 b.fType);
210 }
211 case Expression::kBoolLiteral_Kind:
212 case Expression::kIntLiteral_Kind:
213 case Expression::kFloatLiteral_Kind:
214 case Expression::kNullLiteral_Kind:
215 return expression.clone();
216 case Expression::kConstructor_Kind: {
217 const Constructor& constructor = expression.as<Constructor>();
218 return std::make_unique<Constructor>(offset, constructor.fType,
219 argList(constructor.fArguments));
220 }
221 case Expression::kExternalFunctionCall_Kind: {
222 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
223 return std::make_unique<ExternalFunctionCall>(offset, externalCall.fType,
224 externalCall.fFunction,
225 argList(externalCall.fArguments));
226 }
227 case Expression::kExternalValue_Kind:
228 return expression.clone();
229 case Expression::kFieldAccess_Kind: {
230 const FieldAccess& f = expression.as<FieldAccess>();
231 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
232 }
233 case Expression::kFunctionCall_Kind: {
234 const FunctionCall& funcCall = expression.as<FunctionCall>();
235 return std::make_unique<FunctionCall>(offset, funcCall.fType, funcCall.fFunction,
236 argList(funcCall.fArguments));
237 }
Brian Osman2b3b35f2020-09-08 09:17:36 -0400238 case Expression::kFunctionReference_Kind:
239 return expression.clone();
John Stiles44e96be2020-08-31 13:16:04 -0400240 case Expression::kIndex_Kind: {
241 const IndexExpression& idx = expression.as<IndexExpression>();
242 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
243 }
244 case Expression::kPrefix_Kind: {
245 const PrefixExpression& p = expression.as<PrefixExpression>();
246 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
247 }
248 case Expression::kPostfix_Kind: {
249 const PostfixExpression& p = expression.as<PostfixExpression>();
250 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
251 }
252 case Expression::kSetting_Kind:
253 return expression.clone();
254 case Expression::kSwizzle_Kind: {
255 const Swizzle& s = expression.as<Swizzle>();
256 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
257 }
258 case Expression::kTernary_Kind: {
259 const TernaryExpression& t = expression.as<TernaryExpression>();
260 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
261 expr(t.fIfTrue), expr(t.fIfFalse));
262 }
263 case Expression::kVariableReference_Kind: {
264 const VariableReference& v = expression.as<VariableReference>();
265 auto found = varMap->find(&v.fVariable);
266 if (found != varMap->end()) {
267 return std::make_unique<VariableReference>(offset, *found->second, v.fRefKind);
268 }
269 return v.clone();
270 }
271 default:
272 SkASSERT(false);
273 return nullptr;
274 }
275}
276
277std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
278 VariableRewriteMap* varMap,
279 SymbolTable* symbolTableForStatement,
280 const Variable* returnVar,
281 bool haveEarlyReturns,
282 const Statement& statement) {
283 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
284 if (s) {
285 return this->inlineStatement(offset, varMap, symbolTableForStatement, returnVar,
286 haveEarlyReturns, *s);
287 }
288 return nullptr;
289 };
290 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
291 std::vector<std::unique_ptr<Statement>> result;
292 for (const auto& s : ss) {
293 result.push_back(stmt(s));
294 }
295 return result;
296 };
297 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
298 if (e) {
299 return this->inlineExpression(offset, varMap, *e);
300 }
301 return nullptr;
302 };
303 switch (statement.fKind) {
304 case Statement::kBlock_Kind: {
305 const Block& b = statement.as<Block>();
306 return std::make_unique<Block>(offset, stmts(b.fStatements), b.fSymbols, b.fIsScope);
307 }
308
309 case Statement::kBreak_Kind:
310 case Statement::kContinue_Kind:
311 case Statement::kDiscard_Kind:
312 return statement.clone();
313
314 case Statement::kDo_Kind: {
315 const DoStatement& d = statement.as<DoStatement>();
316 return std::make_unique<DoStatement>(offset, stmt(d.fStatement), expr(d.fTest));
317 }
318 case Statement::kExpression_Kind: {
319 const ExpressionStatement& e = statement.as<ExpressionStatement>();
320 return std::make_unique<ExpressionStatement>(expr(e.fExpression));
321 }
322 case Statement::kFor_Kind: {
323 const ForStatement& f = statement.as<ForStatement>();
324 // need to ensure initializer is evaluated first so that we've already remapped its
325 // declarations by the time we evaluate test & next
326 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
327 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
328 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
329 }
330 case Statement::kIf_Kind: {
331 const IfStatement& i = statement.as<IfStatement>();
332 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
333 stmt(i.fIfTrue), stmt(i.fIfFalse));
334 }
335 case Statement::kNop_Kind:
336 return statement.clone();
337 case Statement::kReturn_Kind: {
338 const ReturnStatement& r = statement.as<ReturnStatement>();
339 if (r.fExpression) {
340 auto assignment = std::make_unique<ExpressionStatement>(
341 std::make_unique<BinaryExpression>(
342 offset,
343 std::make_unique<VariableReference>(offset, *returnVar,
344 VariableReference::kWrite_RefKind),
345 Token::Kind::TK_EQ,
346 expr(r.fExpression),
347 returnVar->fType));
348 if (haveEarlyReturns) {
349 std::vector<std::unique_ptr<Statement>> block;
350 block.push_back(std::move(assignment));
351 block.emplace_back(new BreakStatement(offset));
352 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
353 /*isScope=*/true);
354 } else {
355 return std::move(assignment);
356 }
357 } else {
358 if (haveEarlyReturns) {
359 return std::make_unique<BreakStatement>(offset);
360 } else {
361 return std::make_unique<Nop>();
362 }
363 }
364 }
365 case Statement::kSwitch_Kind: {
366 const SwitchStatement& ss = statement.as<SwitchStatement>();
367 std::vector<std::unique_ptr<SwitchCase>> cases;
368 for (const auto& sc : ss.fCases) {
369 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
370 stmts(sc->fStatements)));
371 }
372 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
373 std::move(cases), ss.fSymbols);
374 }
375 case Statement::kVarDeclaration_Kind: {
376 const VarDeclaration& decl = statement.as<VarDeclaration>();
377 std::vector<std::unique_ptr<Expression>> sizes;
378 for (const auto& size : decl.fSizes) {
379 sizes.push_back(expr(size));
380 }
381 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
382 const Variable* old = decl.fVar;
383 // need to copy the var name in case the originating function is discarded and we lose
384 // its symbols
385 std::unique_ptr<String> name(new String(old->fName));
386 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
387 const Type* typePtr = copy_if_needed(&old->fType, *symbolTableForStatement);
388 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
389 std::make_unique<Variable>(offset,
390 old->fModifiers,
391 namePtr->c_str(),
392 *typePtr,
393 old->fStorage,
394 initialValue.get()));
395 (*varMap)[old] = clone;
396 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
397 std::move(initialValue));
398 }
399 case Statement::kVarDeclarations_Kind: {
400 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
401 std::vector<std::unique_ptr<VarDeclaration>> vars;
402 for (const auto& var : decls.fVars) {
403 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
404 }
405 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
406 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
407 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
408 }
409 case Statement::kWhile_Kind: {
410 const WhileStatement& w = statement.as<WhileStatement>();
411 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
412 }
413 default:
414 SkASSERT(false);
415 return nullptr;
416 }
417}
418
John Stiles6eadf132020-09-08 10:16:10 -0400419Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
John Stiles44e96be2020-08-31 13:16:04 -0400420 SymbolTable* symbolTableForCall) {
421 // Inlining is more complicated here than in a typical compiler, because we have to have a
422 // high-level IR and can't just drop statements into the middle of an expression or even use
423 // gotos.
424 //
425 // Since we can't insert statements into an expression, we run the inline function as extra
426 // statements before the statement we're currently processing, relying on a lack of execution
427 // order guarantees. Since we can't use gotos (which are normally used to replace return
428 // statements), we wrap the whole function in a loop and use break statements to jump to the
429 // end.
430 SkASSERT(fSettings);
431 SkASSERT(fContext);
432 SkASSERT(call);
433 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
434
John Stiles44e96be2020-08-31 13:16:04 -0400435 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
John Stiles6eadf132020-09-08 10:16:10 -0400436 const int offset = call->fOffset;
John Stiles44e96be2020-08-31 13:16:04 -0400437 const FunctionDefinition& function = *call->fFunction.fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400438 const bool hasEarlyReturn = has_early_return(function);
439
John Stiles44e96be2020-08-31 13:16:04 -0400440 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400441 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
442 std::vector<std::unique_ptr<Statement>>{},
443 /*symbols=*/nullptr,
444 /*isScope=*/false);
445 std::vector<std::unique_ptr<Statement>>& inlinedBody = inlinedCall.fInlinedBody->fStatements;
John Stiles44e96be2020-08-31 13:16:04 -0400446
John Stilescf936f92020-08-31 17:18:45 -0400447 auto makeInlineVar = [&](const String& baseName, const Type& type, Modifiers modifiers,
John Stiles44e96be2020-08-31 13:16:04 -0400448 std::unique_ptr<Expression>* initialValue) -> const Variable* {
John Stilescf936f92020-08-31 17:18:45 -0400449 // If the base name starts with an underscore, like "_coords", we can't append another
450 // underscore, because some OpenGL platforms error out when they see two consecutive
451 // underscores (anywhere in the string!). But in the general case, using the underscore as
452 // a splitter reads nicely enough that it's worth putting in this special case.
453 const char* splitter = baseName.startsWith("_") ? "_X" : "_";
454
455 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
456 // we're not reusing an existing name. (Note that within a single compilation pass, this
457 // check isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
458 String uniqueName;
459 for (;;) {
460 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
461 StringFragment frag{uniqueName.data(), uniqueName.length()};
462 if ((*symbolTableForCall)[frag] == nullptr) {
463 break;
464 }
465 }
466
John Stiles44e96be2020-08-31 13:16:04 -0400467 // Add our new variable's name to the symbol table.
John Stilescf936f92020-08-31 17:18:45 -0400468 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
469 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400470 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
471
472 // Add our new variable to the symbol table.
473 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
474 Variable::kLocal_Storage, initialValue->get());
475 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
476
477 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
478 // initial value).
479 std::vector<std::unique_ptr<VarDeclaration>> variables;
480 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
481 variables.push_back(std::make_unique<VarDeclaration>(
482 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
483 (*initialValue)->clone()));
484 } else {
485 variables.push_back(std::make_unique<VarDeclaration>(
486 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
487 std::move(*initialValue)));
488 }
489
490 // Add the new variable-declaration statement to our block of extra statements.
John Stiles39616ec2020-08-31 14:16:06 -0400491 inlinedBody.push_back(std::make_unique<VarDeclarationsStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400492 std::make_unique<VarDeclarations>(offset, &type, std::move(variables))));
493
494 return variableSymbol;
495 };
496
497 // Create a variable to hold the result in the extra statements (excepting void).
498 const Variable* resultVar = nullptr;
499 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400500 std::unique_ptr<Expression> noInitialValue;
John Stilescf936f92020-08-31 17:18:45 -0400501 resultVar = makeInlineVar(String(function.fDeclaration.fName),
John Stiles44e96be2020-08-31 13:16:04 -0400502 function.fDeclaration.fReturnType, Modifiers{}, &noInitialValue);
503 }
504
505 // Create variables in the extra statements to hold the arguments, and assign the arguments to
506 // them.
507 VariableRewriteMap varMap;
John Stiles44e96be2020-08-31 13:16:04 -0400508 for (int i = 0; i < (int) arguments.size(); ++i) {
509 const Variable* param = function.fDeclaration.fParameters[i];
510
511 if (arguments[i]->fKind == Expression::kVariableReference_Kind) {
512 // The argument is just a variable, so we only need to copy it if it's an out parameter
513 // or it's written to within the function.
514 if ((param->fModifiers.fFlags & Modifiers::kOut_Flag) ||
515 !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
516 varMap[param] = &arguments[i]->as<VariableReference>().fVariable;
517 continue;
518 }
519 }
520
John Stilescf936f92020-08-31 17:18:45 -0400521 varMap[param] = makeInlineVar(String(param->fName), arguments[i]->fType, param->fModifiers,
522 &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400523 }
524
525 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400526 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
527 inlineBlock->fStatements.reserve(body.fStatements.size());
528 for (const std::unique_ptr<Statement>& stmt : body.fStatements) {
529 inlineBlock->fStatements.push_back(this->inlineStatement(
530 offset, &varMap, symbolTableForCall, resultVar, hasEarlyReturn, *stmt));
531 }
532 if (hasEarlyReturn) {
533 // Since we output to backends that don't have a goto statement (which would normally be
534 // used to perform an early return), we fake it by wrapping the function in a
535 // do { } while (false); and then use break statements to jump to the end in order to
536 // emulate a goto.
John Stiles39616ec2020-08-31 14:16:06 -0400537 inlinedBody.push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400538 /*offset=*/-1,
539 std::move(inlineBlock),
540 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
541 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400542 // No early returns, so we can just dump the code in. We still need to keep the block so we
543 // don't get name conflicts with locals.
John Stiles39616ec2020-08-31 14:16:06 -0400544 inlinedBody.push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400545 }
546
547 // Copy the values of `out` parameters into their destinations.
548 for (size_t i = 0; i < arguments.size(); ++i) {
549 const Variable* p = function.fDeclaration.fParameters[i];
550 if (p->fModifiers.fFlags & Modifiers::kOut_Flag) {
551 SkASSERT(varMap.find(p) != varMap.end());
552 if (arguments[i]->fKind == Expression::kVariableReference_Kind &&
553 &arguments[i]->as<VariableReference>().fVariable == varMap[p]) {
John Stiles6eadf132020-09-08 10:16:10 -0400554 // We didn't create a temporary for this parameter, so there's nothing to copy back
555 // out.
John Stiles44e96be2020-08-31 13:16:04 -0400556 continue;
557 }
558 auto varRef = std::make_unique<VariableReference>(offset, *varMap[p]);
John Stiles39616ec2020-08-31 14:16:06 -0400559 inlinedBody.push_back(std::make_unique<ExpressionStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400560 std::make_unique<BinaryExpression>(offset,
561 arguments[i]->clone(),
562 Token::Kind::TK_EQ,
563 std::move(varRef),
564 arguments[i]->fType)));
565 }
566 }
567
568 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
569 // Return a reference to the result variable as our replacement expression.
570 inlinedCall.fReplacementExpr = std::make_unique<VariableReference>(offset, *resultVar);
571 } else {
572 // It's a void function, so it doesn't actually result in anything, but we have to return
573 // something non-null as a standin.
574 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
575 /*value=*/false);
576 }
577
John Stiles44e96be2020-08-31 13:16:04 -0400578 return inlinedCall;
579}
580
581bool Inliner::isSafeToInline(const FunctionCall& functionCall,
582 int inlineThreshold) {
583 SkASSERT(fSettings);
584
585 if (functionCall.fFunction.fDefinition == nullptr) {
586 // Can't inline something if we don't actually have its definition.
587 return false;
588 }
589 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
590 if (inlineThreshold < INT_MAX) {
591 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
592 Analysis::NodeCount(functionDef) >= inlineThreshold) {
593 // The function exceeds our maximum inline size and is not flagged 'inline'.
594 return false;
595 }
596 }
597 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
598 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
599 // can't inline functions that have an early return.
600 bool hasEarlyReturn = has_early_return(functionDef);
601
602 // If we didn't detect an early return, there shouldn't be any returns in breakable
603 // constructs either.
604 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
605 return !hasEarlyReturn;
606 }
607 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
608 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
609 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
610
611 // If we detected returns in breakable constructs, we should also detect an early return.
612 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
613 return !hasReturnInBreakableConstruct;
614}
615
616} // namespace SkSL