blob: 9c663a5ec9273b262e36b2c7d8a068d13f7aa206 [file] [log] [blame]
John Stiles44e96be2020-08-31 13:16:04 -04001/*
2 * Copyright 2020 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/sksl/SkSLInliner.h"
9
10#include "limits.h"
11#include <memory>
12#include <unordered_set>
13
14#include "src/sksl/SkSLAnalysis.h"
15#include "src/sksl/ir/SkSLBinaryExpression.h"
16#include "src/sksl/ir/SkSLBoolLiteral.h"
17#include "src/sksl/ir/SkSLBreakStatement.h"
18#include "src/sksl/ir/SkSLConstructor.h"
19#include "src/sksl/ir/SkSLContinueStatement.h"
20#include "src/sksl/ir/SkSLDiscardStatement.h"
21#include "src/sksl/ir/SkSLDoStatement.h"
22#include "src/sksl/ir/SkSLEnum.h"
23#include "src/sksl/ir/SkSLExpressionStatement.h"
24#include "src/sksl/ir/SkSLExternalFunctionCall.h"
25#include "src/sksl/ir/SkSLExternalValueReference.h"
26#include "src/sksl/ir/SkSLField.h"
27#include "src/sksl/ir/SkSLFieldAccess.h"
28#include "src/sksl/ir/SkSLFloatLiteral.h"
29#include "src/sksl/ir/SkSLForStatement.h"
30#include "src/sksl/ir/SkSLFunctionCall.h"
31#include "src/sksl/ir/SkSLFunctionDeclaration.h"
32#include "src/sksl/ir/SkSLFunctionDefinition.h"
33#include "src/sksl/ir/SkSLFunctionReference.h"
34#include "src/sksl/ir/SkSLIfStatement.h"
35#include "src/sksl/ir/SkSLIndexExpression.h"
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);
595 SkASSERT(this->isSafeToInline(*call, /*inlineThreshold=*/INT_MAX));
596
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 Stiles93442622020-09-11 12:11:27 -0400748bool Inliner::isSafeToInline(const FunctionCall& functionCall, int inlineThreshold) {
John Stiles44e96be2020-08-31 13:16:04 -0400749 SkASSERT(fSettings);
750
751 if (functionCall.fFunction.fDefinition == nullptr) {
752 // Can't inline something if we don't actually have its definition.
753 return false;
754 }
755 const FunctionDefinition& functionDef = *functionCall.fFunction.fDefinition;
756 if (inlineThreshold < INT_MAX) {
757 if (!(functionDef.fDeclaration.fModifiers.fFlags & Modifiers::kInline_Flag) &&
John Stiles2c1e4922020-10-01 09:14:14 -0400758 Analysis::NodeCountExceeds(functionDef, inlineThreshold)) {
John Stiles44e96be2020-08-31 13:16:04 -0400759 // The function exceeds our maximum inline size and is not flagged 'inline'.
760 return false;
761 }
762 }
John Stiles44e96be2020-08-31 13:16:04 -0400763 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
764 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
765 // can't inline functions that have an early return.
766 bool hasEarlyReturn = has_early_return(functionDef);
767
768 // If we didn't detect an early return, there shouldn't be any returns in breakable
769 // constructs either.
770 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(functionDef) == 0);
771 return !hasEarlyReturn;
772 }
773 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
774 // breakable construct (switch/for/do/while), so we can't inline if there's a return inside one.
775 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(functionDef) > 0);
776
777 // If we detected returns in breakable constructs, we should also detect an early return.
778 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(functionDef));
779 return !hasReturnInBreakableConstruct;
780}
781
John Stiles93442622020-09-11 12:11:27 -0400782bool Inliner::analyze(Program& program) {
783 // A candidate function for inlining, containing everything that `inlineCall` needs.
784 struct InlineCandidate {
John Stiles915a38c2020-09-14 09:38:13 -0400785 SymbolTable* fSymbols; // the SymbolTable of the candidate
John Stiles6d696082020-10-01 10:18:54 -0400786 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
John Stiles915a38c2020-09-14 09:38:13 -0400787 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
788 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
Brian Osman3887a012020-09-30 13:22:27 -0400789 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
John Stiles93442622020-09-11 12:11:27 -0400790 };
791
792 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
793 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
794 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
795 // `const T&`.
796 class InlineCandidateAnalyzer {
797 public:
798 // A list of all the inlining candidates we found during analysis.
799 std::vector<InlineCandidate> fInlineCandidates;
800 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower
801 // than the enclosing-statement stack.
802 std::vector<SymbolTable*> fSymbolTableStack;
803 // A stack of "enclosing" statements--these would be suitable for the inliner to use for
804 // adding new instructions. Not all statements are suitable (e.g. a for-loop's initializer).
805 // The inliner might replace a statement with a block containing the statement.
806 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
Brian Osman3887a012020-09-30 13:22:27 -0400807 // The function that we're currently processing (i.e. inlining into).
808 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400809
810 void visit(Program& program) {
811 fSymbolTableStack.push_back(program.fSymbols.get());
812
813 for (ProgramElement& pe : program) {
814 this->visitProgramElement(&pe);
815 }
816
817 fSymbolTableStack.pop_back();
818 }
819
820 void visitProgramElement(ProgramElement* pe) {
821 switch (pe->kind()) {
822 case ProgramElement::Kind::kFunction: {
823 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
Brian Osman3887a012020-09-30 13:22:27 -0400824 fEnclosingFunction = &funcDef;
John Stiles93442622020-09-11 12:11:27 -0400825 this->visitStatement(&funcDef.fBody);
826 break;
827 }
828 default:
829 // The inliner can't operate outside of a function's scope.
830 break;
831 }
832 }
833
834 void visitStatement(std::unique_ptr<Statement>* stmt,
835 bool isViableAsEnclosingStatement = true) {
836 if (!*stmt) {
837 return;
838 }
839
840 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
841 size_t oldSymbolStackSize = fSymbolTableStack.size();
842
843 if (isViableAsEnclosingStatement) {
844 fEnclosingStmtStack.push_back(stmt);
845 }
846
847 switch ((*stmt)->kind()) {
848 case Statement::Kind::kBreak:
849 case Statement::Kind::kContinue:
850 case Statement::Kind::kDiscard:
851 case Statement::Kind::kInlineMarker:
852 case Statement::Kind::kNop:
853 break;
854
855 case Statement::Kind::kBlock: {
856 Block& block = (*stmt)->as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400857 if (block.symbolTable()) {
858 fSymbolTableStack.push_back(block.symbolTable().get());
John Stiles93442622020-09-11 12:11:27 -0400859 }
860
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400861 for (std::unique_ptr<Statement>& stmt : block.children()) {
862 this->visitStatement(&stmt);
John Stiles93442622020-09-11 12:11:27 -0400863 }
864 break;
865 }
866 case Statement::Kind::kDo: {
867 DoStatement& doStmt = (*stmt)->as<DoStatement>();
868 // The loop body is a candidate for inlining.
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400869 this->visitStatement(&doStmt.statement());
John Stiles93442622020-09-11 12:11:27 -0400870 // The inliner isn't smart enough to inline the test-expression for a do-while
871 // loop at this time. There are two limitations:
872 // - We would need to insert the inlined-body block at the very end of the do-
873 // statement's inner fStatement. We don't support that today, but it's doable.
874 // - We cannot inline the test expression if the loop uses `continue` anywhere;
875 // that would skip over the inlined block that evaluates the test expression.
876 // There isn't a good fix for this--any workaround would be more complex than
877 // the cost of a function call. However, loops that don't use `continue` would
878 // still be viable candidates for inlining.
879 break;
880 }
881 case Statement::Kind::kExpression: {
882 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400883 this->visitExpression(&expr.expression());
John Stiles93442622020-09-11 12:11:27 -0400884 break;
885 }
886 case Statement::Kind::kFor: {
887 ForStatement& forStmt = (*stmt)->as<ForStatement>();
888 if (forStmt.fSymbols) {
889 fSymbolTableStack.push_back(forStmt.fSymbols.get());
890 }
891
892 // The initializer and loop body are candidates for inlining.
893 this->visitStatement(&forStmt.fInitializer,
894 /*isViableAsEnclosingStatement=*/false);
895 this->visitStatement(&forStmt.fStatement);
896
897 // The inliner isn't smart enough to inline the test- or increment-expressions
898 // of a for loop loop at this time. There are a handful of limitations:
899 // - We would need to insert the test-expression block at the very beginning of
900 // the for-loop's inner fStatement, and the increment-expression block at the
901 // very end. We don't support that today, but it's doable.
902 // - The for-loop's built-in test-expression would need to be dropped entirely,
903 // and the loop would be halted via a break statement at the end of the
904 // inlined test-expression. This is again something we don't support today,
905 // but it could be implemented.
906 // - We cannot inline the increment-expression if the loop uses `continue`
907 // anywhere; that would skip over the inlined block that evaluates the
908 // increment expression. There isn't a good fix for this--any workaround would
909 // be more complex than the cost of a function call. However, loops that don't
910 // use `continue` would still be viable candidates for increment-expression
911 // inlining.
912 break;
913 }
914 case Statement::Kind::kIf: {
915 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
916 this->visitExpression(&ifStmt.fTest);
917 this->visitStatement(&ifStmt.fIfTrue);
918 this->visitStatement(&ifStmt.fIfFalse);
919 break;
920 }
921 case Statement::Kind::kReturn: {
922 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
923 this->visitExpression(&returnStmt.fExpression);
924 break;
925 }
926 case Statement::Kind::kSwitch: {
927 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
928 if (switchStmt.fSymbols) {
929 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
930 }
931
932 this->visitExpression(&switchStmt.fValue);
933 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
934 // The switch-case's fValue cannot be a FunctionCall; skip it.
935 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
936 this->visitStatement(&caseBlock);
937 }
938 }
939 break;
940 }
941 case Statement::Kind::kVarDeclaration: {
942 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
943 // Don't need to scan the declaration's sizes; those are always IntLiterals.
944 this->visitExpression(&varDeclStmt.fValue);
945 break;
946 }
947 case Statement::Kind::kVarDeclarations: {
948 VarDeclarationsStatement& varDecls = (*stmt)->as<VarDeclarationsStatement>();
949 for (std::unique_ptr<Statement>& varDecl : varDecls.fDeclaration->fVars) {
950 this->visitStatement(&varDecl, /*isViableAsEnclosingStatement=*/false);
951 }
952 break;
953 }
954 case Statement::Kind::kWhile: {
955 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
956 // The loop body is a candidate for inlining.
957 this->visitStatement(&whileStmt.fStatement);
958 // The inliner isn't smart enough to inline the test-expression for a while
959 // loop at this time. There are two limitations:
960 // - We would need to insert the inlined-body block at the very beginning of the
961 // while loop's inner fStatement. We don't support that today, but it's
962 // doable.
963 // - The while-loop's built-in test-expression would need to be replaced with a
964 // `true` BoolLiteral, and the loop would be halted via a break statement at
965 // the end of the inlined test-expression. This is again something we don't
966 // support today, but it could be implemented.
967 break;
968 }
969 default:
970 SkUNREACHABLE;
971 }
972
973 // Pop our symbol and enclosing-statement stacks.
974 fSymbolTableStack.resize(oldSymbolStackSize);
975 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
976 }
977
978 void visitExpression(std::unique_ptr<Expression>* expr) {
979 if (!*expr) {
980 return;
981 }
982
983 switch ((*expr)->kind()) {
984 case Expression::Kind::kBoolLiteral:
985 case Expression::Kind::kDefined:
986 case Expression::Kind::kExternalValue:
987 case Expression::Kind::kFieldAccess:
988 case Expression::Kind::kFloatLiteral:
989 case Expression::Kind::kFunctionReference:
990 case Expression::Kind::kIntLiteral:
991 case Expression::Kind::kNullLiteral:
992 case Expression::Kind::kSetting:
993 case Expression::Kind::kTypeReference:
994 case Expression::Kind::kVariableReference:
995 // Nothing to scan here.
996 break;
997
998 case Expression::Kind::kBinary: {
999 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001000 this->visitExpression(&binaryExpr.leftPointer());
John Stiles93442622020-09-11 12:11:27 -04001001
1002 // Logical-and and logical-or binary expressions do not inline the right side,
1003 // because that would invalidate short-circuiting. That is, when evaluating
1004 // expressions like these:
1005 // (false && x()) // always false
1006 // (true || y()) // always true
1007 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1008 // enforce that rule is to avoid inlining the right side entirely. However, it
1009 // is safe for other types of binary expression to inline both sides.
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001010 Token::Kind op = binaryExpr.getOperator();
1011 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1012 op == Token::Kind::TK_LOGICALOR);
John Stiles93442622020-09-11 12:11:27 -04001013 if (!shortCircuitable) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001014 this->visitExpression(&binaryExpr.rightPointer());
John Stiles93442622020-09-11 12:11:27 -04001015 }
1016 break;
1017 }
1018 case Expression::Kind::kConstructor: {
1019 Constructor& constructorExpr = (*expr)->as<Constructor>();
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001020 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
John Stiles93442622020-09-11 12:11:27 -04001021 this->visitExpression(&arg);
1022 }
1023 break;
1024 }
1025 case Expression::Kind::kExternalFunctionCall: {
1026 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
Ethan Nicholas6e86ec92020-09-30 14:29:56 -04001027 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
John Stiles93442622020-09-11 12:11:27 -04001028 this->visitExpression(&arg);
1029 }
1030 break;
1031 }
1032 case Expression::Kind::kFunctionCall: {
1033 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
1034 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
1035 this->visitExpression(&arg);
1036 }
1037 this->addInlineCandidate(expr);
1038 break;
1039 }
1040 case Expression::Kind::kIndex:{
1041 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
1042 this->visitExpression(&indexExpr.fBase);
1043 this->visitExpression(&indexExpr.fIndex);
1044 break;
1045 }
1046 case Expression::Kind::kPostfix: {
1047 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
1048 this->visitExpression(&postfixExpr.fOperand);
1049 break;
1050 }
1051 case Expression::Kind::kPrefix: {
1052 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
1053 this->visitExpression(&prefixExpr.fOperand);
1054 break;
1055 }
1056 case Expression::Kind::kSwizzle: {
1057 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
1058 this->visitExpression(&swizzleExpr.fBase);
1059 break;
1060 }
1061 case Expression::Kind::kTernary: {
1062 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1063 // The test expression is a candidate for inlining.
1064 this->visitExpression(&ternaryExpr.fTest);
1065 // The true- and false-expressions cannot be inlined, because we are only
1066 // allowed to evaluate one side.
1067 break;
1068 }
1069 default:
1070 SkUNREACHABLE;
1071 }
1072 }
1073
1074 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1075 fInlineCandidates.push_back(InlineCandidate{fSymbolTableStack.back(),
John Stiles915a38c2020-09-14 09:38:13 -04001076 find_parent_statement(fEnclosingStmtStack),
1077 fEnclosingStmtStack.back(),
Brian Osman3887a012020-09-30 13:22:27 -04001078 candidate,
1079 fEnclosingFunction});
John Stiles93442622020-09-11 12:11:27 -04001080 }
1081 };
1082
John Stiles93442622020-09-11 12:11:27 -04001083 InlineCandidateAnalyzer analyzer;
1084 analyzer.visit(program);
John Stiles915a38c2020-09-14 09:38:13 -04001085
1086 // For each of our candidate function-call sites, check if it is actually safe to inline.
1087 // Memoize our results so we don't check a function more than once.
John Stiles93442622020-09-11 12:11:27 -04001088 std::unordered_map<const FunctionDeclaration*, bool> inlinableMap; // <function, safe-to-inline>
John Stiles915a38c2020-09-14 09:38:13 -04001089 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
John Stiles93442622020-09-11 12:11:27 -04001090 const FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1091 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1092 if (inlinableMap.find(funcDecl) == inlinableMap.end()) {
1093 // We do not perform inlining on recursive calls to avoid an infinite death spiral of
1094 // inlining.
1095 int inlineThreshold = (funcDecl->fCallCount.load() > 1) ? fSettings->fInlineThreshold
1096 : INT_MAX;
1097 inlinableMap[funcDecl] = this->isSafeToInline(funcCall, inlineThreshold) &&
1098 !contains_recursive_call(*funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001099 }
1100 }
1101
John Stiles915a38c2020-09-14 09:38:13 -04001102 // Inline the candidates where we've determined that it's safe to do so.
1103 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1104 bool madeChanges = false;
1105 for (const InlineCandidate& candidate : analyzer.fInlineCandidates) {
1106 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1107 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1108
1109 // If we determined that this candidate was not actually inlinable, skip it.
1110 if (!inlinableMap[funcDecl]) {
1111 continue;
1112 }
1113
1114 // Inlining two expressions using the same enclosing statement in the same inlining pass
1115 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1116 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1117 if (!inserted) {
1118 continue;
1119 }
1120
1121 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001122 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
1123 &candidate.fEnclosingFunction->fDeclaration);
John Stiles915a38c2020-09-14 09:38:13 -04001124 if (inlinedCall.fInlinedBody) {
1125 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001126 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001127
1128 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1129 // function, then replace the enclosing statement with that Block.
1130 // Before:
1131 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1132 // fEnclosingStmt = stmt4
1133 // After:
1134 // fInlinedBody = null
1135 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001136 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001137 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1138 }
1139
1140 // Replace the candidate function call with our replacement expression.
1141 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1142 madeChanges = true;
1143
1144 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1145 // remain valid.
1146 }
1147
1148 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001149}
1150
John Stiles44e96be2020-08-31 13:16:04 -04001151} // namespace SkSL