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