blob: c5f3879ab0bc78ce654a51a276619ecde2fd64dd [file] [log] [blame]
John Stiles44e96be2020-08-31 13:16:04 -04001/*
2 * Copyright 2020 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/sksl/SkSLInliner.h"
9
John Stiles2d7973a2020-10-02 15:01:03 -040010#include <limits.h>
John Stiles44e96be2020-08-31 13:16:04 -040011#include <memory>
12#include <unordered_set>
13
14#include "src/sksl/SkSLAnalysis.h"
15#include "src/sksl/ir/SkSLBinaryExpression.h"
16#include "src/sksl/ir/SkSLBoolLiteral.h"
17#include "src/sksl/ir/SkSLBreakStatement.h"
18#include "src/sksl/ir/SkSLConstructor.h"
19#include "src/sksl/ir/SkSLContinueStatement.h"
20#include "src/sksl/ir/SkSLDiscardStatement.h"
21#include "src/sksl/ir/SkSLDoStatement.h"
22#include "src/sksl/ir/SkSLEnum.h"
23#include "src/sksl/ir/SkSLExpressionStatement.h"
24#include "src/sksl/ir/SkSLExternalFunctionCall.h"
25#include "src/sksl/ir/SkSLExternalValueReference.h"
26#include "src/sksl/ir/SkSLField.h"
27#include "src/sksl/ir/SkSLFieldAccess.h"
28#include "src/sksl/ir/SkSLFloatLiteral.h"
29#include "src/sksl/ir/SkSLForStatement.h"
30#include "src/sksl/ir/SkSLFunctionCall.h"
31#include "src/sksl/ir/SkSLFunctionDeclaration.h"
32#include "src/sksl/ir/SkSLFunctionDefinition.h"
33#include "src/sksl/ir/SkSLFunctionReference.h"
34#include "src/sksl/ir/SkSLIfStatement.h"
35#include "src/sksl/ir/SkSLIndexExpression.h"
John Stiles98c1f822020-09-09 14:18:53 -040036#include "src/sksl/ir/SkSLInlineMarker.h"
John Stiles44e96be2020-08-31 13:16:04 -040037#include "src/sksl/ir/SkSLIntLiteral.h"
38#include "src/sksl/ir/SkSLInterfaceBlock.h"
39#include "src/sksl/ir/SkSLLayout.h"
40#include "src/sksl/ir/SkSLNop.h"
41#include "src/sksl/ir/SkSLNullLiteral.h"
42#include "src/sksl/ir/SkSLPostfixExpression.h"
43#include "src/sksl/ir/SkSLPrefixExpression.h"
44#include "src/sksl/ir/SkSLReturnStatement.h"
45#include "src/sksl/ir/SkSLSetting.h"
46#include "src/sksl/ir/SkSLSwitchCase.h"
47#include "src/sksl/ir/SkSLSwitchStatement.h"
48#include "src/sksl/ir/SkSLSwizzle.h"
49#include "src/sksl/ir/SkSLTernaryExpression.h"
50#include "src/sksl/ir/SkSLUnresolvedFunction.h"
51#include "src/sksl/ir/SkSLVarDeclarations.h"
52#include "src/sksl/ir/SkSLVarDeclarationsStatement.h"
53#include "src/sksl/ir/SkSLVariable.h"
54#include "src/sksl/ir/SkSLVariableReference.h"
55#include "src/sksl/ir/SkSLWhileStatement.h"
56
57namespace SkSL {
58namespace {
59
John Stiles44dff4f2020-09-21 12:28:01 -040060static bool contains_returns_above_limit(const FunctionDefinition& funcDef, int limit) {
61 class CountReturnsWithLimit : public ProgramVisitor {
John Stiles44e96be2020-08-31 13:16:04 -040062 public:
John Stiles44dff4f2020-09-21 12:28:01 -040063 CountReturnsWithLimit(const FunctionDefinition& funcDef, int limit) : fLimit(limit) {
John Stiles44e96be2020-08-31 13:16:04 -040064 this->visitProgramElement(funcDef);
65 }
66
67 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040068 switch (stmt.kind()) {
69 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -040070 ++fNumReturns;
John Stiles44dff4f2020-09-21 12:28:01 -040071 return (fNumReturns > fLimit) || INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040072
73 default:
John Stiles93442622020-09-11 12:11:27 -040074 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -040075 }
76 }
77
78 int fNumReturns = 0;
John Stiles44dff4f2020-09-21 12:28:01 -040079 int fLimit = 0;
John Stiles44e96be2020-08-31 13:16:04 -040080 using INHERITED = ProgramVisitor;
81 };
82
John Stiles44dff4f2020-09-21 12:28:01 -040083 return CountReturnsWithLimit{funcDef, limit}.fNumReturns > limit;
John Stiles44e96be2020-08-31 13:16:04 -040084}
85
86static int count_returns_at_end_of_control_flow(const FunctionDefinition& funcDef) {
87 class CountReturnsAtEndOfControlFlow : public ProgramVisitor {
88 public:
89 CountReturnsAtEndOfControlFlow(const FunctionDefinition& funcDef) {
90 this->visitProgramElement(funcDef);
91 }
92
93 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -040094 switch (stmt.kind()) {
95 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -040096 // Check only the last statement of a block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -040097 const auto& block = stmt.as<Block>();
98 return block.children().size() &&
99 this->visitStatement(*block.children().back());
John Stiles44e96be2020-08-31 13:16:04 -0400100 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400101 case Statement::Kind::kSwitch:
102 case Statement::Kind::kWhile:
103 case Statement::Kind::kDo:
104 case Statement::Kind::kFor:
John Stiles44e96be2020-08-31 13:16:04 -0400105 // Don't introspect switches or loop structures at all.
106 return false;
107
Ethan Nicholase6592142020-09-08 10:22:09 -0400108 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400109 ++fNumReturns;
110 [[fallthrough]];
111
112 default:
John Stiles93442622020-09-11 12:11:27 -0400113 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400114 }
115 }
116
117 int fNumReturns = 0;
118 using INHERITED = ProgramVisitor;
119 };
120
121 return CountReturnsAtEndOfControlFlow{funcDef}.fNumReturns;
122}
123
124static int count_returns_in_breakable_constructs(const FunctionDefinition& funcDef) {
125 class CountReturnsInBreakableConstructs : public ProgramVisitor {
126 public:
127 CountReturnsInBreakableConstructs(const FunctionDefinition& funcDef) {
128 this->visitProgramElement(funcDef);
129 }
130
131 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -0400132 switch (stmt.kind()) {
133 case Statement::Kind::kSwitch:
134 case Statement::Kind::kWhile:
135 case Statement::Kind::kDo:
136 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400137 ++fInsideBreakableConstruct;
John Stiles93442622020-09-11 12:11:27 -0400138 bool result = INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400139 --fInsideBreakableConstruct;
140 return result;
141 }
142
Ethan Nicholase6592142020-09-08 10:22:09 -0400143 case Statement::Kind::kReturn:
John Stiles44e96be2020-08-31 13:16:04 -0400144 fNumReturns += (fInsideBreakableConstruct > 0) ? 1 : 0;
145 [[fallthrough]];
146
147 default:
John Stiles93442622020-09-11 12:11:27 -0400148 return INHERITED::visitStatement(stmt);
John Stiles44e96be2020-08-31 13:16:04 -0400149 }
150 }
151
152 int fNumReturns = 0;
153 int fInsideBreakableConstruct = 0;
154 using INHERITED = ProgramVisitor;
155 };
156
157 return CountReturnsInBreakableConstructs{funcDef}.fNumReturns;
158}
159
160static bool has_early_return(const FunctionDefinition& funcDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400161 int returnsAtEndOfControlFlow = count_returns_at_end_of_control_flow(funcDef);
John Stiles44dff4f2020-09-21 12:28:01 -0400162 return contains_returns_above_limit(funcDef, returnsAtEndOfControlFlow);
John Stiles44e96be2020-08-31 13:16:04 -0400163}
164
John Stiles991b09d2020-09-10 13:33:40 -0400165static bool contains_recursive_call(const FunctionDeclaration& funcDecl) {
166 class ContainsRecursiveCall : public ProgramVisitor {
167 public:
168 bool visit(const FunctionDeclaration& funcDecl) {
169 fFuncDecl = &funcDecl;
170 return funcDecl.fDefinition ? this->visitProgramElement(*funcDecl.fDefinition)
171 : false;
172 }
173
174 bool visitExpression(const Expression& expr) override {
175 if (expr.is<FunctionCall>() && expr.as<FunctionCall>().fFunction.matches(*fFuncDecl)) {
176 return true;
177 }
178 return INHERITED::visitExpression(expr);
179 }
180
181 bool visitStatement(const Statement& stmt) override {
182 if (stmt.is<InlineMarker>() && stmt.as<InlineMarker>().fFuncDecl->matches(*fFuncDecl)) {
183 return true;
184 }
185 return INHERITED::visitStatement(stmt);
186 }
187
188 const FunctionDeclaration* fFuncDecl;
189 using INHERITED = ProgramVisitor;
190 };
191
192 return ContainsRecursiveCall{}.visit(funcDecl);
193}
194
John Stiles44e96be2020-08-31 13:16:04 -0400195static const Type* copy_if_needed(const Type* src, SymbolTable& symbolTable) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400196 if (src->typeKind() == Type::TypeKind::kArray) {
John Stiles44e96be2020-08-31 13:16:04 -0400197 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(*src));
198 }
199 return src;
200}
201
John Stiles6d696082020-10-01 10:18:54 -0400202static std::unique_ptr<Statement>* find_parent_statement(
203 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400204 SkASSERT(!stmtStack.empty());
205
206 // Walk the statement stack from back to front, ignoring the last element (which is the
207 // enclosing statement).
208 auto iter = stmtStack.rbegin();
209 ++iter;
210
211 // Anything counts as a parent statement other than a scopeless Block.
212 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400213 std::unique_ptr<Statement>* stmt = *iter;
214 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400215 return stmt;
216 }
217 }
218
219 // There wasn't any parent statement to be found.
220 return nullptr;
221}
222
John Stilese41b4ee2020-09-28 12:28:16 -0400223std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
224 VariableReference::RefKind refKind) {
225 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400226 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400227 public:
228 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400229 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400230 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400231 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400232 }
233 return INHERITED::visitExpression(expr);
234 }
235
236 private:
237 VariableReference::RefKind fRefKind;
238
John Stiles70b82422020-09-30 10:55:12 -0400239 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400240 };
241
242 SetRefKindInExpression{refKind}.visitExpression(*clone);
243 return clone;
244}
245
John Stiles44733aa2020-09-29 17:42:23 -0400246bool is_trivial_argument(const Expression& argument) {
247 return argument.is<VariableReference>() ||
248 (argument.is<Swizzle>() && is_trivial_argument(*argument.as<Swizzle>().fBase)) ||
249 (argument.is<FieldAccess>() && is_trivial_argument(*argument.as<FieldAccess>().fBase)) ||
John Stiles80ccdbd2020-09-30 11:58:16 -0400250 (argument.is<Constructor>() &&
251 argument.as<Constructor>().arguments().size() == 1 &&
252 is_trivial_argument(*argument.as<Constructor>().arguments().front())) ||
John Stiles44733aa2020-09-29 17:42:23 -0400253 (argument.is<IndexExpression>() &&
254 argument.as<IndexExpression>().fIndex->is<IntLiteral>() &&
255 is_trivial_argument(*argument.as<IndexExpression>().fBase));
256}
257
John Stiles44e96be2020-08-31 13:16:04 -0400258} // namespace
259
John Stilesb61ee902020-09-21 12:26:59 -0400260void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
261 // No changes necessary if this statement isn't actually a block.
262 if (!inlinedBody || !inlinedBody->is<Block>()) {
263 return;
264 }
265
266 // No changes necessary if the parent statement doesn't require a scope.
267 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
268 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
269 return;
270 }
271
272 Block& block = inlinedBody->as<Block>();
273
274 // The inliner will create inlined function bodies as a Block containing multiple statements,
275 // but no scope. Normally, this is fine, but if this block is used as the statement for a
276 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
277 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
278 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
279 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
280 // absorbing the following statement into our loop--so we also add a scope to these.
281 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400282 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400283 // We found an explicit scope; all is well.
284 return;
285 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400286 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400287 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
288 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400289 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400290 return;
291 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400292 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400293 // This block has exactly one thing inside, and it's not another block. No need to scope
294 // it.
295 return;
296 }
297 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400298 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400299 }
300}
301
John Stiles44e96be2020-08-31 13:16:04 -0400302void Inliner::reset(const Context& context, const Program::Settings& settings) {
303 fContext = &context;
304 fSettings = &settings;
305 fInlineVarCounter = 0;
306}
307
John Stilesc75abb82020-09-14 18:24:12 -0400308String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
309 // If the base name starts with an underscore, like "_coords", we can't append another
310 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
311 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
312 // putting in this special case.
313 const char* splitter = baseName.startsWith("_") ? "" : "_";
314
315 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
316 // we're not reusing an existing name. (Note that within a single compilation pass, this check
317 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
318 String uniqueName;
319 for (;;) {
320 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
321 StringFragment frag{uniqueName.data(), uniqueName.length()};
322 if ((*symbolTable)[frag] == nullptr) {
323 break;
324 }
325 }
326
327 return uniqueName;
328}
329
John Stiles44e96be2020-08-31 13:16:04 -0400330std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
331 VariableRewriteMap* varMap,
332 const Expression& expression) {
333 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
334 if (e) {
335 return this->inlineExpression(offset, varMap, *e);
336 }
337 return nullptr;
338 };
339 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
340 -> std::vector<std::unique_ptr<Expression>> {
341 std::vector<std::unique_ptr<Expression>> args;
342 args.reserve(originalArgs.size());
343 for (const std::unique_ptr<Expression>& arg : originalArgs) {
344 args.push_back(expr(arg));
345 }
346 return args;
347 };
348
Ethan Nicholase6592142020-09-08 10:22:09 -0400349 switch (expression.kind()) {
350 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400351 const BinaryExpression& b = expression.as<BinaryExpression>();
352 return std::make_unique<BinaryExpression>(offset,
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400353 expr(b.leftPointer()),
354 b.getOperator(),
355 expr(b.rightPointer()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400356 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400357 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400358 case Expression::Kind::kBoolLiteral:
359 case Expression::Kind::kIntLiteral:
360 case Expression::Kind::kFloatLiteral:
361 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400362 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400363 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400364 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400365 return std::make_unique<Constructor>(offset, &constructor.type(),
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400366 argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400367 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400368 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400369 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400370 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.type(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400371 externalCall.function(),
372 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400373 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400374 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400375 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400376 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400377 const FieldAccess& f = expression.as<FieldAccess>();
378 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
379 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400380 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400381 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400382 return std::make_unique<FunctionCall>(offset, &funcCall.type(), funcCall.fFunction,
John Stiles44e96be2020-08-31 13:16:04 -0400383 argList(funcCall.fArguments));
384 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400385 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400386 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400387 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400388 const IndexExpression& idx = expression.as<IndexExpression>();
389 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
390 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400391 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400392 const PrefixExpression& p = expression.as<PrefixExpression>();
393 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
394 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400395 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400396 const PostfixExpression& p = expression.as<PostfixExpression>();
397 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
398 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400399 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400400 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400401 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400402 const Swizzle& s = expression.as<Swizzle>();
403 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
404 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400405 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400406 const TernaryExpression& t = expression.as<TernaryExpression>();
407 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
408 expr(t.fIfTrue), expr(t.fIfFalse));
409 }
Brian Osman83ba9302020-09-11 13:33:46 -0400410 case Expression::Kind::kTypeReference:
411 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400412 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400413 const VariableReference& v = expression.as<VariableReference>();
John Stilese41b4ee2020-09-28 12:28:16 -0400414 auto varMapIter = varMap->find(v.fVariable);
415 if (varMapIter != varMap->end()) {
416 return clone_with_ref_kind(*varMapIter->second, v.fRefKind);
John Stiles44e96be2020-08-31 13:16:04 -0400417 }
418 return v.clone();
419 }
420 default:
421 SkASSERT(false);
422 return nullptr;
423 }
424}
425
426std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
427 VariableRewriteMap* varMap,
428 SymbolTable* symbolTableForStatement,
John Stilese41b4ee2020-09-28 12:28:16 -0400429 const Expression* resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400430 bool haveEarlyReturns,
Brian Osman3887a012020-09-30 13:22:27 -0400431 const Statement& statement,
432 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400433 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
434 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400435 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
Brian Osman3887a012020-09-30 13:22:27 -0400436 haveEarlyReturns, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400437 }
438 return nullptr;
439 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400440 auto blockStmts = [&](const Block& block) {
441 std::vector<std::unique_ptr<Statement>> result;
442 for (const std::unique_ptr<Statement>& child : block.children()) {
443 result.push_back(stmt(child));
444 }
445 return result;
446 };
John Stiles44e96be2020-08-31 13:16:04 -0400447 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
448 std::vector<std::unique_ptr<Statement>> result;
449 for (const auto& s : ss) {
450 result.push_back(stmt(s));
451 }
452 return result;
453 };
454 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
455 if (e) {
456 return this->inlineExpression(offset, varMap, *e);
457 }
458 return nullptr;
459 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400460 switch (statement.kind()) {
461 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400462 const Block& b = statement.as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400463 return std::make_unique<Block>(offset, blockStmts(b), b.symbolTable(), b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400464 }
465
Ethan Nicholase6592142020-09-08 10:22:09 -0400466 case Statement::Kind::kBreak:
467 case Statement::Kind::kContinue:
468 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400469 return statement.clone();
470
Ethan Nicholase6592142020-09-08 10:22:09 -0400471 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400472 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400473 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400474 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400475 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400476 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400477 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400478 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400479 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400480 const ForStatement& f = statement.as<ForStatement>();
481 // need to ensure initializer is evaluated first so that we've already remapped its
482 // declarations by the time we evaluate test & next
483 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
484 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
485 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
486 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400487 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400488 const IfStatement& i = statement.as<IfStatement>();
489 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
490 stmt(i.fIfTrue), stmt(i.fIfFalse));
491 }
John Stiles98c1f822020-09-09 14:18:53 -0400492 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400493 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400494 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400495 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400496 const ReturnStatement& r = statement.as<ReturnStatement>();
497 if (r.fExpression) {
John Stilese41b4ee2020-09-28 12:28:16 -0400498 SkASSERT(resultExpr);
John Stilesa5f3c312020-09-22 12:05:16 -0400499 auto assignment =
500 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
501 offset,
John Stilese41b4ee2020-09-28 12:28:16 -0400502 clone_with_ref_kind(*resultExpr, VariableReference::kWrite_RefKind),
John Stilesa5f3c312020-09-22 12:05:16 -0400503 Token::Kind::TK_EQ,
504 expr(r.fExpression),
John Stilese41b4ee2020-09-28 12:28:16 -0400505 &resultExpr->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400506 if (haveEarlyReturns) {
507 std::vector<std::unique_ptr<Statement>> block;
508 block.push_back(std::move(assignment));
509 block.emplace_back(new BreakStatement(offset));
510 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
511 /*isScope=*/true);
512 } else {
513 return std::move(assignment);
514 }
515 } else {
516 if (haveEarlyReturns) {
517 return std::make_unique<BreakStatement>(offset);
518 } else {
519 return std::make_unique<Nop>();
520 }
521 }
522 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400523 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400524 const SwitchStatement& ss = statement.as<SwitchStatement>();
525 std::vector<std::unique_ptr<SwitchCase>> cases;
526 for (const auto& sc : ss.fCases) {
527 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
528 stmts(sc->fStatements)));
529 }
530 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
531 std::move(cases), ss.fSymbols);
532 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400533 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400534 const VarDeclaration& decl = statement.as<VarDeclaration>();
535 std::vector<std::unique_ptr<Expression>> sizes;
536 for (const auto& size : decl.fSizes) {
537 sizes.push_back(expr(size));
538 }
539 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
540 const Variable* old = decl.fVar;
John Stilesc75abb82020-09-14 18:24:12 -0400541 // We assign unique names to inlined variables--scopes hide most of the problems in this
542 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
543 // names are important.
544 auto name = std::make_unique<String>(
545 this->uniqueNameForInlineVar(String(old->fName), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400546 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas30d30222020-09-11 12:27:26 -0400547 const Type* typePtr = copy_if_needed(&old->type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400548 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
549 std::make_unique<Variable>(offset,
550 old->fModifiers,
551 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400552 typePtr,
Brian Osman3887a012020-09-30 13:22:27 -0400553 isBuiltinCode,
John Stiles44e96be2020-08-31 13:16:04 -0400554 old->fStorage,
555 initialValue.get()));
John Stilese41b4ee2020-09-28 12:28:16 -0400556 (*varMap)[old] = std::make_unique<VariableReference>(offset, clone);
John Stiles44e96be2020-08-31 13:16:04 -0400557 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
558 std::move(initialValue));
559 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400560 case Statement::Kind::kVarDeclarations: {
John Stiles44e96be2020-08-31 13:16:04 -0400561 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
562 std::vector<std::unique_ptr<VarDeclaration>> vars;
563 for (const auto& var : decls.fVars) {
564 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
565 }
566 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
567 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
568 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
569 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400570 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400571 const WhileStatement& w = statement.as<WhileStatement>();
572 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
573 }
574 default:
575 SkASSERT(false);
576 return nullptr;
577 }
578}
579
John Stiles6eadf132020-09-08 10:16:10 -0400580Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
Brian Osman3887a012020-09-30 13:22:27 -0400581 SymbolTable* symbolTableForCall,
582 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400583 // Inlining is more complicated here than in a typical compiler, because we have to have a
584 // high-level IR and can't just drop statements into the middle of an expression or even use
585 // gotos.
586 //
587 // Since we can't insert statements into an expression, we run the inline function as extra
588 // statements before the statement we're currently processing, relying on a lack of execution
589 // order guarantees. Since we can't use gotos (which are normally used to replace return
590 // statements), we wrap the whole function in a loop and use break statements to jump to the
591 // end.
592 SkASSERT(fSettings);
593 SkASSERT(fContext);
594 SkASSERT(call);
John Stiles2d7973a2020-10-02 15:01:03 -0400595 SkASSERT(this->isSafeToInline(call->fFunction.fDefinition));
John Stiles44e96be2020-08-31 13:16:04 -0400596
John Stiles44e96be2020-08-31 13:16:04 -0400597 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
John Stiles6eadf132020-09-08 10:16:10 -0400598 const int offset = call->fOffset;
John Stiles44e96be2020-08-31 13:16:04 -0400599 const FunctionDefinition& function = *call->fFunction.fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400600 const bool hasEarlyReturn = has_early_return(function);
601
John Stiles44e96be2020-08-31 13:16:04 -0400602 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400603 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
604 std::vector<std::unique_ptr<Statement>>{},
605 /*symbols=*/nullptr,
606 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400607
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400608 Block& inlinedBody = *inlinedCall.fInlinedBody;
609 inlinedBody.children().reserve(1 + // Inline marker
610 1 + // Result variable
611 arguments.size() + // Function arguments (passing in)
John Stilese41b4ee2020-09-28 12:28:16 -0400612 arguments.size() + // Function arguments (copy out-params back)
613 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400614
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400615 inlinedBody.children().push_back(std::make_unique<InlineMarker>(call->fFunction));
John Stiles44e96be2020-08-31 13:16:04 -0400616
John Stilese41b4ee2020-09-28 12:28:16 -0400617 auto makeInlineVar =
618 [&](const String& baseName, const Type* type, Modifiers modifiers,
619 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400620 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
621 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
622 // somewhere during compilation.
623 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400624 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400625 type = fContext->fFloat_Type.get();
626 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400627 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400628 type = fContext->fInt_Type.get();
629 }
630
John Stilesc75abb82020-09-14 18:24:12 -0400631 // Provide our new variable with a unique name, and add it to our symbol table.
632 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400633 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
634 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400635 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
636
637 // Add our new variable to the symbol table.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400638 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
Brian Osman3887a012020-09-30 13:22:27 -0400639 caller->fBuiltin, Variable::kLocal_Storage,
640 initialValue->get());
John Stiles44e96be2020-08-31 13:16:04 -0400641 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
642
643 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
644 // initial value).
645 std::vector<std::unique_ptr<VarDeclaration>> variables;
646 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
647 variables.push_back(std::make_unique<VarDeclaration>(
648 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
649 (*initialValue)->clone()));
650 } else {
651 variables.push_back(std::make_unique<VarDeclaration>(
652 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
653 std::move(*initialValue)));
654 }
655
656 // Add the new variable-declaration statement to our block of extra statements.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400657 inlinedBody.children().push_back(std::make_unique<VarDeclarationsStatement>(
John Stilesa003e812020-09-11 09:43:49 -0400658 std::make_unique<VarDeclarations>(offset, type, std::move(variables))));
John Stiles44e96be2020-08-31 13:16:04 -0400659
John Stilese41b4ee2020-09-28 12:28:16 -0400660 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400661 };
662
663 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400664 std::unique_ptr<Expression> resultExpr;
John Stiles44e96be2020-08-31 13:16:04 -0400665 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400666 std::unique_ptr<Expression> noInitialValue;
John Stilese41b4ee2020-09-28 12:28:16 -0400667 resultExpr = makeInlineVar(String(function.fDeclaration.fName),
668 &function.fDeclaration.fReturnType,
669 Modifiers{}, &noInitialValue);
670 }
John Stiles44e96be2020-08-31 13:16:04 -0400671
672 // Create variables in the extra statements to hold the arguments, and assign the arguments to
673 // them.
674 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400675 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400676 for (int i = 0; i < (int) arguments.size(); ++i) {
677 const Variable* param = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400678 bool isOutParam = param->fModifiers.fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400679
John Stiles44733aa2020-09-29 17:42:23 -0400680 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
681 if (is_trivial_argument(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400682 // ... and it's an `out` param, or it isn't written to within the inline function...
683 if (isOutParam || !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400684 // ... we don't need to copy it at all! We can just use the existing expression.
685 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400686 continue;
687 }
688 }
689
John Stilese41b4ee2020-09-28 12:28:16 -0400690 if (isOutParam) {
691 argsToCopyBack.push_back(i);
692 }
693
Ethan Nicholas30d30222020-09-11 12:27:26 -0400694 varMap[param] = makeInlineVar(String(param->fName), &arguments[i]->type(),
695 param->fModifiers, &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400696 }
697
698 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400699 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400700 inlineBlock->children().reserve(body.children().size());
701 for (const std::unique_ptr<Statement>& stmt : body.children()) {
Brian Osman3887a012020-09-30 13:22:27 -0400702 inlineBlock->children().push_back(this->inlineStatement(offset, &varMap, symbolTableForCall,
703 resultExpr.get(), hasEarlyReturn,
704 *stmt, caller->fBuiltin));
John Stiles44e96be2020-08-31 13:16:04 -0400705 }
706 if (hasEarlyReturn) {
707 // Since we output to backends that don't have a goto statement (which would normally be
708 // used to perform an early return), we fake it by wrapping the function in a
709 // do { } while (false); and then use break statements to jump to the end in order to
710 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400711 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400712 /*offset=*/-1,
713 std::move(inlineBlock),
714 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
715 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400716 // No early returns, so we can just dump the code in. We still need to keep the block so we
717 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400718 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400719 }
720
John Stilese41b4ee2020-09-28 12:28:16 -0400721 // Copy back the values of `out` parameters into their real destinations.
722 for (int i : argsToCopyBack) {
John Stiles44e96be2020-08-31 13:16:04 -0400723 const Variable* p = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400724 SkASSERT(varMap.find(p) != varMap.end());
725 inlinedBody.children().push_back(
726 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
727 offset,
728 clone_with_ref_kind(*arguments[i], VariableReference::kWrite_RefKind),
729 Token::Kind::TK_EQ,
730 std::move(varMap[p]),
731 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400732 }
733
John Stilese41b4ee2020-09-28 12:28:16 -0400734 if (resultExpr != nullptr) {
735 // Return our result variable as our replacement expression.
736 SkASSERT(resultExpr->as<VariableReference>().fRefKind == VariableReference::kRead_RefKind);
737 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400738 } else {
739 // It's a void function, so it doesn't actually result in anything, but we have to return
740 // something non-null as a standin.
741 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
742 /*value=*/false);
743 }
744
John Stiles44e96be2020-08-31 13:16:04 -0400745 return inlinedCall;
746}
747
John Stiles2d7973a2020-10-02 15:01:03 -0400748bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400749 SkASSERT(fSettings);
750
John Stiles2d7973a2020-10-02 15:01:03 -0400751 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400752 // Can't inline something if we don't actually have its definition.
753 return false;
754 }
John Stiles2d7973a2020-10-02 15:01:03 -0400755
John Stiles44e96be2020-08-31 13:16:04 -0400756 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
757 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
758 // can't inline functions that have an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400759 bool hasEarlyReturn = has_early_return(*functionDef);
John Stiles44e96be2020-08-31 13:16:04 -0400760
761 // If we didn't detect an early return, there shouldn't be any returns in breakable
762 // constructs either.
John Stiles2d7973a2020-10-02 15:01:03 -0400763 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(*functionDef) == 0);
John Stiles44e96be2020-08-31 13:16:04 -0400764 return !hasEarlyReturn;
765 }
766 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
767 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
John Stiles2d7973a2020-10-02 15:01:03 -0400768 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(*functionDef) > 0);
John Stiles44e96be2020-08-31 13:16:04 -0400769
770 // If we detected returns in breakable constructs, we should also detect an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400771 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(*functionDef));
John Stiles44e96be2020-08-31 13:16:04 -0400772 return !hasReturnInBreakableConstruct;
773}
774
John Stiles2d7973a2020-10-02 15:01:03 -0400775// A candidate function for inlining, containing everything that `inlineCall` needs.
776struct InlineCandidate {
777 SymbolTable* fSymbols; // the SymbolTable of the candidate
778 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
779 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
780 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
781 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
782 bool fIsLargeFunction; // does candidate exceed the inline threshold?
783};
John Stiles93442622020-09-11 12:11:27 -0400784
John Stiles2d7973a2020-10-02 15:01:03 -0400785struct InlineCandidateList {
786 std::vector<InlineCandidate> fCandidates;
787};
788
789class InlineCandidateAnalyzer {
John Stiles93442622020-09-11 12:11:27 -0400790 public:
791 // A list of all the inlining candidates we found during analysis.
John Stiles2d7973a2020-10-02 15:01:03 -0400792 InlineCandidateList* fCandidateList;
793
John Stiles93442622020-09-11 12:11:27 -0400794 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower
795 // than the enclosing-statement stack.
796 std::vector<SymbolTable*> fSymbolTableStack;
797 // A stack of "enclosing" statements--these would be suitable for the inliner to use for
798 // adding new instructions. Not all statements are suitable (e.g. a for-loop's initializer).
799 // The inliner might replace a statement with a block containing the statement.
800 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
Brian Osman3887a012020-09-30 13:22:27 -0400801 // The function that we're currently processing (i.e. inlining into).
802 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400803
John Stiles2d7973a2020-10-02 15:01:03 -0400804 void visit(Program& program, InlineCandidateList* candidateList) {
805 fCandidateList = candidateList;
John Stiles93442622020-09-11 12:11:27 -0400806 fSymbolTableStack.push_back(program.fSymbols.get());
807
808 for (ProgramElement& pe : program) {
809 this->visitProgramElement(&pe);
810 }
811
812 fSymbolTableStack.pop_back();
John Stiles2d7973a2020-10-02 15:01:03 -0400813 fCandidateList = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400814 }
815
816 void visitProgramElement(ProgramElement* pe) {
817 switch (pe->kind()) {
818 case ProgramElement::Kind::kFunction: {
819 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman3887a012020-09-30 13:22:27 -0400820 fEnclosingFunction = &funcDef;
John Stiles93442622020-09-11 12:11:27 -0400821 this->visitStatement(&funcDef.fBody);
822 break;
823 }
824 default:
825 // The inliner can't operate outside of a function's scope.
826 break;
827 }
828 }
829
830 void visitStatement(std::unique_ptr<Statement>* stmt,
831 bool isViableAsEnclosingStatement = true) {
832 if (!*stmt) {
833 return;
834 }
835
836 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
837 size_t oldSymbolStackSize = fSymbolTableStack.size();
838
839 if (isViableAsEnclosingStatement) {
840 fEnclosingStmtStack.push_back(stmt);
841 }
842
843 switch ((*stmt)->kind()) {
844 case Statement::Kind::kBreak:
845 case Statement::Kind::kContinue:
846 case Statement::Kind::kDiscard:
847 case Statement::Kind::kInlineMarker:
848 case Statement::Kind::kNop:
849 break;
850
851 case Statement::Kind::kBlock: {
852 Block& block = (*stmt)->as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400853 if (block.symbolTable()) {
854 fSymbolTableStack.push_back(block.symbolTable().get());
John Stiles93442622020-09-11 12:11:27 -0400855 }
856
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400857 for (std::unique_ptr<Statement>& stmt : block.children()) {
858 this->visitStatement(&stmt);
John Stiles93442622020-09-11 12:11:27 -0400859 }
860 break;
861 }
862 case Statement::Kind::kDo: {
863 DoStatement& doStmt = (*stmt)->as<DoStatement>();
864 // The loop body is a candidate for inlining.
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400865 this->visitStatement(&doStmt.statement());
John Stiles93442622020-09-11 12:11:27 -0400866 // The inliner isn't smart enough to inline the test-expression for a do-while
867 // loop at this time. There are two limitations:
868 // - We would need to insert the inlined-body block at the very end of the do-
869 // statement's inner fStatement. We don't support that today, but it's doable.
870 // - We cannot inline the test expression if the loop uses `continue` anywhere;
871 // that would skip over the inlined block that evaluates the test expression.
872 // There isn't a good fix for this--any workaround would be more complex than
873 // the cost of a function call. However, loops that don't use `continue` would
874 // still be viable candidates for inlining.
875 break;
876 }
877 case Statement::Kind::kExpression: {
878 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400879 this->visitExpression(&expr.expression());
John Stiles93442622020-09-11 12:11:27 -0400880 break;
881 }
882 case Statement::Kind::kFor: {
883 ForStatement& forStmt = (*stmt)->as<ForStatement>();
884 if (forStmt.fSymbols) {
885 fSymbolTableStack.push_back(forStmt.fSymbols.get());
886 }
887
888 // The initializer and loop body are candidates for inlining.
889 this->visitStatement(&forStmt.fInitializer,
890 /*isViableAsEnclosingStatement=*/false);
891 this->visitStatement(&forStmt.fStatement);
892
893 // The inliner isn't smart enough to inline the test- or increment-expressions
894 // of a for loop loop at this time. There are a handful of limitations:
895 // - We would need to insert the test-expression block at the very beginning of
896 // the for-loop's inner fStatement, and the increment-expression block at the
897 // very end. We don't support that today, but it's doable.
898 // - The for-loop's built-in test-expression would need to be dropped entirely,
899 // and the loop would be halted via a break statement at the end of the
900 // inlined test-expression. This is again something we don't support today,
901 // but it could be implemented.
902 // - We cannot inline the increment-expression if the loop uses `continue`
903 // anywhere; that would skip over the inlined block that evaluates the
904 // increment expression. There isn't a good fix for this--any workaround would
905 // be more complex than the cost of a function call. However, loops that don't
906 // use `continue` would still be viable candidates for increment-expression
907 // inlining.
908 break;
909 }
910 case Statement::Kind::kIf: {
911 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
912 this->visitExpression(&ifStmt.fTest);
913 this->visitStatement(&ifStmt.fIfTrue);
914 this->visitStatement(&ifStmt.fIfFalse);
915 break;
916 }
917 case Statement::Kind::kReturn: {
918 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
919 this->visitExpression(&returnStmt.fExpression);
920 break;
921 }
922 case Statement::Kind::kSwitch: {
923 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
924 if (switchStmt.fSymbols) {
925 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
926 }
927
928 this->visitExpression(&switchStmt.fValue);
929 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
930 // The switch-case's fValue cannot be a FunctionCall; skip it.
931 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
932 this->visitStatement(&caseBlock);
933 }
934 }
935 break;
936 }
937 case Statement::Kind::kVarDeclaration: {
938 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
939 // Don't need to scan the declaration's sizes; those are always IntLiterals.
940 this->visitExpression(&varDeclStmt.fValue);
941 break;
942 }
943 case Statement::Kind::kVarDeclarations: {
944 VarDeclarationsStatement& varDecls = (*stmt)->as<VarDeclarationsStatement>();
945 for (std::unique_ptr<Statement>& varDecl : varDecls.fDeclaration->fVars) {
946 this->visitStatement(&varDecl, /*isViableAsEnclosingStatement=*/false);
947 }
948 break;
949 }
950 case Statement::Kind::kWhile: {
951 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
952 // The loop body is a candidate for inlining.
953 this->visitStatement(&whileStmt.fStatement);
954 // The inliner isn't smart enough to inline the test-expression for a while
955 // loop at this time. There are two limitations:
956 // - We would need to insert the inlined-body block at the very beginning of the
957 // while loop's inner fStatement. We don't support that today, but it's
958 // doable.
959 // - The while-loop's built-in test-expression would need to be replaced with a
960 // `true` BoolLiteral, and the loop would be halted via a break statement at
961 // the end of the inlined test-expression. This is again something we don't
962 // support today, but it could be implemented.
963 break;
964 }
965 default:
966 SkUNREACHABLE;
967 }
968
969 // Pop our symbol and enclosing-statement stacks.
970 fSymbolTableStack.resize(oldSymbolStackSize);
971 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
972 }
973
974 void visitExpression(std::unique_ptr<Expression>* expr) {
975 if (!*expr) {
976 return;
977 }
978
979 switch ((*expr)->kind()) {
980 case Expression::Kind::kBoolLiteral:
981 case Expression::Kind::kDefined:
982 case Expression::Kind::kExternalValue:
983 case Expression::Kind::kFieldAccess:
984 case Expression::Kind::kFloatLiteral:
985 case Expression::Kind::kFunctionReference:
986 case Expression::Kind::kIntLiteral:
987 case Expression::Kind::kNullLiteral:
988 case Expression::Kind::kSetting:
989 case Expression::Kind::kTypeReference:
990 case Expression::Kind::kVariableReference:
991 // Nothing to scan here.
992 break;
993
994 case Expression::Kind::kBinary: {
995 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400996 this->visitExpression(&binaryExpr.leftPointer());
John Stiles93442622020-09-11 12:11:27 -0400997
998 // Logical-and and logical-or binary expressions do not inline the right side,
999 // because that would invalidate short-circuiting. That is, when evaluating
1000 // expressions like these:
1001 // (false && x()) // always false
1002 // (true || y()) // always true
1003 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1004 // enforce that rule is to avoid inlining the right side entirely. However, it
1005 // is safe for other types of binary expression to inline both sides.
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001006 Token::Kind op = binaryExpr.getOperator();
1007 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1008 op == Token::Kind::TK_LOGICALOR);
John Stiles93442622020-09-11 12:11:27 -04001009 if (!shortCircuitable) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001010 this->visitExpression(&binaryExpr.rightPointer());
John Stiles93442622020-09-11 12:11:27 -04001011 }
1012 break;
1013 }
1014 case Expression::Kind::kConstructor: {
1015 Constructor& constructorExpr = (*expr)->as<Constructor>();
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001016 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
John Stiles93442622020-09-11 12:11:27 -04001017 this->visitExpression(&arg);
1018 }
1019 break;
1020 }
1021 case Expression::Kind::kExternalFunctionCall: {
1022 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
Ethan Nicholas6e86ec92020-09-30 14:29:56 -04001023 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles93442622020-09-11 12:11:27 -04001024 this->visitExpression(&arg);
1025 }
1026 break;
1027 }
1028 case Expression::Kind::kFunctionCall: {
1029 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
1030 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
1031 this->visitExpression(&arg);
1032 }
1033 this->addInlineCandidate(expr);
1034 break;
1035 }
1036 case Expression::Kind::kIndex:{
1037 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
1038 this->visitExpression(&indexExpr.fBase);
1039 this->visitExpression(&indexExpr.fIndex);
1040 break;
1041 }
1042 case Expression::Kind::kPostfix: {
1043 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
1044 this->visitExpression(&postfixExpr.fOperand);
1045 break;
1046 }
1047 case Expression::Kind::kPrefix: {
1048 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
1049 this->visitExpression(&prefixExpr.fOperand);
1050 break;
1051 }
1052 case Expression::Kind::kSwizzle: {
1053 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
1054 this->visitExpression(&swizzleExpr.fBase);
1055 break;
1056 }
1057 case Expression::Kind::kTernary: {
1058 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1059 // The test expression is a candidate for inlining.
1060 this->visitExpression(&ternaryExpr.fTest);
1061 // The true- and false-expressions cannot be inlined, because we are only
1062 // allowed to evaluate one side.
1063 break;
1064 }
1065 default:
1066 SkUNREACHABLE;
1067 }
1068 }
1069
1070 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
John Stiles2d7973a2020-10-02 15:01:03 -04001071 fCandidateList->fCandidates.push_back(
1072 InlineCandidate{fSymbolTableStack.back(),
1073 find_parent_statement(fEnclosingStmtStack),
1074 fEnclosingStmtStack.back(),
1075 candidate,
1076 fEnclosingFunction,
1077 /*isLargeFunction=*/false});
John Stiles93442622020-09-11 12:11:27 -04001078 }
John Stiles2d7973a2020-10-02 15:01:03 -04001079};
John Stiles93442622020-09-11 12:11:27 -04001080
John Stiles2d7973a2020-10-02 15:01:03 -04001081bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1082 const FunctionDeclaration& funcDecl = (*candidate.fCandidateExpr)->as<FunctionCall>().fFunction;
John Stiles915a38c2020-09-14 09:38:13 -04001083
John Stiles2d7973a2020-10-02 15:01:03 -04001084 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
1085 if (wasInserted) {
1086 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
1087 iter->second = this->isSafeToInline(funcDecl.fDefinition) &&
1088 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001089 }
1090
John Stiles2d7973a2020-10-02 15:01:03 -04001091 return iter->second;
1092}
1093
1094bool Inliner::isLargeFunction(const FunctionDefinition* functionDef) {
1095 return Analysis::NodeCountExceeds(*functionDef, fSettings->fInlineThreshold);
1096}
1097
1098bool Inliner::isLargeFunction(const InlineCandidate& candidate, LargeFunctionCache* cache) {
1099 const FunctionDeclaration& funcDecl = (*candidate.fCandidateExpr)->as<FunctionCall>().fFunction;
1100
1101 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
1102 if (wasInserted) {
1103 iter->second = this->isLargeFunction(funcDecl.fDefinition);
1104 }
1105
1106 return iter->second;
1107}
1108
1109void Inliner::buildCandidateList(Program& program, InlineCandidateList* candidateList) {
1110 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1111 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1112 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1113 // `const T&`.
1114 InlineCandidateAnalyzer analyzer;
1115 analyzer.visit(program, candidateList);
1116
1117 // Remove candidates that are not safe to inline.
1118 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
1119 InlinabilityCache cache;
1120 candidates.erase(std::remove_if(candidates.begin(),
1121 candidates.end(),
1122 [&](const InlineCandidate& candidate) {
1123 return !this->candidateCanBeInlined(candidate, &cache);
1124 }),
1125 candidates.end());
1126
1127 // Determine whether each candidate function exceeds our inlining size threshold or not. These
1128 // can still be valid candidates if they are only called one time, so we don't remove them from
1129 // the candidate list, but they will not be inlined if they're called more than once.
1130 LargeFunctionCache largeFunctionCache;
1131 for (InlineCandidate& candidate : candidates) {
1132 candidate.fIsLargeFunction = this->isLargeFunction(candidate, &largeFunctionCache);
1133 }
1134}
1135
1136bool Inliner::analyze(Program& program) {
1137 InlineCandidateList candidateList;
1138 this->buildCandidateList(program, &candidateList);
1139
John Stiles915a38c2020-09-14 09:38:13 -04001140 // Inline the candidates where we've determined that it's safe to do so.
1141 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1142 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001143 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001144 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1145 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1146
John Stiles2d7973a2020-10-02 15:01:03 -04001147 // If the function is large, not marked `inline`, and is called more than once, it's a bad
1148 // idea to inline it.
1149 if (candidate.fIsLargeFunction &&
1150 !(funcDecl->fModifiers.fFlags & Modifiers::kInline_Flag) &&
1151 funcDecl->fCallCount.load() > 1) {
John Stiles915a38c2020-09-14 09:38:13 -04001152 continue;
1153 }
1154
1155 // Inlining two expressions using the same enclosing statement in the same inlining pass
1156 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1157 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1158 if (!inserted) {
1159 continue;
1160 }
1161
1162 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001163 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
1164 &candidate.fEnclosingFunction->fDeclaration);
John Stiles915a38c2020-09-14 09:38:13 -04001165 if (inlinedCall.fInlinedBody) {
1166 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001167 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001168
1169 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1170 // function, then replace the enclosing statement with that Block.
1171 // Before:
1172 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1173 // fEnclosingStmt = stmt4
1174 // After:
1175 // fInlinedBody = null
1176 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001177 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001178 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1179 }
1180
1181 // Replace the candidate function call with our replacement expression.
1182 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1183 madeChanges = true;
1184
1185 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1186 // remain valid.
1187 }
1188
1189 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001190}
1191
John Stiles44e96be2020-08-31 13:16:04 -04001192} // namespace SkSL