xref: /aosp_15_r20/external/skia/src/sksl/SkSLInliner.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
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 #ifndef SK_ENABLE_OPTIMIZE_SIZE
11 
12 #include "include/core/SkSpan.h"
13 #include "include/core/SkTypes.h"
14 #include "include/private/base/SkTArray.h"
15 #include "src/base/SkEnumBitMask.h"
16 #include "src/sksl/SkSLAnalysis.h"
17 #include "src/sksl/SkSLDefines.h"
18 #include "src/sksl/SkSLErrorReporter.h"
19 #include "src/sksl/SkSLOperator.h"
20 #include "src/sksl/SkSLPosition.h"
21 #include "src/sksl/analysis/SkSLProgramUsage.h"
22 #include "src/sksl/ir/SkSLBinaryExpression.h"
23 #include "src/sksl/ir/SkSLBreakStatement.h"
24 #include "src/sksl/ir/SkSLChildCall.h"
25 #include "src/sksl/ir/SkSLConstructor.h"
26 #include "src/sksl/ir/SkSLConstructorArray.h"
27 #include "src/sksl/ir/SkSLConstructorArrayCast.h"
28 #include "src/sksl/ir/SkSLConstructorCompound.h"
29 #include "src/sksl/ir/SkSLConstructorCompoundCast.h"
30 #include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
31 #include "src/sksl/ir/SkSLConstructorMatrixResize.h"
32 #include "src/sksl/ir/SkSLConstructorScalarCast.h"
33 #include "src/sksl/ir/SkSLConstructorSplat.h"
34 #include "src/sksl/ir/SkSLConstructorStruct.h"
35 #include "src/sksl/ir/SkSLContinueStatement.h"
36 #include "src/sksl/ir/SkSLDiscardStatement.h"
37 #include "src/sksl/ir/SkSLDoStatement.h"
38 #include "src/sksl/ir/SkSLEmptyExpression.h"
39 #include "src/sksl/ir/SkSLExpressionStatement.h"
40 #include "src/sksl/ir/SkSLFieldAccess.h"
41 #include "src/sksl/ir/SkSLForStatement.h"
42 #include "src/sksl/ir/SkSLFunctionCall.h"
43 #include "src/sksl/ir/SkSLFunctionDeclaration.h"
44 #include "src/sksl/ir/SkSLFunctionDefinition.h"
45 #include "src/sksl/ir/SkSLIRNode.h"
46 #include "src/sksl/ir/SkSLIfStatement.h"
47 #include "src/sksl/ir/SkSLIndexExpression.h"
48 #include "src/sksl/ir/SkSLModifierFlags.h"
49 #include "src/sksl/ir/SkSLNop.h"
50 #include "src/sksl/ir/SkSLPostfixExpression.h"
51 #include "src/sksl/ir/SkSLPrefixExpression.h"
52 #include "src/sksl/ir/SkSLProgramElement.h"
53 #include "src/sksl/ir/SkSLReturnStatement.h"
54 #include "src/sksl/ir/SkSLSetting.h"
55 #include "src/sksl/ir/SkSLStatement.h"
56 #include "src/sksl/ir/SkSLSwitchCase.h"
57 #include "src/sksl/ir/SkSLSwitchStatement.h"
58 #include "src/sksl/ir/SkSLSwizzle.h"
59 #include "src/sksl/ir/SkSLSymbolTable.h"
60 #include "src/sksl/ir/SkSLTernaryExpression.h"
61 #include "src/sksl/ir/SkSLType.h"
62 #include "src/sksl/ir/SkSLVarDeclarations.h"
63 #include "src/sksl/ir/SkSLVariable.h"
64 #include "src/sksl/ir/SkSLVariableReference.h"
65 #include "src/sksl/transform/SkSLTransform.h"
66 
67 #include <algorithm>
68 #include <climits>
69 #include <cstddef>
70 #include <memory>
71 #include <string>
72 #include <string_view>
73 #include <utility>
74 
75 using namespace skia_private;
76 
77 namespace SkSL {
78 namespace {
79 
80 static constexpr int kInlinedStatementLimit = 2500;
81 
is_scopeless_block(Statement * stmt)82 static bool is_scopeless_block(Statement* stmt) {
83     return stmt->is<Block>() && !stmt->as<Block>().isScope();
84 }
85 
find_parent_statement(const std::vector<std::unique_ptr<Statement> * > & stmtStack)86 static std::unique_ptr<Statement>* find_parent_statement(
87         const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
88     SkASSERT(!stmtStack.empty());
89 
90     // Walk the statement stack from back to front, ignoring the last element (which is the
91     // enclosing statement).
92     auto iter = stmtStack.rbegin();
93     ++iter;
94 
95     // Anything counts as a parent statement other than a scopeless Block.
96     for (; iter != stmtStack.rend(); ++iter) {
97         std::unique_ptr<Statement>* stmt = *iter;
98         if (!is_scopeless_block(stmt->get())) {
99             return stmt;
100         }
101     }
102 
103     // There wasn't any parent statement to be found.
104     return nullptr;
105 }
106 
clone_with_ref_kind(const Expression & expr,VariableReference::RefKind refKind,Position pos)107 std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
108                                                 VariableReference::RefKind refKind,
109                                                 Position pos) {
110     std::unique_ptr<Expression> clone = expr.clone(pos);
111     Analysis::UpdateVariableRefKind(clone.get(), refKind);
112     return clone;
113 }
114 
115 }  // namespace
116 
RemapVariable(const Variable * variable,const VariableRewriteMap * varMap)117 const Variable* Inliner::RemapVariable(const Variable* variable,
118                                        const VariableRewriteMap* varMap) {
119     std::unique_ptr<Expression>* remap = varMap->find(variable);
120     if (!remap) {
121         SkDEBUGFAILF("rewrite map does not contain variable '%.*s'",
122                      (int)variable->name().size(), variable->name().data());
123         return variable;
124     }
125     Expression* expr = remap->get();
126     SkASSERT(expr);
127     if (!expr->is<VariableReference>()) {
128         SkDEBUGFAILF("rewrite map contains non-variable replacement for '%.*s'",
129                      (int)variable->name().size(), variable->name().data());
130         return variable;
131     }
132     return expr->as<VariableReference>().variable();
133 }
134 
ensureScopedBlocks(Statement * inlinedBody,Statement * parentStmt)135 void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
136     // No changes necessary if this statement isn't actually a block.
137     if (!inlinedBody || !inlinedBody->is<Block>()) {
138         return;
139     }
140 
141     // No changes necessary if the parent statement doesn't require a scope.
142     if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
143                          parentStmt->is<DoStatement>() || is_scopeless_block(parentStmt))) {
144         return;
145     }
146 
147     Block& block = inlinedBody->as<Block>();
148 
149     // The inliner will create inlined function bodies as a Block containing multiple statements,
150     // but no scope. Normally, this is fine, but if this block is used as the statement for a
151     // do/for/if/while, the block needs to be scoped for the generated code to match the intent.
152     // In the case of Blocks nested inside other Blocks, we add the scope to the outermost block if
153     // needed.
154     for (Block* nestedBlock = &block;; ) {
155         if (nestedBlock->isScope()) {
156             // We found an explicit scope; all is well.
157             return;
158         }
159         if (nestedBlock->children().size() == 1 && nestedBlock->children()[0]->is<Block>()) {
160             // This block wraps another unscoped block; we need to go deeper.
161             nestedBlock = &nestedBlock->children()[0]->as<Block>();
162             continue;
163         }
164         // We found a block containing real statements (not just more blocks), but no scope.
165         // Let's add a scope to the outermost block.
166         block.setBlockKind(Block::Kind::kBracedScope);
167         return;
168     }
169 }
170 
inlineExpression(Position pos,VariableRewriteMap * varMap,SymbolTable * symbolTableForExpression,const Expression & expression)171 std::unique_ptr<Expression> Inliner::inlineExpression(Position pos,
172                                                       VariableRewriteMap* varMap,
173                                                       SymbolTable* symbolTableForExpression,
174                                                       const Expression& expression) {
175     auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
176         if (e) {
177             return this->inlineExpression(pos, varMap, symbolTableForExpression, *e);
178         }
179         return nullptr;
180     };
181     auto argList = [&](const ExpressionArray& originalArgs) -> ExpressionArray {
182         ExpressionArray args;
183         args.reserve_exact(originalArgs.size());
184         for (const std::unique_ptr<Expression>& arg : originalArgs) {
185             args.push_back(expr(arg));
186         }
187         return args;
188     };
189     auto childRemap = [&](const Variable& var) -> const Variable& {
190         // If our variable remapping table contains the passed-in variable...
191         if (std::unique_ptr<Expression>* remap = varMap->find(&var)) {
192             // ... the remapped expression _must_ be another variable reference.
193             // SkSL doesn't allow opaque types to participate in complex expressions.
194             if ((*remap)->is<VariableReference>()) {
195                 const VariableReference& remappedRef = (*remap)->as<VariableReference>();
196                 return *remappedRef.variable();
197             } else {
198                 SkDEBUGFAILF("Child effect '%.*s' remaps to unexpected expression '%s'",
199                              (int)var.name().size(), var.name().data(),
200                              (*remap)->description().c_str());
201             }
202         }
203 
204         // There's no remapping for this; return it as-is.
205         return var;
206     };
207 
208     switch (expression.kind()) {
209         case Expression::Kind::kBinary: {
210             const BinaryExpression& binaryExpr = expression.as<BinaryExpression>();
211             return BinaryExpression::Make(*fContext,
212                                           pos,
213                                           expr(binaryExpr.left()),
214                                           binaryExpr.getOperator(),
215                                           expr(binaryExpr.right()));
216         }
217         case Expression::Kind::kEmpty:
218             return expression.clone(pos);
219         case Expression::Kind::kLiteral:
220             return expression.clone(pos);
221         case Expression::Kind::kChildCall: {
222             const ChildCall& childCall = expression.as<ChildCall>();
223             return ChildCall::Make(*fContext,
224                                    pos,
225                                    childCall.type().clone(*fContext, symbolTableForExpression),
226                                    childRemap(childCall.child()),
227                                    argList(childCall.arguments()));
228         }
229         case Expression::Kind::kConstructorArray: {
230             const ConstructorArray& ctor = expression.as<ConstructorArray>();
231             return ConstructorArray::Make(*fContext,
232                                           pos,
233                                           *ctor.type().clone(*fContext, symbolTableForExpression),
234                                           argList(ctor.arguments()));
235         }
236         case Expression::Kind::kConstructorArrayCast: {
237             const ConstructorArrayCast& ctor = expression.as<ConstructorArrayCast>();
238             return ConstructorArrayCast::Make(
239                     *fContext,
240                     pos,
241                     *ctor.type().clone(*fContext, symbolTableForExpression),
242                     expr(ctor.argument()));
243         }
244         case Expression::Kind::kConstructorCompound: {
245             const ConstructorCompound& ctor = expression.as<ConstructorCompound>();
246             return ConstructorCompound::Make(
247                     *fContext,
248                     pos,
249                     *ctor.type().clone(*fContext, symbolTableForExpression),
250                     argList(ctor.arguments()));
251         }
252         case Expression::Kind::kConstructorCompoundCast: {
253             const ConstructorCompoundCast& ctor = expression.as<ConstructorCompoundCast>();
254             return ConstructorCompoundCast::Make(
255                     *fContext,
256                     pos,
257                     *ctor.type().clone(*fContext, symbolTableForExpression),
258                     expr(ctor.argument()));
259         }
260         case Expression::Kind::kConstructorDiagonalMatrix: {
261             const ConstructorDiagonalMatrix& ctor = expression.as<ConstructorDiagonalMatrix>();
262             return ConstructorDiagonalMatrix::Make(
263                     *fContext,
264                     pos,
265                     *ctor.type().clone(*fContext, symbolTableForExpression),
266                     expr(ctor.argument()));
267         }
268         case Expression::Kind::kConstructorMatrixResize: {
269             const ConstructorMatrixResize& ctor = expression.as<ConstructorMatrixResize>();
270             return ConstructorMatrixResize::Make(
271                     *fContext,
272                     pos,
273                     *ctor.type().clone(*fContext, symbolTableForExpression),
274                     expr(ctor.argument()));
275         }
276         case Expression::Kind::kConstructorScalarCast: {
277             const ConstructorScalarCast& ctor = expression.as<ConstructorScalarCast>();
278             return ConstructorScalarCast::Make(
279                     *fContext,
280                     pos,
281                     *ctor.type().clone(*fContext, symbolTableForExpression),
282                     expr(ctor.argument()));
283         }
284         case Expression::Kind::kConstructorSplat: {
285             const ConstructorSplat& ctor = expression.as<ConstructorSplat>();
286             return ConstructorSplat::Make(*fContext,
287                                           pos,
288                                           *ctor.type().clone(*fContext, symbolTableForExpression),
289                                           expr(ctor.argument()));
290         }
291         case Expression::Kind::kConstructorStruct: {
292             const ConstructorStruct& ctor = expression.as<ConstructorStruct>();
293             return ConstructorStruct::Make(*fContext,
294                                            pos,
295                                            *ctor.type().clone(*fContext, symbolTableForExpression),
296                                            argList(ctor.arguments()));
297         }
298         case Expression::Kind::kFieldAccess: {
299             const FieldAccess& f = expression.as<FieldAccess>();
300             return FieldAccess::Make(*fContext, pos, expr(f.base()), f.fieldIndex(), f.ownerKind());
301         }
302         case Expression::Kind::kFunctionCall: {
303             const FunctionCall& funcCall = expression.as<FunctionCall>();
304             return FunctionCall::Make(*fContext,
305                                       pos,
306                                       funcCall.type().clone(*fContext, symbolTableForExpression),
307                                       funcCall.function(),
308                                       argList(funcCall.arguments()));
309         }
310         case Expression::Kind::kFunctionReference:
311             return expression.clone(pos);
312         case Expression::Kind::kIndex: {
313             const IndexExpression& idx = expression.as<IndexExpression>();
314             return IndexExpression::Make(*fContext, pos, expr(idx.base()), expr(idx.index()));
315         }
316         case Expression::Kind::kMethodReference:
317             return expression.clone(pos);
318         case Expression::Kind::kPrefix: {
319             const PrefixExpression& p = expression.as<PrefixExpression>();
320             return PrefixExpression::Make(*fContext, pos, p.getOperator(), expr(p.operand()));
321         }
322         case Expression::Kind::kPostfix: {
323             const PostfixExpression& p = expression.as<PostfixExpression>();
324             return PostfixExpression::Make(*fContext, pos, expr(p.operand()), p.getOperator());
325         }
326         case Expression::Kind::kSetting: {
327             const Setting& s = expression.as<Setting>();
328             return Setting::Make(*fContext, pos, s.capsPtr());
329         }
330         case Expression::Kind::kSwizzle: {
331             const Swizzle& s = expression.as<Swizzle>();
332             return Swizzle::Make(*fContext, pos, expr(s.base()), s.components());
333         }
334         case Expression::Kind::kTernary: {
335             const TernaryExpression& t = expression.as<TernaryExpression>();
336             return TernaryExpression::Make(*fContext, pos, expr(t.test()),
337                                            expr(t.ifTrue()), expr(t.ifFalse()));
338         }
339         case Expression::Kind::kTypeReference:
340             return expression.clone(pos);
341         case Expression::Kind::kVariableReference: {
342             const VariableReference& v = expression.as<VariableReference>();
343             std::unique_ptr<Expression>* remap = varMap->find(v.variable());
344             if (remap) {
345                 return clone_with_ref_kind(**remap, v.refKind(), pos);
346             }
347             return expression.clone(pos);
348         }
349         default:
350             SkDEBUGFAILF("unsupported expression: %s", expression.description().c_str());
351             return nullptr;
352     }
353 }
354 
inlineStatement(Position pos,VariableRewriteMap * varMap,SymbolTable * symbolTableForStatement,std::unique_ptr<Expression> * resultExpr,Analysis::ReturnComplexity returnComplexity,const Statement & statement,const ProgramUsage & usage,bool isBuiltinCode)355 std::unique_ptr<Statement> Inliner::inlineStatement(Position pos,
356                                                     VariableRewriteMap* varMap,
357                                                     SymbolTable* symbolTableForStatement,
358                                                     std::unique_ptr<Expression>* resultExpr,
359                                                     Analysis::ReturnComplexity returnComplexity,
360                                                     const Statement& statement,
361                                                     const ProgramUsage& usage,
362                                                     bool isBuiltinCode) {
363     auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
364         if (s) {
365             return this->inlineStatement(pos, varMap, symbolTableForStatement, resultExpr,
366                                          returnComplexity, *s, usage, isBuiltinCode);
367         }
368         return nullptr;
369     };
370     auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
371         if (e) {
372             return this->inlineExpression(pos, varMap, symbolTableForStatement, *e);
373         }
374         return nullptr;
375     };
376     auto variableModifiers = [&](const Variable& variable,
377                                  const Expression* initialValue) -> ModifierFlags {
378         return Transform::AddConstToVarModifiers(variable, initialValue, &usage);
379     };
380     auto makeWithChildSymbolTable = [&](auto callback) -> std::unique_ptr<Statement> {
381         SymbolTable* origSymbolTable = symbolTableForStatement;
382         auto childSymbols = std::make_unique<SymbolTable>(origSymbolTable, isBuiltinCode);
383         symbolTableForStatement = childSymbols.get();
384 
385         std::unique_ptr<Statement> stmt = callback(std::move(childSymbols));
386 
387         symbolTableForStatement = origSymbolTable;
388         return stmt;
389     };
390 
391     ++fInlinedStatementCounter;
392 
393     switch (statement.kind()) {
394         case Statement::Kind::kBlock:
395             return makeWithChildSymbolTable([&](std::unique_ptr<SymbolTable> symbolTable) {
396                 const Block& block = statement.as<Block>();
397                 StatementArray statements;
398                 statements.reserve_exact(block.children().size());
399                 for (const std::unique_ptr<Statement>& child : block.children()) {
400                     statements.push_back(stmt(child));
401                 }
402                 return Block::Make(pos,
403                                    std::move(statements),
404                                    block.blockKind(),
405                                    std::move(symbolTable));
406             });
407 
408         case Statement::Kind::kBreak:
409             return BreakStatement::Make(pos);
410 
411         case Statement::Kind::kContinue:
412             return ContinueStatement::Make(pos);
413 
414         case Statement::Kind::kDiscard:
415             return DiscardStatement::Make(*fContext, pos);
416 
417         case Statement::Kind::kDo: {
418             const DoStatement& d = statement.as<DoStatement>();
419             return DoStatement::Make(*fContext, pos, stmt(d.statement()), expr(d.test()));
420         }
421         case Statement::Kind::kExpression: {
422             const ExpressionStatement& e = statement.as<ExpressionStatement>();
423             return ExpressionStatement::Make(*fContext, expr(e.expression()));
424         }
425         case Statement::Kind::kFor:
426             return makeWithChildSymbolTable([&](std::unique_ptr<SymbolTable> symbolTable) {
427                 const ForStatement& f = statement.as<ForStatement>();
428                 // We need to ensure `initializer` is evaluated first, so that we've already
429                 // remapped its declaration by the time we evaluate `test` and `next`.
430                 std::unique_ptr<Statement> initializerStmt = stmt(f.initializer());
431                 std::unique_ptr<Expression> testExpr = expr(f.test());
432                 std::unique_ptr<Expression> nextExpr = expr(f.next());
433                 std::unique_ptr<Statement> bodyStmt = stmt(f.statement());
434 
435                 std::unique_ptr<LoopUnrollInfo> unrollInfo;
436                 if (f.unrollInfo()) {
437                     // The for loop's unroll-info points to the Variable in the initializer as the
438                     // index. This variable has been rewritten into a clone by the inliner, so we
439                     // need to update the loop-unroll info to point to the clone.
440                     unrollInfo = std::make_unique<LoopUnrollInfo>(*f.unrollInfo());
441                     unrollInfo->fIndex = RemapVariable(unrollInfo->fIndex, varMap);
442                 }
443 
444                 return ForStatement::Make(*fContext, pos, ForLoopPositions{},
445                                           std::move(initializerStmt),
446                                           std::move(testExpr),
447                                           std::move(nextExpr),
448                                           std::move(bodyStmt),
449                                           std::move(unrollInfo),
450                                           std::move(symbolTable));
451             });
452 
453         case Statement::Kind::kIf: {
454             const IfStatement& i = statement.as<IfStatement>();
455             return IfStatement::Make(*fContext, pos, expr(i.test()),
456                                      stmt(i.ifTrue()), stmt(i.ifFalse()));
457         }
458         case Statement::Kind::kNop:
459             return Nop::Make();
460 
461         case Statement::Kind::kReturn: {
462             const ReturnStatement& r = statement.as<ReturnStatement>();
463             if (!r.expression()) {
464                 // This function doesn't return a value. We won't inline functions with early
465                 // returns, so a return statement is a no-op and can be treated as such.
466                 return Nop::Make();
467             }
468 
469             // If a function only contains a single return, and it doesn't reference variables from
470             // inside an Block's scope, we don't need to store the result in a variable at all. Just
471             // replace the function-call expression with the function's return expression.
472             SkASSERT(resultExpr);
473             if (returnComplexity <= Analysis::ReturnComplexity::kSingleSafeReturn) {
474                 *resultExpr = expr(r.expression());
475                 return Nop::Make();
476             }
477 
478             // For more complex functions, we assign their result into a variable. We refuse to
479             // inline anything with early returns, so this should be safe to do; that is, on this
480             // control path, this is the last statement that will occur.
481             SkASSERT(*resultExpr);
482             return ExpressionStatement::Make(
483                     *fContext,
484                     BinaryExpression::Make(
485                             *fContext,
486                             pos,
487                             clone_with_ref_kind(**resultExpr, VariableRefKind::kWrite, pos),
488                             Operator::Kind::EQ,
489                             expr(r.expression())));
490         }
491         case Statement::Kind::kSwitch: {
492             const SwitchStatement& ss = statement.as<SwitchStatement>();
493             return SwitchStatement::Make(*fContext, pos, expr(ss.value()), stmt(ss.caseBlock()));
494         }
495         case Statement::Kind::kSwitchCase: {
496             const SwitchCase& sc = statement.as<SwitchCase>();
497             return sc.isDefault() ? SwitchCase::MakeDefault(pos, stmt(sc.statement()))
498                                   : SwitchCase::Make(pos, sc.value(), stmt(sc.statement()));
499         }
500         case Statement::Kind::kVarDeclaration: {
501             const VarDeclaration& decl = statement.as<VarDeclaration>();
502             std::unique_ptr<Expression> initialValue = expr(decl.value());
503             const Variable* variable = decl.var();
504 
505             // We assign unique names to inlined variables--scopes hide most of the problems in this
506             // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
507             // names are important.
508             const std::string* name = symbolTableForStatement->takeOwnershipOfString(
509                     fMangler.uniqueName(variable->name(), symbolTableForStatement));
510             auto clonedVar =
511                     Variable::Make(pos,
512                                    variable->modifiersPosition(),
513                                    variable->layout(),
514                                    variableModifiers(*variable, initialValue.get()),
515                                    variable->type().clone(*fContext, symbolTableForStatement),
516                                    name->c_str(),
517                                    /*mangledName=*/"",
518                                    isBuiltinCode,
519                                    variable->storage());
520             varMap->set(variable, VariableReference::Make(pos, clonedVar.get()));
521             std::unique_ptr<Statement> result =
522                     VarDeclaration::Make(*fContext,
523                                          clonedVar.get(),
524                                          decl.baseType().clone(*fContext, symbolTableForStatement),
525                                          decl.arraySize(),
526                                          std::move(initialValue));
527             symbolTableForStatement->add(*fContext, std::move(clonedVar));
528             return result;
529         }
530         default:
531             SkASSERT(false);
532             return nullptr;
533     }
534 }
535 
argument_needs_scratch_variable(const Expression * arg,const Variable * param,const ProgramUsage & usage)536 static bool argument_needs_scratch_variable(const Expression* arg,
537                                             const Variable* param,
538                                             const ProgramUsage& usage) {
539     // If the parameter isn't written to within the inline function ...
540     const ProgramUsage::VariableCounts& paramUsage = usage.get(*param);
541     if (!paramUsage.fWrite) {
542         // ... and it can be inlined trivially (e.g. a swizzle, or a constant array index),
543         // or it is any expression without side effects that is only accessed at most once...
544         if ((paramUsage.fRead > 1) ? Analysis::IsTrivialExpression(*arg)
545                                    : !Analysis::HasSideEffects(*arg)) {
546             // ... we don't need to copy it at all! We can just use the existing expression.
547             return false;
548         }
549     }
550     // We need a scratch variable.
551     return true;
552 }
553 
inlineCall(const FunctionCall & call,SymbolTable * symbolTable,const ProgramUsage & usage,const FunctionDeclaration * caller)554 Inliner::InlinedCall Inliner::inlineCall(const FunctionCall& call,
555                                          SymbolTable* symbolTable,
556                                          const ProgramUsage& usage,
557                                          const FunctionDeclaration* caller) {
558     using ScratchVariable = Variable::ScratchVariable;
559 
560     // Inlining is more complicated here than in a typical compiler, because we have to have a
561     // high-level IR and can't just drop statements into the middle of an expression or even use
562     // gotos.
563     //
564     // Since we can't insert statements into an expression, we run the inline function as extra
565     // statements before the statement we're currently processing, relying on a lack of execution
566     // order guarantees.
567     SkASSERT(fContext);
568     SkASSERT(this->isSafeToInline(call.function().definition(), usage));
569 
570     const ExpressionArray& arguments = call.arguments();
571     const Position pos = call.fPosition;
572     const FunctionDefinition& function = *call.function().definition();
573     const Block& body = function.body()->as<Block>();
574     const Analysis::ReturnComplexity returnComplexity = Analysis::GetReturnComplexity(function);
575 
576     StatementArray inlineStatements;
577     int expectedStmtCount = 1 +                      // Result variable
578                             arguments.size() +       // Function argument temp-vars
579                             body.children().size();  // Inlined code
580 
581     inlineStatements.reserve_exact(expectedStmtCount);
582 
583     std::unique_ptr<Expression> resultExpr;
584     if (returnComplexity > Analysis::ReturnComplexity::kSingleSafeReturn &&
585         !function.declaration().returnType().isVoid()) {
586         // Create a variable to hold the result in the extra statements. We don't need to do this
587         // for void-return functions, or in cases that are simple enough that we can just replace
588         // the function-call node with the result expression.
589         ScratchVariable var = Variable::MakeScratchVariable(*fContext,
590                                                             fMangler,
591                                                             function.declaration().name(),
592                                                             &function.declaration().returnType(),
593                                                             symbolTable,
594                                                             /*initialValue=*/nullptr);
595         inlineStatements.push_back(std::move(var.fVarDecl));
596         resultExpr = VariableReference::Make(Position(), var.fVarSymbol);
597     }
598 
599     // Create variables in the extra statements to hold the arguments, and assign the arguments to
600     // them.
601     VariableRewriteMap varMap;
602     for (int i = 0; i < arguments.size(); ++i) {
603         const Expression* arg = arguments[i].get();
604         const Variable* param = function.declaration().parameters()[i];
605         if (!argument_needs_scratch_variable(arg, param, usage)) {
606             varMap.set(param, arg->clone());
607             continue;
608         }
609         ScratchVariable var = Variable::MakeScratchVariable(*fContext,
610                                                             fMangler,
611                                                             param->name(),
612                                                             &arg->type(),
613                                                             symbolTable,
614                                                             arg->clone());
615         inlineStatements.push_back(std::move(var.fVarDecl));
616         varMap.set(param, VariableReference::Make(Position(), var.fVarSymbol));
617     }
618 
619     for (const std::unique_ptr<Statement>& stmt : body.children()) {
620         inlineStatements.push_back(this->inlineStatement(pos, &varMap, symbolTable,
621                                                          &resultExpr, returnComplexity, *stmt,
622                                                          usage, caller->isBuiltin()));
623     }
624 
625     SkASSERT(inlineStatements.size() <= expectedStmtCount);
626 
627     // Wrap all of the generated statements in a block. We need a real Block here, because we need
628     // to add another child statement to the Block later.
629     InlinedCall inlinedCall;
630     inlinedCall.fInlinedBody = Block::MakeBlock(pos, std::move(inlineStatements),
631                                                 Block::Kind::kUnbracedBlock);
632     if (resultExpr) {
633         // Return our result expression as-is.
634         inlinedCall.fReplacementExpr = std::move(resultExpr);
635     } else if (function.declaration().returnType().isVoid()) {
636         // It's a void function, so its result is the empty expression.
637         inlinedCall.fReplacementExpr = EmptyExpression::Make(pos, *fContext);
638     } else {
639         // It's a non-void function, but it never created a result expression--that is, it never
640         // returned anything on any path! This should have been detected in the function finalizer.
641         // Still, discard our output and generate an error.
642         SkDEBUGFAIL("inliner found non-void function that fails to return a value on any path");
643         fContext->fErrors->error(function.fPosition, "inliner found non-void function '" +
644                                                      std::string(function.declaration().name()) +
645                                                      "' that fails to return a value on any path");
646         inlinedCall = {};
647     }
648 
649     return inlinedCall;
650 }
651 
isSafeToInline(const FunctionDefinition * functionDef,const ProgramUsage & usage)652 bool Inliner::isSafeToInline(const FunctionDefinition* functionDef, const ProgramUsage& usage) {
653     // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
654     if (this->settings().fInlineThreshold <= 0) {
655         return false;
656     }
657 
658     // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
659     if (fInlinedStatementCounter >= kInlinedStatementLimit) {
660         return false;
661     }
662 
663     if (functionDef == nullptr) {
664         // Can't inline something if we don't actually have its definition.
665         return false;
666     }
667 
668     if (functionDef->declaration().modifierFlags().isNoInline()) {
669         // Refuse to inline functions decorated with `noinline`.
670         return false;
671     }
672 
673     for (const Variable* param : functionDef->declaration().parameters()) {
674         // We don't allow inlining functions with parameters that are written-to, if they...
675         // - are `out` parameters (see skia:11326 for rationale.)
676         // - are arrays or structures (introducing temporary copies is non-trivial)
677         if ((param->modifierFlags() & ModifierFlag::kOut) ||
678             param->type().isArray() ||
679             param->type().isStruct()) {
680             ProgramUsage::VariableCounts counts = usage.get(*param);
681             if (counts.fWrite > 0) {
682                 return false;
683             }
684         }
685     }
686 
687     // We don't have a mechanism to simulate early returns, so we can't inline if there is one.
688     return Analysis::GetReturnComplexity(*functionDef) < Analysis::ReturnComplexity::kEarlyReturns;
689 }
690 
691 // A candidate function for inlining, containing everything that `inlineCall` needs.
692 struct InlineCandidate {
693     SymbolTable* fSymbols;                        // the SymbolTable of the candidate
694     std::unique_ptr<Statement>* fParentStmt;      // the parent Statement of the enclosing stmt
695     std::unique_ptr<Statement>* fEnclosingStmt;   // the Statement containing the candidate
696     std::unique_ptr<Expression>* fCandidateExpr;  // the candidate FunctionCall to be inlined
697     FunctionDefinition* fEnclosingFunction;       // the Function containing the candidate
698 };
699 
700 struct InlineCandidateList {
701     std::vector<InlineCandidate> fCandidates;
702 };
703 
704 class InlineCandidateAnalyzer {
705 public:
706     // A list of all the inlining candidates we found during analysis.
707     InlineCandidateList* fCandidateList;
708 
709     // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
710     // the enclosing-statement stack.
711     std::vector<SymbolTable*> fSymbolTableStack;
712     // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
713     // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
714     // inliner might replace a statement with a block containing the statement.
715     std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
716     // The function that we're currently processing (i.e. inlining into).
717     FunctionDefinition* fEnclosingFunction = nullptr;
718 
visit(const std::vector<std::unique_ptr<ProgramElement>> & elements,SymbolTable * symbols,InlineCandidateList * candidateList)719     void visit(const std::vector<std::unique_ptr<ProgramElement>>& elements,
720                SymbolTable* symbols,
721                InlineCandidateList* candidateList) {
722         fCandidateList = candidateList;
723         fSymbolTableStack.push_back(symbols);
724 
725         for (const std::unique_ptr<ProgramElement>& pe : elements) {
726             this->visitProgramElement(pe.get());
727         }
728 
729         fSymbolTableStack.pop_back();
730         fCandidateList = nullptr;
731     }
732 
visitProgramElement(ProgramElement * pe)733     void visitProgramElement(ProgramElement* pe) {
734         switch (pe->kind()) {
735             case ProgramElement::Kind::kFunction: {
736                 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
737 
738                 // If this function has parameter names that would shadow globally-scoped names, we
739                 // don't scan it for inline candidates, because it's too late to mangle the names.
740                 bool foundShadowingParameterName = false;
741                 for (const Variable* param : funcDef.declaration().parameters()) {
742                     if (fSymbolTableStack.front()->find(param->name())) {
743                         foundShadowingParameterName = true;
744                         break;
745                     }
746                 }
747 
748                 if (!foundShadowingParameterName) {
749                     fEnclosingFunction = &funcDef;
750                     this->visitStatement(&funcDef.body());
751                 }
752                 break;
753             }
754             default:
755                 // The inliner can't operate outside of a function's scope.
756                 break;
757         }
758     }
759 
visitStatement(std::unique_ptr<Statement> * stmt,bool isViableAsEnclosingStatement=true)760     void visitStatement(std::unique_ptr<Statement>* stmt,
761                         bool isViableAsEnclosingStatement = true) {
762         if (!*stmt) {
763             return;
764         }
765 
766         Analysis::SymbolTableStackBuilder scopedStackBuilder(stmt->get(), &fSymbolTableStack);
767         // If this statement contains symbols that would shadow globally-scoped names, we don't look
768         // for any inline candidates, because it's too late to mangle the names.
769         if (scopedStackBuilder.foundSymbolTable() &&
770             fSymbolTableStack.back()->wouldShadowSymbolsFrom(fSymbolTableStack.front())) {
771             return;
772         }
773 
774         size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
775 
776         if (isViableAsEnclosingStatement) {
777             fEnclosingStmtStack.push_back(stmt);
778         }
779 
780         switch ((*stmt)->kind()) {
781             case Statement::Kind::kBreak:
782             case Statement::Kind::kContinue:
783             case Statement::Kind::kDiscard:
784             case Statement::Kind::kNop:
785                 break;
786 
787             case Statement::Kind::kBlock: {
788                 Block& block = (*stmt)->as<Block>();
789                 for (std::unique_ptr<Statement>& blockStmt : block.children()) {
790                     this->visitStatement(&blockStmt);
791                 }
792                 break;
793             }
794             case Statement::Kind::kDo: {
795                 DoStatement& doStmt = (*stmt)->as<DoStatement>();
796                 // The loop body is a candidate for inlining.
797                 this->visitStatement(&doStmt.statement());
798                 // The inliner isn't smart enough to inline the test-expression for a do-while
799                 // loop at this time. There are two limitations:
800                 // - We would need to insert the inlined-body block at the very end of the do-
801                 //   statement's inner fStatement. We don't support that today, but it's doable.
802                 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
803                 //   would skip over the inlined block that evaluates the test expression. There
804                 //   isn't a good fix for this--any workaround would be more complex than the cost
805                 //   of a function call. However, loops that don't use `continue` would still be
806                 //   viable candidates for inlining.
807                 break;
808             }
809             case Statement::Kind::kExpression: {
810                 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
811                 this->visitExpression(&expr.expression());
812                 break;
813             }
814             case Statement::Kind::kFor: {
815                 ForStatement& forStmt = (*stmt)->as<ForStatement>();
816                 // The initializer and loop body are candidates for inlining.
817                 this->visitStatement(&forStmt.initializer(),
818                                      /*isViableAsEnclosingStatement=*/false);
819                 this->visitStatement(&forStmt.statement());
820 
821                 // The inliner isn't smart enough to inline the test- or increment-expressions
822                 // of a for loop loop at this time. There are a handful of limitations:
823                 // - We would need to insert the test-expression block at the very beginning of the
824                 //   for-loop's inner fStatement, and the increment-expression block at the very
825                 //   end. We don't support that today, but it's doable.
826                 // - The for-loop's built-in test-expression would need to be dropped entirely,
827                 //   and the loop would be halted via a break statement at the end of the inlined
828                 //   test-expression. This is again something we don't support today, but it could
829                 //   be implemented.
830                 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
831                 //   that would skip over the inlined block that evaluates the increment expression.
832                 //   There isn't a good fix for this--any workaround would be more complex than the
833                 //   cost of a function call. However, loops that don't use `continue` would still
834                 //   be viable candidates for increment-expression inlining.
835                 break;
836             }
837             case Statement::Kind::kIf: {
838                 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
839                 this->visitExpression(&ifStmt.test());
840                 this->visitStatement(&ifStmt.ifTrue());
841                 this->visitStatement(&ifStmt.ifFalse());
842                 break;
843             }
844             case Statement::Kind::kReturn: {
845                 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
846                 this->visitExpression(&returnStmt.expression());
847                 break;
848             }
849             case Statement::Kind::kSwitch: {
850                 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
851                 this->visitExpression(&switchStmt.value());
852                 for (const std::unique_ptr<Statement>& switchCase : switchStmt.cases()) {
853                     // The switch-case's fValue cannot be a FunctionCall; skip it.
854                     this->visitStatement(&switchCase->as<SwitchCase>().statement());
855                 }
856                 break;
857             }
858             case Statement::Kind::kVarDeclaration: {
859                 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
860                 // Don't need to scan the declaration's sizes; those are always literals.
861                 this->visitExpression(&varDeclStmt.value());
862                 break;
863             }
864             default:
865                 SkUNREACHABLE;
866         }
867 
868         // Pop our symbol and enclosing-statement stacks.
869         fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
870     }
871 
visitExpression(std::unique_ptr<Expression> * expr)872     void visitExpression(std::unique_ptr<Expression>* expr) {
873         if (!*expr) {
874             return;
875         }
876 
877         switch ((*expr)->kind()) {
878             case Expression::Kind::kFieldAccess:
879             case Expression::Kind::kFunctionReference:
880             case Expression::Kind::kLiteral:
881             case Expression::Kind::kMethodReference:
882             case Expression::Kind::kSetting:
883             case Expression::Kind::kTypeReference:
884             case Expression::Kind::kVariableReference:
885                 // Nothing to scan here.
886                 break;
887 
888             case Expression::Kind::kBinary: {
889                 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
890                 this->visitExpression(&binaryExpr.left());
891 
892                 // Logical-and and logical-or binary expressions do not inline the right side,
893                 // because that would invalidate short-circuiting. That is, when evaluating
894                 // expressions like these:
895                 //    (false && x())   // always false
896                 //    (true || y())    // always true
897                 // It is illegal for side-effects from x() or y() to occur. The simplest way to
898                 // enforce that rule is to avoid inlining the right side entirely. However, it is
899                 // safe for other types of binary expression to inline both sides.
900                 Operator op = binaryExpr.getOperator();
901                 bool shortCircuitable = (op.kind() == Operator::Kind::LOGICALAND ||
902                                          op.kind() == Operator::Kind::LOGICALOR);
903                 if (!shortCircuitable) {
904                     this->visitExpression(&binaryExpr.right());
905                 }
906                 break;
907             }
908             case Expression::Kind::kChildCall: {
909                 ChildCall& childCallExpr = (*expr)->as<ChildCall>();
910                 for (std::unique_ptr<Expression>& arg : childCallExpr.arguments()) {
911                     this->visitExpression(&arg);
912                 }
913                 break;
914             }
915             case Expression::Kind::kConstructorArray:
916             case Expression::Kind::kConstructorArrayCast:
917             case Expression::Kind::kConstructorCompound:
918             case Expression::Kind::kConstructorCompoundCast:
919             case Expression::Kind::kConstructorDiagonalMatrix:
920             case Expression::Kind::kConstructorMatrixResize:
921             case Expression::Kind::kConstructorScalarCast:
922             case Expression::Kind::kConstructorSplat:
923             case Expression::Kind::kConstructorStruct: {
924                 AnyConstructor& constructorExpr = (*expr)->asAnyConstructor();
925                 for (std::unique_ptr<Expression>& arg : constructorExpr.argumentSpan()) {
926                     this->visitExpression(&arg);
927                 }
928                 break;
929             }
930             case Expression::Kind::kFunctionCall: {
931                 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
932                 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
933                     this->visitExpression(&arg);
934                 }
935                 this->addInlineCandidate(expr);
936                 break;
937             }
938             case Expression::Kind::kIndex: {
939                 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
940                 this->visitExpression(&indexExpr.base());
941                 this->visitExpression(&indexExpr.index());
942                 break;
943             }
944             case Expression::Kind::kPostfix: {
945                 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
946                 this->visitExpression(&postfixExpr.operand());
947                 break;
948             }
949             case Expression::Kind::kPrefix: {
950                 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
951                 this->visitExpression(&prefixExpr.operand());
952                 break;
953             }
954             case Expression::Kind::kSwizzle: {
955                 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
956                 this->visitExpression(&swizzleExpr.base());
957                 break;
958             }
959             case Expression::Kind::kTernary: {
960                 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
961                 // The test expression is a candidate for inlining.
962                 this->visitExpression(&ternaryExpr.test());
963                 // The true- and false-expressions cannot be inlined, because we are only allowed to
964                 // evaluate one side.
965                 break;
966             }
967             default:
968                 SkUNREACHABLE;
969         }
970     }
971 
addInlineCandidate(std::unique_ptr<Expression> * candidate)972     void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
973         fCandidateList->fCandidates.push_back(
974                 InlineCandidate{fSymbolTableStack.back(),
975                                 find_parent_statement(fEnclosingStmtStack),
976                                 fEnclosingStmtStack.back(),
977                                 candidate,
978                                 fEnclosingFunction});
979     }
980 };
981 
candidate_func(const InlineCandidate & candidate)982 static const FunctionDeclaration& candidate_func(const InlineCandidate& candidate) {
983     return (*candidate.fCandidateExpr)->as<FunctionCall>().function();
984 }
985 
functionCanBeInlined(const FunctionDeclaration & funcDecl,const ProgramUsage & usage,InlinabilityCache * cache)986 bool Inliner::functionCanBeInlined(const FunctionDeclaration& funcDecl,
987                                    const ProgramUsage& usage,
988                                    InlinabilityCache* cache) {
989     if (const bool* cachedInlinability = cache->find(&funcDecl)) {
990         return *cachedInlinability;
991     }
992     bool inlinability = this->isSafeToInline(funcDecl.definition(), usage);
993     cache->set(&funcDecl, inlinability);
994     return inlinability;
995 }
996 
candidateCanBeInlined(const InlineCandidate & candidate,const ProgramUsage & usage,InlinabilityCache * cache)997 bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate,
998                                     const ProgramUsage& usage,
999                                     InlinabilityCache* cache) {
1000     // Check the cache to see if this function is safe to inline.
1001     const FunctionDeclaration& funcDecl = candidate_func(candidate);
1002     if (!this->functionCanBeInlined(funcDecl, usage, cache)) {
1003         return false;
1004     }
1005 
1006     // Even if the function is safe, the arguments we are passing may not be. In particular, we
1007     // can't make copies of opaque values, so we need to reject inline candidates that would need to
1008     // do this. Every call has different arguments, so this part is not cacheable. (skia:13824)
1009     const FunctionCall& call = candidate.fCandidateExpr->get()->as<FunctionCall>();
1010     const ExpressionArray& arguments = call.arguments();
1011     for (int i = 0; i < arguments.size(); ++i) {
1012         const Expression* arg = arguments[i].get();
1013         if (arg->type().isOpaque()) {
1014             const Variable* param = funcDecl.parameters()[i];
1015             if (argument_needs_scratch_variable(arg, param, usage)) {
1016                 return false;
1017             }
1018         }
1019     }
1020 
1021     return true;
1022 }
1023 
getFunctionSize(const FunctionDeclaration & funcDecl,FunctionSizeCache * cache)1024 int Inliner::getFunctionSize(const FunctionDeclaration& funcDecl, FunctionSizeCache* cache) {
1025     if (const int* cachedSize = cache->find(&funcDecl)) {
1026         return *cachedSize;
1027     }
1028     int size = Analysis::NodeCountUpToLimit(*funcDecl.definition(),
1029                                             this->settings().fInlineThreshold);
1030     cache->set(&funcDecl, size);
1031     return size;
1032 }
1033 
buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>> & elements,SymbolTable * symbols,ProgramUsage * usage,InlineCandidateList * candidateList)1034 void Inliner::buildCandidateList(const std::vector<std::unique_ptr<ProgramElement>>& elements,
1035                                  SymbolTable* symbols,
1036                                  ProgramUsage* usage,
1037                                  InlineCandidateList* candidateList) {
1038     // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1039     // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1040     // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1041     // `const T&`.
1042     InlineCandidateAnalyzer analyzer;
1043     analyzer.visit(elements, symbols, candidateList);
1044 
1045     // Early out if there are no inlining candidates.
1046     std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
1047     if (candidates.empty()) {
1048         return;
1049     }
1050 
1051     // Remove candidates that are not safe to inline.
1052     InlinabilityCache cache;
1053     candidates.erase(std::remove_if(candidates.begin(),
1054                                     candidates.end(),
1055                                     [&](const InlineCandidate& candidate) {
1056                                         return !this->candidateCanBeInlined(
1057                                                 candidate, *usage, &cache);
1058                                     }),
1059                      candidates.end());
1060 
1061     // If the inline threshold is unlimited, or if we have no candidates left, our candidate list is
1062     // complete.
1063     if (this->settings().fInlineThreshold == INT_MAX || candidates.empty()) {
1064         return;
1065     }
1066 
1067     // Remove candidates on a per-function basis if the effect of inlining would be to make more
1068     // than `inlineThreshold` nodes. (i.e. if Func() would be inlined six times and its size is
1069     // 10 nodes, it should be inlined if the inlineThreshold is 60 or higher.)
1070     FunctionSizeCache functionSizeCache;
1071     FunctionSizeCache candidateTotalCost;
1072     for (InlineCandidate& candidate : candidates) {
1073         const FunctionDeclaration& fnDecl = candidate_func(candidate);
1074         candidateTotalCost[&fnDecl] += this->getFunctionSize(fnDecl, &functionSizeCache);
1075     }
1076 
1077     candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
1078                         [&](const InlineCandidate& candidate) {
1079                             const FunctionDeclaration& fnDecl = candidate_func(candidate);
1080                             if (fnDecl.modifierFlags().isInline()) {
1081                                 // Functions marked `inline` ignore size limitations.
1082                                 return false;
1083                             }
1084                             if (usage->get(fnDecl) == 1) {
1085                                 // If a function is only used once, it's cost-free to inline.
1086                                 return false;
1087                             }
1088                             if (candidateTotalCost[&fnDecl] <= this->settings().fInlineThreshold) {
1089                                 // We won't exceed the inline threshold by inlining this.
1090                                 return false;
1091                             }
1092                             // Inlining this function will add too many IRNodes.
1093                             return true;
1094                         }),
1095          candidates.end());
1096 }
1097 
analyze(const std::vector<std::unique_ptr<ProgramElement>> & elements,SymbolTable * symbols,ProgramUsage * usage)1098 bool Inliner::analyze(const std::vector<std::unique_ptr<ProgramElement>>& elements,
1099                       SymbolTable* symbols,
1100                       ProgramUsage* usage) {
1101     // A threshold of zero indicates that the inliner is completely disabled, so we can just return.
1102     if (this->settings().fInlineThreshold <= 0) {
1103         return false;
1104     }
1105 
1106     // Enforce a limit on inlining to avoid pathological cases. (inliner/ExponentialGrowth.sksl)
1107     if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1108         return false;
1109     }
1110 
1111     InlineCandidateList candidateList;
1112     this->buildCandidateList(elements, symbols, usage, &candidateList);
1113 
1114     // Inline the candidates where we've determined that it's safe to do so.
1115     using StatementRemappingTable = THashMap<std::unique_ptr<Statement>*,
1116                                              std::unique_ptr<Statement>*>;
1117     StatementRemappingTable statementRemappingTable;
1118 
1119     bool madeChanges = false;
1120     for (const InlineCandidate& candidate : candidateList.fCandidates) {
1121         const FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1122 
1123         // Convert the function call to its inlined equivalent.
1124         InlinedCall inlinedCall = this->inlineCall(funcCall, candidate.fSymbols, *usage,
1125                                                    &candidate.fEnclosingFunction->declaration());
1126 
1127         // Stop if an error was detected during the inlining process.
1128         if (!inlinedCall.fInlinedBody && !inlinedCall.fReplacementExpr) {
1129             break;
1130         }
1131 
1132         // Ensure that the inlined body has a scope if it needs one.
1133         this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
1134 
1135         // Add references within the inlined body
1136         usage->add(inlinedCall.fInlinedBody.get());
1137 
1138         // Look up the enclosing statement; remap it if necessary.
1139         std::unique_ptr<Statement>* enclosingStmt = candidate.fEnclosingStmt;
1140         for (;;) {
1141             std::unique_ptr<Statement>** remappedStmt = statementRemappingTable.find(enclosingStmt);
1142             if (!remappedStmt) {
1143                 break;
1144             }
1145             enclosingStmt = *remappedStmt;
1146         }
1147 
1148         // Move the enclosing statement to the end of the unscoped Block containing the inlined
1149         // function, then replace the enclosing statement with that Block.
1150         // Before:
1151         //     fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1152         //     fEnclosingStmt = stmt4
1153         // After:
1154         //     fInlinedBody = null
1155         //     fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
1156         inlinedCall.fInlinedBody->children().push_back(std::move(*enclosingStmt));
1157         *enclosingStmt = std::move(inlinedCall.fInlinedBody);
1158 
1159         // Replace the candidate function call with our replacement expression.
1160         usage->remove(candidate.fCandidateExpr->get());
1161         usage->add(inlinedCall.fReplacementExpr.get());
1162         *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1163         madeChanges = true;
1164 
1165         // If anything else pointed at our enclosing statement, it's now pointing at a Block
1166         // containing many other statements as well. Maintain a fix-up table to account for this.
1167         statementRemappingTable.set(enclosingStmt,&(*enclosingStmt)->as<Block>().children().back());
1168 
1169         // Stop inlining if we've reached our hard cap on new statements.
1170         if (fInlinedStatementCounter >= kInlinedStatementLimit) {
1171             break;
1172         }
1173 
1174         // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1175         // remain valid.
1176     }
1177 
1178     return madeChanges;
1179 }
1180 
1181 }  // namespace SkSL
1182 
1183 #endif  // SK_ENABLE_OPTIMIZE_SIZE
1184