blob: 736cb56f6f3cc8ca8d01f3b6a6e10dc433522265 [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 }
238 case Expression::kIndex_Kind: {
239 const IndexExpression& idx = expression.as<IndexExpression>();
240 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
241 }
242 case Expression::kPrefix_Kind: {
243 const PrefixExpression& p = expression.as<PrefixExpression>();
244 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
245 }
246 case Expression::kPostfix_Kind: {
247 const PostfixExpression& p = expression.as<PostfixExpression>();
248 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
249 }
250 case Expression::kSetting_Kind:
251 return expression.clone();
252 case Expression::kSwizzle_Kind: {
253 const Swizzle& s = expression.as<Swizzle>();
254 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
255 }
256 case Expression::kTernary_Kind: {
257 const TernaryExpression& t = expression.as<TernaryExpression>();
258 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
259 expr(t.fIfTrue), expr(t.fIfFalse));
260 }
261 case Expression::kVariableReference_Kind: {
262 const VariableReference& v = expression.as<VariableReference>();
263 auto found = varMap->find(&v.fVariable);
264 if (found != varMap->end()) {
265 return std::make_unique<VariableReference>(offset, *found->second, v.fRefKind);
266 }
267 return v.clone();
268 }
269 default:
270 SkASSERT(false);
271 return nullptr;
272 }
273}
274
275std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
276 VariableRewriteMap* varMap,
277 SymbolTable* symbolTableForStatement,
278 const Variable* returnVar,
279 bool haveEarlyReturns,
280 const Statement& statement) {
281 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
282 if (s) {
283 return this->inlineStatement(offset, varMap, symbolTableForStatement, returnVar,
284 haveEarlyReturns, *s);
285 }
286 return nullptr;
287 };
288 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
289 std::vector<std::unique_ptr<Statement>> result;
290 for (const auto& s : ss) {
291 result.push_back(stmt(s));
292 }
293 return result;
294 };
295 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
296 if (e) {
297 return this->inlineExpression(offset, varMap, *e);
298 }
299 return nullptr;
300 };
301 switch (statement.fKind) {
302 case Statement::kBlock_Kind: {
303 const Block& b = statement.as<Block>();
304 return std::make_unique<Block>(offset, stmts(b.fStatements), b.fSymbols, b.fIsScope);
305 }
306
307 case Statement::kBreak_Kind:
308 case Statement::kContinue_Kind:
309 case Statement::kDiscard_Kind:
310 return statement.clone();
311
312 case Statement::kDo_Kind: {
313 const DoStatement& d = statement.as<DoStatement>();
314 return std::make_unique<DoStatement>(offset, stmt(d.fStatement), expr(d.fTest));
315 }
316 case Statement::kExpression_Kind: {
317 const ExpressionStatement& e = statement.as<ExpressionStatement>();
318 return std::make_unique<ExpressionStatement>(expr(e.fExpression));
319 }
320 case Statement::kFor_Kind: {
321 const ForStatement& f = statement.as<ForStatement>();
322 // need to ensure initializer is evaluated first so that we've already remapped its
323 // declarations by the time we evaluate test & next
324 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
325 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
326 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
327 }
328 case Statement::kIf_Kind: {
329 const IfStatement& i = statement.as<IfStatement>();
330 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
331 stmt(i.fIfTrue), stmt(i.fIfFalse));
332 }
333 case Statement::kNop_Kind:
334 return statement.clone();
335 case Statement::kReturn_Kind: {
336 const ReturnStatement& r = statement.as<ReturnStatement>();
337 if (r.fExpression) {
338 auto assignment = std::make_unique<ExpressionStatement>(
339 std::make_unique<BinaryExpression>(
340 offset,
341 std::make_unique<VariableReference>(offset, *returnVar,
342 VariableReference::kWrite_RefKind),
343 Token::Kind::TK_EQ,
344 expr(r.fExpression),
345 returnVar->fType));
346 if (haveEarlyReturns) {
347 std::vector<std::unique_ptr<Statement>> block;
348 block.push_back(std::move(assignment));
349 block.emplace_back(new BreakStatement(offset));
350 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
351 /*isScope=*/true);
352 } else {
353 return std::move(assignment);
354 }
355 } else {
356 if (haveEarlyReturns) {
357 return std::make_unique<BreakStatement>(offset);
358 } else {
359 return std::make_unique<Nop>();
360 }
361 }
362 }
363 case Statement::kSwitch_Kind: {
364 const SwitchStatement& ss = statement.as<SwitchStatement>();
365 std::vector<std::unique_ptr<SwitchCase>> cases;
366 for (const auto& sc : ss.fCases) {
367 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
368 stmts(sc->fStatements)));
369 }
370 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
371 std::move(cases), ss.fSymbols);
372 }
373 case Statement::kVarDeclaration_Kind: {
374 const VarDeclaration& decl = statement.as<VarDeclaration>();
375 std::vector<std::unique_ptr<Expression>> sizes;
376 for (const auto& size : decl.fSizes) {
377 sizes.push_back(expr(size));
378 }
379 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
380 const Variable* old = decl.fVar;
381 // need to copy the var name in case the originating function is discarded and we lose
382 // its symbols
383 std::unique_ptr<String> name(new String(old->fName));
384 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
385 const Type* typePtr = copy_if_needed(&old->fType, *symbolTableForStatement);
386 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
387 std::make_unique<Variable>(offset,
388 old->fModifiers,
389 namePtr->c_str(),
390 *typePtr,
391 old->fStorage,
392 initialValue.get()));
393 (*varMap)[old] = clone;
394 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
395 std::move(initialValue));
396 }
397 case Statement::kVarDeclarations_Kind: {
398 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
399 std::vector<std::unique_ptr<VarDeclaration>> vars;
400 for (const auto& var : decls.fVars) {
401 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
402 }
403 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
404 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
405 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
406 }
407 case Statement::kWhile_Kind: {
408 const WhileStatement& w = statement.as<WhileStatement>();
409 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
410 }
411 default:
412 SkASSERT(false);
413 return nullptr;
414 }
415}
416
417Inliner::InlinedCall Inliner::inlineCall(std::unique_ptr<FunctionCall> call,
418 SymbolTable* symbolTableForCall) {
419 // Inlining is more complicated here than in a typical compiler, because we have to have a
420 // high-level IR and can't just drop statements into the middle of an expression or even use
421 // gotos.
422 //
423 // Since we can't insert statements into an expression, we run the inline function as extra
424 // statements before the statement we're currently processing, relying on a lack of execution
425 // order guarantees. Since we can't use gotos (which are normally used to replace return
426 // statements), we wrap the whole function in a loop and use break statements to jump to the
427 // end.
428 SkASSERT(fSettings);
429 SkASSERT(fContext);
430 SkASSERT(call);
431 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
432
433 int offset = call->fOffset;
434 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
435 const FunctionDefinition& function = *call->fFunction.fDefinition;
436 InlinedCall inlinedCall;
John Stiles39616ec2020-08-31 14:16:06 -0400437 std::vector<std::unique_ptr<Statement>> inlinedBody;
John Stiles44e96be2020-08-31 13:16:04 -0400438
John Stilescf936f92020-08-31 17:18:45 -0400439 auto makeInlineVar = [&](const String& baseName, const Type& type, Modifiers modifiers,
John Stiles44e96be2020-08-31 13:16:04 -0400440 std::unique_ptr<Expression>* initialValue) -> const Variable* {
John Stilescf936f92020-08-31 17:18:45 -0400441 // If the base name starts with an underscore, like "_coords", we can't append another
442 // underscore, because some OpenGL platforms error out when they see two consecutive
443 // underscores (anywhere in the string!). But in the general case, using the underscore as
444 // a splitter reads nicely enough that it's worth putting in this special case.
445 const char* splitter = baseName.startsWith("_") ? "_X" : "_";
446
447 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
448 // we're not reusing an existing name. (Note that within a single compilation pass, this
449 // check isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
450 String uniqueName;
451 for (;;) {
452 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
453 StringFragment frag{uniqueName.data(), uniqueName.length()};
454 if ((*symbolTableForCall)[frag] == nullptr) {
455 break;
456 }
457 }
458
John Stiles44e96be2020-08-31 13:16:04 -0400459 // Add our new variable's name to the symbol table.
John Stilescf936f92020-08-31 17:18:45 -0400460 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
461 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400462 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
463
464 // Add our new variable to the symbol table.
465 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
466 Variable::kLocal_Storage, initialValue->get());
467 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
468
469 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
470 // initial value).
471 std::vector<std::unique_ptr<VarDeclaration>> variables;
472 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
473 variables.push_back(std::make_unique<VarDeclaration>(
474 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
475 (*initialValue)->clone()));
476 } else {
477 variables.push_back(std::make_unique<VarDeclaration>(
478 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
479 std::move(*initialValue)));
480 }
481
482 // Add the new variable-declaration statement to our block of extra statements.
John Stiles39616ec2020-08-31 14:16:06 -0400483 inlinedBody.push_back(std::make_unique<VarDeclarationsStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400484 std::make_unique<VarDeclarations>(offset, &type, std::move(variables))));
485
486 return variableSymbol;
487 };
488
489 // Create a variable to hold the result in the extra statements (excepting void).
490 const Variable* resultVar = nullptr;
491 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400492 std::unique_ptr<Expression> noInitialValue;
John Stilescf936f92020-08-31 17:18:45 -0400493 resultVar = makeInlineVar(String(function.fDeclaration.fName),
John Stiles44e96be2020-08-31 13:16:04 -0400494 function.fDeclaration.fReturnType, Modifiers{}, &noInitialValue);
495 }
496
497 // Create variables in the extra statements to hold the arguments, and assign the arguments to
498 // them.
499 VariableRewriteMap varMap;
John Stiles44e96be2020-08-31 13:16:04 -0400500 for (int i = 0; i < (int) arguments.size(); ++i) {
501 const Variable* param = function.fDeclaration.fParameters[i];
502
503 if (arguments[i]->fKind == Expression::kVariableReference_Kind) {
504 // The argument is just a variable, so we only need to copy it if it's an out parameter
505 // or it's written to within the function.
506 if ((param->fModifiers.fFlags & Modifiers::kOut_Flag) ||
507 !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
508 varMap[param] = &arguments[i]->as<VariableReference>().fVariable;
509 continue;
510 }
511 }
512
John Stilescf936f92020-08-31 17:18:45 -0400513 varMap[param] = makeInlineVar(String(param->fName), arguments[i]->fType, param->fModifiers,
514 &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400515 }
516
517 const Block& body = function.fBody->as<Block>();
518 bool hasEarlyReturn = has_early_return(function);
519 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
520 inlineBlock->fStatements.reserve(body.fStatements.size());
521 for (const std::unique_ptr<Statement>& stmt : body.fStatements) {
522 inlineBlock->fStatements.push_back(this->inlineStatement(
523 offset, &varMap, symbolTableForCall, resultVar, hasEarlyReturn, *stmt));
524 }
525 if (hasEarlyReturn) {
526 // Since we output to backends that don't have a goto statement (which would normally be
527 // used to perform an early return), we fake it by wrapping the function in a
528 // do { } while (false); and then use break statements to jump to the end in order to
529 // emulate a goto.
John Stiles39616ec2020-08-31 14:16:06 -0400530 inlinedBody.push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400531 /*offset=*/-1,
532 std::move(inlineBlock),
533 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
534 } else {
535 // No early returns, so we can just dump the code in. We need to use a block so we don't get
536 // name conflicts with locals.
John Stiles39616ec2020-08-31 14:16:06 -0400537 inlinedBody.push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400538 }
539
540 // Copy the values of `out` parameters into their destinations.
541 for (size_t i = 0; i < arguments.size(); ++i) {
542 const Variable* p = function.fDeclaration.fParameters[i];
543 if (p->fModifiers.fFlags & Modifiers::kOut_Flag) {
544 SkASSERT(varMap.find(p) != varMap.end());
545 if (arguments[i]->fKind == Expression::kVariableReference_Kind &&
546 &arguments[i]->as<VariableReference>().fVariable == varMap[p]) {
547 // we didn't create a temporary for this parameter, so there's nothing to copy back
548 // out
549 continue;
550 }
551 auto varRef = std::make_unique<VariableReference>(offset, *varMap[p]);
John Stiles39616ec2020-08-31 14:16:06 -0400552 inlinedBody.push_back(std::make_unique<ExpressionStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400553 std::make_unique<BinaryExpression>(offset,
554 arguments[i]->clone(),
555 Token::Kind::TK_EQ,
556 std::move(varRef),
557 arguments[i]->fType)));
558 }
559 }
560
561 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
562 // Return a reference to the result variable as our replacement expression.
563 inlinedCall.fReplacementExpr = std::make_unique<VariableReference>(offset, *resultVar);
564 } else {
565 // It's a void function, so it doesn't actually result in anything, but we have to return
566 // something non-null as a standin.
567 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
568 /*value=*/false);
569 }
570
John Stiles39616ec2020-08-31 14:16:06 -0400571 switch (inlinedBody.size()) {
572 case 0:
573 break;
574 case 1:
575 inlinedCall.fInlinedBody = std::move(inlinedBody.front());
576 break;
577 default:
578 inlinedCall.fInlinedBody = std::make_unique<Block>(offset, std::move(inlinedBody),
579 /*symbols=*/nullptr,
580 /*isScope=*/false);
581 break;
582 }
583
John Stiles44e96be2020-08-31 13:16:04 -0400584 return inlinedCall;
585}
586
587bool Inliner::isSafeToInline(const FunctionCall& functionCall,
588 int inlineThreshold) {
589 SkASSERT(fSettings);
590
591 if (functionCall.fFunction.fDefinition == nullptr) {
592 // Can't inline something if we don't actually have its definition.
593 return false;
594 }
595 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
596 if (inlineThreshold < INT_MAX) {
597 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
598 Analysis::NodeCount(functionDef) >= inlineThreshold) {
599 // The function exceeds our maximum inline size and is not flagged 'inline'.
600 return false;
601 }
602 }
603 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
604 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
605 // can't inline functions that have an early return.
606 bool hasEarlyReturn = has_early_return(functionDef);
607
608 // If we didn't detect an early return, there shouldn't be any returns in breakable
609 // constructs either.
610 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
611 return !hasEarlyReturn;
612 }
613 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
614 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
615 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
616
617 // If we detected returns in breakable constructs, we should also detect an early return.
618 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
619 return !hasReturnInBreakableConstruct;
620}
621
622} // namespace SkSL