blob: e6928de29a9bbc667a8a692551d1cd629ea5749a [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) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400197 return symbolTable.takeOwnershipOfSymbol(std::make_unique<Type>(src->name(),
198 src->typeKind(),
199 src->componentType(),
200 src->columns()));
John Stiles44e96be2020-08-31 13:16:04 -0400201 }
202 return src;
203}
204
John Stiles6d696082020-10-01 10:18:54 -0400205static std::unique_ptr<Statement>* find_parent_statement(
206 const std::vector<std::unique_ptr<Statement>*>& stmtStack) {
John Stiles915a38c2020-09-14 09:38:13 -0400207 SkASSERT(!stmtStack.empty());
208
209 // Walk the statement stack from back to front, ignoring the last element (which is the
210 // enclosing statement).
211 auto iter = stmtStack.rbegin();
212 ++iter;
213
214 // Anything counts as a parent statement other than a scopeless Block.
215 for (; iter != stmtStack.rend(); ++iter) {
John Stiles6d696082020-10-01 10:18:54 -0400216 std::unique_ptr<Statement>* stmt = *iter;
217 if (!(*stmt)->is<Block>() || (*stmt)->as<Block>().isScope()) {
John Stiles915a38c2020-09-14 09:38:13 -0400218 return stmt;
219 }
220 }
221
222 // There wasn't any parent statement to be found.
223 return nullptr;
224}
225
John Stilese41b4ee2020-09-28 12:28:16 -0400226std::unique_ptr<Expression> clone_with_ref_kind(const Expression& expr,
227 VariableReference::RefKind refKind) {
228 std::unique_ptr<Expression> clone = expr.clone();
John Stiles70b82422020-09-30 10:55:12 -0400229 class SetRefKindInExpression : public ProgramWriter {
John Stilese41b4ee2020-09-28 12:28:16 -0400230 public:
231 SetRefKindInExpression(VariableReference::RefKind refKind) : fRefKind(refKind) {}
John Stiles70b82422020-09-30 10:55:12 -0400232 bool visitExpression(Expression& expr) override {
John Stilese41b4ee2020-09-28 12:28:16 -0400233 if (expr.is<VariableReference>()) {
John Stiles70b82422020-09-30 10:55:12 -0400234 expr.as<VariableReference>().setRefKind(fRefKind);
John Stilese41b4ee2020-09-28 12:28:16 -0400235 }
236 return INHERITED::visitExpression(expr);
237 }
238
239 private:
240 VariableReference::RefKind fRefKind;
241
John Stiles70b82422020-09-30 10:55:12 -0400242 using INHERITED = ProgramWriter;
John Stilese41b4ee2020-09-28 12:28:16 -0400243 };
244
245 SetRefKindInExpression{refKind}.visitExpression(*clone);
246 return clone;
247}
248
John Stiles44733aa2020-09-29 17:42:23 -0400249bool is_trivial_argument(const Expression& argument) {
250 return argument.is<VariableReference>() ||
251 (argument.is<Swizzle>() && is_trivial_argument(*argument.as<Swizzle>().fBase)) ||
252 (argument.is<FieldAccess>() && is_trivial_argument(*argument.as<FieldAccess>().fBase)) ||
John Stiles80ccdbd2020-09-30 11:58:16 -0400253 (argument.is<Constructor>() &&
254 argument.as<Constructor>().arguments().size() == 1 &&
255 is_trivial_argument(*argument.as<Constructor>().arguments().front())) ||
John Stiles44733aa2020-09-29 17:42:23 -0400256 (argument.is<IndexExpression>() &&
257 argument.as<IndexExpression>().fIndex->is<IntLiteral>() &&
258 is_trivial_argument(*argument.as<IndexExpression>().fBase));
259}
260
John Stiles44e96be2020-08-31 13:16:04 -0400261} // namespace
262
John Stilesb61ee902020-09-21 12:26:59 -0400263void Inliner::ensureScopedBlocks(Statement* inlinedBody, Statement* parentStmt) {
264 // No changes necessary if this statement isn't actually a block.
265 if (!inlinedBody || !inlinedBody->is<Block>()) {
266 return;
267 }
268
269 // No changes necessary if the parent statement doesn't require a scope.
270 if (!parentStmt || !(parentStmt->is<IfStatement>() || parentStmt->is<ForStatement>() ||
271 parentStmt->is<DoStatement>() || parentStmt->is<WhileStatement>())) {
272 return;
273 }
274
275 Block& block = inlinedBody->as<Block>();
276
277 // The inliner will create inlined function bodies as a Block containing multiple statements,
278 // but no scope. Normally, this is fine, but if this block is used as the statement for a
279 // do/for/if/while, this isn't actually possible to represent textually; a scope must be added
280 // for the generated code to match the intent. In the case of Blocks nested inside other Blocks,
281 // we add the scope to the outermost block if needed. Zero-statement blocks have similar
282 // issues--if we don't represent the Block textually somehow, we run the risk of accidentally
283 // absorbing the following statement into our loop--so we also add a scope to these.
284 for (Block* nestedBlock = &block;; ) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400285 if (nestedBlock->isScope()) {
John Stilesb61ee902020-09-21 12:26:59 -0400286 // We found an explicit scope; all is well.
287 return;
288 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400289 if (nestedBlock->children().size() != 1) {
John Stilesb61ee902020-09-21 12:26:59 -0400290 // We found a block with multiple (or zero) statements, but no scope? Let's add a scope
291 // to the outermost block.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400292 block.setIsScope(true);
John Stilesb61ee902020-09-21 12:26:59 -0400293 return;
294 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400295 if (!nestedBlock->children()[0]->is<Block>()) {
John Stilesb61ee902020-09-21 12:26:59 -0400296 // This block has exactly one thing inside, and it's not another block. No need to scope
297 // it.
298 return;
299 }
300 // We have to go deeper.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400301 nestedBlock = &nestedBlock->children()[0]->as<Block>();
John Stilesb61ee902020-09-21 12:26:59 -0400302 }
303}
304
John Stiles44e96be2020-08-31 13:16:04 -0400305void Inliner::reset(const Context& context, const Program::Settings& settings) {
306 fContext = &context;
307 fSettings = &settings;
308 fInlineVarCounter = 0;
309}
310
John Stilesc75abb82020-09-14 18:24:12 -0400311String Inliner::uniqueNameForInlineVar(const String& baseName, SymbolTable* symbolTable) {
312 // If the base name starts with an underscore, like "_coords", we can't append another
313 // underscore, because OpenGL disallows two consecutive underscores anywhere in the string. But
314 // in the general case, using the underscore as a splitter reads nicely enough that it's worth
315 // putting in this special case.
316 const char* splitter = baseName.startsWith("_") ? "" : "_";
317
318 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
319 // we're not reusing an existing name. (Note that within a single compilation pass, this check
320 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
321 String uniqueName;
322 for (;;) {
323 uniqueName = String::printf("_%d%s%s", fInlineVarCounter++, splitter, baseName.c_str());
324 StringFragment frag{uniqueName.data(), uniqueName.length()};
325 if ((*symbolTable)[frag] == nullptr) {
326 break;
327 }
328 }
329
330 return uniqueName;
331}
332
John Stiles44e96be2020-08-31 13:16:04 -0400333std::unique_ptr<Expression> Inliner::inlineExpression(int offset,
334 VariableRewriteMap* varMap,
335 const Expression& expression) {
336 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
337 if (e) {
338 return this->inlineExpression(offset, varMap, *e);
339 }
340 return nullptr;
341 };
342 auto argList = [&](const std::vector<std::unique_ptr<Expression>>& originalArgs)
343 -> std::vector<std::unique_ptr<Expression>> {
344 std::vector<std::unique_ptr<Expression>> args;
345 args.reserve(originalArgs.size());
346 for (const std::unique_ptr<Expression>& arg : originalArgs) {
347 args.push_back(expr(arg));
348 }
349 return args;
350 };
351
Ethan Nicholase6592142020-09-08 10:22:09 -0400352 switch (expression.kind()) {
353 case Expression::Kind::kBinary: {
John Stiles44e96be2020-08-31 13:16:04 -0400354 const BinaryExpression& b = expression.as<BinaryExpression>();
355 return std::make_unique<BinaryExpression>(offset,
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400356 expr(b.leftPointer()),
357 b.getOperator(),
358 expr(b.rightPointer()),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400359 &b.type());
John Stiles44e96be2020-08-31 13:16:04 -0400360 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400361 case Expression::Kind::kBoolLiteral:
362 case Expression::Kind::kIntLiteral:
363 case Expression::Kind::kFloatLiteral:
364 case Expression::Kind::kNullLiteral:
John Stiles44e96be2020-08-31 13:16:04 -0400365 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400366 case Expression::Kind::kConstructor: {
John Stiles44e96be2020-08-31 13:16:04 -0400367 const Constructor& constructor = expression.as<Constructor>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400368 return std::make_unique<Constructor>(offset, &constructor.type(),
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400369 argList(constructor.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400370 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400371 case Expression::Kind::kExternalFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400372 const ExternalFunctionCall& externalCall = expression.as<ExternalFunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400373 return std::make_unique<ExternalFunctionCall>(offset, &externalCall.type(),
Ethan Nicholas6e86ec92020-09-30 14:29:56 -0400374 externalCall.function(),
375 argList(externalCall.arguments()));
John Stiles44e96be2020-08-31 13:16:04 -0400376 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400377 case Expression::Kind::kExternalValue:
John Stiles44e96be2020-08-31 13:16:04 -0400378 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400379 case Expression::Kind::kFieldAccess: {
John Stiles44e96be2020-08-31 13:16:04 -0400380 const FieldAccess& f = expression.as<FieldAccess>();
381 return std::make_unique<FieldAccess>(expr(f.fBase), f.fFieldIndex, f.fOwnerKind);
382 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400383 case Expression::Kind::kFunctionCall: {
John Stiles44e96be2020-08-31 13:16:04 -0400384 const FunctionCall& funcCall = expression.as<FunctionCall>();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400385 return std::make_unique<FunctionCall>(offset, &funcCall.type(), funcCall.fFunction,
John Stiles44e96be2020-08-31 13:16:04 -0400386 argList(funcCall.fArguments));
387 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400388 case Expression::Kind::kFunctionReference:
Brian Osman2b3b35f2020-09-08 09:17:36 -0400389 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400390 case Expression::Kind::kIndex: {
John Stiles44e96be2020-08-31 13:16:04 -0400391 const IndexExpression& idx = expression.as<IndexExpression>();
392 return std::make_unique<IndexExpression>(*fContext, expr(idx.fBase), expr(idx.fIndex));
393 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400394 case Expression::Kind::kPrefix: {
John Stiles44e96be2020-08-31 13:16:04 -0400395 const PrefixExpression& p = expression.as<PrefixExpression>();
396 return std::make_unique<PrefixExpression>(p.fOperator, expr(p.fOperand));
397 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400398 case Expression::Kind::kPostfix: {
John Stiles44e96be2020-08-31 13:16:04 -0400399 const PostfixExpression& p = expression.as<PostfixExpression>();
400 return std::make_unique<PostfixExpression>(expr(p.fOperand), p.fOperator);
401 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400402 case Expression::Kind::kSetting:
John Stiles44e96be2020-08-31 13:16:04 -0400403 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400404 case Expression::Kind::kSwizzle: {
John Stiles44e96be2020-08-31 13:16:04 -0400405 const Swizzle& s = expression.as<Swizzle>();
406 return std::make_unique<Swizzle>(*fContext, expr(s.fBase), s.fComponents);
407 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400408 case Expression::Kind::kTernary: {
John Stiles44e96be2020-08-31 13:16:04 -0400409 const TernaryExpression& t = expression.as<TernaryExpression>();
410 return std::make_unique<TernaryExpression>(offset, expr(t.fTest),
411 expr(t.fIfTrue), expr(t.fIfFalse));
412 }
Brian Osman83ba9302020-09-11 13:33:46 -0400413 case Expression::Kind::kTypeReference:
414 return expression.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400415 case Expression::Kind::kVariableReference: {
John Stiles44e96be2020-08-31 13:16:04 -0400416 const VariableReference& v = expression.as<VariableReference>();
John Stilese41b4ee2020-09-28 12:28:16 -0400417 auto varMapIter = varMap->find(v.fVariable);
418 if (varMapIter != varMap->end()) {
419 return clone_with_ref_kind(*varMapIter->second, v.fRefKind);
John Stiles44e96be2020-08-31 13:16:04 -0400420 }
421 return v.clone();
422 }
423 default:
424 SkASSERT(false);
425 return nullptr;
426 }
427}
428
429std::unique_ptr<Statement> Inliner::inlineStatement(int offset,
430 VariableRewriteMap* varMap,
431 SymbolTable* symbolTableForStatement,
John Stilese41b4ee2020-09-28 12:28:16 -0400432 const Expression* resultExpr,
John Stiles44e96be2020-08-31 13:16:04 -0400433 bool haveEarlyReturns,
Brian Osman3887a012020-09-30 13:22:27 -0400434 const Statement& statement,
435 bool isBuiltinCode) {
John Stiles44e96be2020-08-31 13:16:04 -0400436 auto stmt = [&](const std::unique_ptr<Statement>& s) -> std::unique_ptr<Statement> {
437 if (s) {
John Stilesa5f3c312020-09-22 12:05:16 -0400438 return this->inlineStatement(offset, varMap, symbolTableForStatement, resultExpr,
Brian Osman3887a012020-09-30 13:22:27 -0400439 haveEarlyReturns, *s, isBuiltinCode);
John Stiles44e96be2020-08-31 13:16:04 -0400440 }
441 return nullptr;
442 };
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400443 auto blockStmts = [&](const Block& block) {
444 std::vector<std::unique_ptr<Statement>> result;
445 for (const std::unique_ptr<Statement>& child : block.children()) {
446 result.push_back(stmt(child));
447 }
448 return result;
449 };
John Stiles44e96be2020-08-31 13:16:04 -0400450 auto stmts = [&](const std::vector<std::unique_ptr<Statement>>& ss) {
451 std::vector<std::unique_ptr<Statement>> result;
452 for (const auto& s : ss) {
453 result.push_back(stmt(s));
454 }
455 return result;
456 };
457 auto expr = [&](const std::unique_ptr<Expression>& e) -> std::unique_ptr<Expression> {
458 if (e) {
459 return this->inlineExpression(offset, varMap, *e);
460 }
461 return nullptr;
462 };
Ethan Nicholase6592142020-09-08 10:22:09 -0400463 switch (statement.kind()) {
464 case Statement::Kind::kBlock: {
John Stiles44e96be2020-08-31 13:16:04 -0400465 const Block& b = statement.as<Block>();
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400466 return std::make_unique<Block>(offset, blockStmts(b), b.symbolTable(), b.isScope());
John Stiles44e96be2020-08-31 13:16:04 -0400467 }
468
Ethan Nicholase6592142020-09-08 10:22:09 -0400469 case Statement::Kind::kBreak:
470 case Statement::Kind::kContinue:
471 case Statement::Kind::kDiscard:
John Stiles44e96be2020-08-31 13:16:04 -0400472 return statement.clone();
473
Ethan Nicholase6592142020-09-08 10:22:09 -0400474 case Statement::Kind::kDo: {
John Stiles44e96be2020-08-31 13:16:04 -0400475 const DoStatement& d = statement.as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -0400476 return std::make_unique<DoStatement>(offset, stmt(d.statement()), expr(d.test()));
John Stiles44e96be2020-08-31 13:16:04 -0400477 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400478 case Statement::Kind::kExpression: {
John Stiles44e96be2020-08-31 13:16:04 -0400479 const ExpressionStatement& e = statement.as<ExpressionStatement>();
Ethan Nicholasd503a5a2020-09-30 09:29:55 -0400480 return std::make_unique<ExpressionStatement>(expr(e.expression()));
John Stiles44e96be2020-08-31 13:16:04 -0400481 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400482 case Statement::Kind::kFor: {
John Stiles44e96be2020-08-31 13:16:04 -0400483 const ForStatement& f = statement.as<ForStatement>();
484 // need to ensure initializer is evaluated first so that we've already remapped its
485 // declarations by the time we evaluate test & next
486 std::unique_ptr<Statement> initializer = stmt(f.fInitializer);
487 return std::make_unique<ForStatement>(offset, std::move(initializer), expr(f.fTest),
488 expr(f.fNext), stmt(f.fStatement), f.fSymbols);
489 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400490 case Statement::Kind::kIf: {
John Stiles44e96be2020-08-31 13:16:04 -0400491 const IfStatement& i = statement.as<IfStatement>();
492 return std::make_unique<IfStatement>(offset, i.fIsStatic, expr(i.fTest),
493 stmt(i.fIfTrue), stmt(i.fIfFalse));
494 }
John Stiles98c1f822020-09-09 14:18:53 -0400495 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -0400496 case Statement::Kind::kNop:
John Stiles44e96be2020-08-31 13:16:04 -0400497 return statement.clone();
Ethan Nicholase6592142020-09-08 10:22:09 -0400498 case Statement::Kind::kReturn: {
John Stiles44e96be2020-08-31 13:16:04 -0400499 const ReturnStatement& r = statement.as<ReturnStatement>();
500 if (r.fExpression) {
John Stilese41b4ee2020-09-28 12:28:16 -0400501 SkASSERT(resultExpr);
John Stilesa5f3c312020-09-22 12:05:16 -0400502 auto assignment =
503 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
504 offset,
John Stilese41b4ee2020-09-28 12:28:16 -0400505 clone_with_ref_kind(*resultExpr, VariableReference::kWrite_RefKind),
John Stilesa5f3c312020-09-22 12:05:16 -0400506 Token::Kind::TK_EQ,
507 expr(r.fExpression),
John Stilese41b4ee2020-09-28 12:28:16 -0400508 &resultExpr->type()));
John Stiles44e96be2020-08-31 13:16:04 -0400509 if (haveEarlyReturns) {
510 std::vector<std::unique_ptr<Statement>> block;
511 block.push_back(std::move(assignment));
512 block.emplace_back(new BreakStatement(offset));
513 return std::make_unique<Block>(offset, std::move(block), /*symbols=*/nullptr,
514 /*isScope=*/true);
515 } else {
516 return std::move(assignment);
517 }
518 } else {
519 if (haveEarlyReturns) {
520 return std::make_unique<BreakStatement>(offset);
521 } else {
522 return std::make_unique<Nop>();
523 }
524 }
525 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400526 case Statement::Kind::kSwitch: {
John Stiles44e96be2020-08-31 13:16:04 -0400527 const SwitchStatement& ss = statement.as<SwitchStatement>();
528 std::vector<std::unique_ptr<SwitchCase>> cases;
529 for (const auto& sc : ss.fCases) {
530 cases.emplace_back(new SwitchCase(offset, expr(sc->fValue),
531 stmts(sc->fStatements)));
532 }
533 return std::make_unique<SwitchStatement>(offset, ss.fIsStatic, expr(ss.fValue),
534 std::move(cases), ss.fSymbols);
535 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400536 case Statement::Kind::kVarDeclaration: {
John Stiles44e96be2020-08-31 13:16:04 -0400537 const VarDeclaration& decl = statement.as<VarDeclaration>();
538 std::vector<std::unique_ptr<Expression>> sizes;
539 for (const auto& size : decl.fSizes) {
540 sizes.push_back(expr(size));
541 }
542 std::unique_ptr<Expression> initialValue = expr(decl.fValue);
543 const Variable* old = decl.fVar;
John Stilesc75abb82020-09-14 18:24:12 -0400544 // We assign unique names to inlined variables--scopes hide most of the problems in this
545 // regard, but see `InlinerAvoidsVariableNameOverlap` for a counterexample where unique
546 // names are important.
547 auto name = std::make_unique<String>(
Ethan Nicholase2c49992020-10-05 11:49:11 -0400548 this->uniqueNameForInlineVar(String(old->name()), symbolTableForStatement));
John Stiles44e96be2020-08-31 13:16:04 -0400549 const String* namePtr = symbolTableForStatement->takeOwnershipOfString(std::move(name));
Ethan Nicholas30d30222020-09-11 12:27:26 -0400550 const Type* typePtr = copy_if_needed(&old->type(), *symbolTableForStatement);
John Stiles44e96be2020-08-31 13:16:04 -0400551 const Variable* clone = symbolTableForStatement->takeOwnershipOfSymbol(
552 std::make_unique<Variable>(offset,
553 old->fModifiers,
554 namePtr->c_str(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400555 typePtr,
Brian Osman3887a012020-09-30 13:22:27 -0400556 isBuiltinCode,
John Stiles44e96be2020-08-31 13:16:04 -0400557 old->fStorage,
558 initialValue.get()));
John Stilese41b4ee2020-09-28 12:28:16 -0400559 (*varMap)[old] = std::make_unique<VariableReference>(offset, clone);
John Stiles44e96be2020-08-31 13:16:04 -0400560 return std::make_unique<VarDeclaration>(clone, std::move(sizes),
561 std::move(initialValue));
562 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400563 case Statement::Kind::kVarDeclarations: {
John Stiles44e96be2020-08-31 13:16:04 -0400564 const VarDeclarations& decls = *statement.as<VarDeclarationsStatement>().fDeclaration;
565 std::vector<std::unique_ptr<VarDeclaration>> vars;
566 for (const auto& var : decls.fVars) {
567 vars.emplace_back(&stmt(var).release()->as<VarDeclaration>());
568 }
569 const Type* typePtr = copy_if_needed(&decls.fBaseType, *symbolTableForStatement);
570 return std::unique_ptr<Statement>(new VarDeclarationsStatement(
571 std::make_unique<VarDeclarations>(offset, typePtr, std::move(vars))));
572 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400573 case Statement::Kind::kWhile: {
John Stiles44e96be2020-08-31 13:16:04 -0400574 const WhileStatement& w = statement.as<WhileStatement>();
575 return std::make_unique<WhileStatement>(offset, expr(w.fTest), stmt(w.fStatement));
576 }
577 default:
578 SkASSERT(false);
579 return nullptr;
580 }
581}
582
John Stiles6eadf132020-09-08 10:16:10 -0400583Inliner::InlinedCall Inliner::inlineCall(FunctionCall* call,
Brian Osman3887a012020-09-30 13:22:27 -0400584 SymbolTable* symbolTableForCall,
585 const FunctionDeclaration* caller) {
John Stiles44e96be2020-08-31 13:16:04 -0400586 // Inlining is more complicated here than in a typical compiler, because we have to have a
587 // high-level IR and can't just drop statements into the middle of an expression or even use
588 // gotos.
589 //
590 // Since we can't insert statements into an expression, we run the inline function as extra
591 // statements before the statement we're currently processing, relying on a lack of execution
592 // order guarantees. Since we can't use gotos (which are normally used to replace return
593 // statements), we wrap the whole function in a loop and use break statements to jump to the
594 // end.
595 SkASSERT(fSettings);
596 SkASSERT(fContext);
597 SkASSERT(call);
John Stiles2d7973a2020-10-02 15:01:03 -0400598 SkASSERT(this->isSafeToInline(call->fFunction.fDefinition));
John Stiles44e96be2020-08-31 13:16:04 -0400599
John Stiles44e96be2020-08-31 13:16:04 -0400600 std::vector<std::unique_ptr<Expression>>& arguments = call->fArguments;
John Stiles6eadf132020-09-08 10:16:10 -0400601 const int offset = call->fOffset;
John Stiles44e96be2020-08-31 13:16:04 -0400602 const FunctionDefinition& function = *call->fFunction.fDefinition;
John Stiles6eadf132020-09-08 10:16:10 -0400603 const bool hasEarlyReturn = has_early_return(function);
604
John Stiles44e96be2020-08-31 13:16:04 -0400605 InlinedCall inlinedCall;
John Stiles6eadf132020-09-08 10:16:10 -0400606 inlinedCall.fInlinedBody = std::make_unique<Block>(offset,
607 std::vector<std::unique_ptr<Statement>>{},
608 /*symbols=*/nullptr,
609 /*isScope=*/false);
John Stiles98c1f822020-09-09 14:18:53 -0400610
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400611 Block& inlinedBody = *inlinedCall.fInlinedBody;
612 inlinedBody.children().reserve(1 + // Inline marker
613 1 + // Result variable
614 arguments.size() + // Function arguments (passing in)
John Stilese41b4ee2020-09-28 12:28:16 -0400615 arguments.size() + // Function arguments (copy out-params back)
616 1); // Inlined code (Block or do-while loop)
John Stiles98c1f822020-09-09 14:18:53 -0400617
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400618 inlinedBody.children().push_back(std::make_unique<InlineMarker>(call->fFunction));
John Stiles44e96be2020-08-31 13:16:04 -0400619
John Stilese41b4ee2020-09-28 12:28:16 -0400620 auto makeInlineVar =
621 [&](const String& baseName, const Type* type, Modifiers modifiers,
622 std::unique_ptr<Expression>* initialValue) -> std::unique_ptr<Expression> {
John Stilesa003e812020-09-11 09:43:49 -0400623 // $floatLiteral or $intLiteral aren't real types that we can use for scratch variables, so
624 // replace them if they ever appear here. If this happens, we likely forgot to coerce a type
625 // somewhere during compilation.
626 if (type == fContext->fFloatLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400627 SkDEBUGFAIL("found a $floatLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400628 type = fContext->fFloat_Type.get();
629 } else if (type == fContext->fIntLiteral_Type.get()) {
John Stilesd2be5c52020-09-11 14:58:06 -0400630 SkDEBUGFAIL("found an $intLiteral type while inlining");
John Stilesa003e812020-09-11 09:43:49 -0400631 type = fContext->fInt_Type.get();
632 }
633
John Stilesc75abb82020-09-14 18:24:12 -0400634 // Provide our new variable with a unique name, and add it to our symbol table.
635 String uniqueName = this->uniqueNameForInlineVar(baseName, symbolTableForCall);
John Stilescf936f92020-08-31 17:18:45 -0400636 const String* namePtr = symbolTableForCall->takeOwnershipOfString(
637 std::make_unique<String>(std::move(uniqueName)));
John Stiles44e96be2020-08-31 13:16:04 -0400638 StringFragment nameFrag{namePtr->c_str(), namePtr->length()};
639
640 // Add our new variable to the symbol table.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400641 auto newVar = std::make_unique<Variable>(/*offset=*/-1, Modifiers(), nameFrag, type,
Brian Osman3887a012020-09-30 13:22:27 -0400642 caller->fBuiltin, Variable::kLocal_Storage,
643 initialValue->get());
John Stiles44e96be2020-08-31 13:16:04 -0400644 const Variable* variableSymbol = symbolTableForCall->add(nameFrag, std::move(newVar));
645
646 // Prepare the variable declaration (taking extra care with `out` params to not clobber any
647 // initial value).
648 std::vector<std::unique_ptr<VarDeclaration>> variables;
649 if (initialValue && (modifiers.fFlags & Modifiers::kOut_Flag)) {
650 variables.push_back(std::make_unique<VarDeclaration>(
651 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
652 (*initialValue)->clone()));
653 } else {
654 variables.push_back(std::make_unique<VarDeclaration>(
655 variableSymbol, /*sizes=*/std::vector<std::unique_ptr<Expression>>{},
656 std::move(*initialValue)));
657 }
658
659 // Add the new variable-declaration statement to our block of extra statements.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400660 inlinedBody.children().push_back(std::make_unique<VarDeclarationsStatement>(
John Stilesa003e812020-09-11 09:43:49 -0400661 std::make_unique<VarDeclarations>(offset, type, std::move(variables))));
John Stiles44e96be2020-08-31 13:16:04 -0400662
John Stilese41b4ee2020-09-28 12:28:16 -0400663 return std::make_unique<VariableReference>(offset, variableSymbol);
John Stiles44e96be2020-08-31 13:16:04 -0400664 };
665
666 // Create a variable to hold the result in the extra statements (excepting void).
John Stilese41b4ee2020-09-28 12:28:16 -0400667 std::unique_ptr<Expression> resultExpr;
John Stiles44e96be2020-08-31 13:16:04 -0400668 if (function.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles44e96be2020-08-31 13:16:04 -0400669 std::unique_ptr<Expression> noInitialValue;
Ethan Nicholase2c49992020-10-05 11:49:11 -0400670 resultExpr = makeInlineVar(String(function.fDeclaration.name()),
John Stilese41b4ee2020-09-28 12:28:16 -0400671 &function.fDeclaration.fReturnType,
672 Modifiers{}, &noInitialValue);
673 }
John Stiles44e96be2020-08-31 13:16:04 -0400674
675 // Create variables in the extra statements to hold the arguments, and assign the arguments to
676 // them.
677 VariableRewriteMap varMap;
John Stilese41b4ee2020-09-28 12:28:16 -0400678 std::vector<int> argsToCopyBack;
John Stiles44e96be2020-08-31 13:16:04 -0400679 for (int i = 0; i < (int) arguments.size(); ++i) {
680 const Variable* param = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400681 bool isOutParam = param->fModifiers.fFlags & Modifiers::kOut_Flag;
John Stiles44e96be2020-08-31 13:16:04 -0400682
John Stiles44733aa2020-09-29 17:42:23 -0400683 // If this argument can be inlined trivially (e.g. a swizzle, or a constant array index)...
684 if (is_trivial_argument(*arguments[i])) {
John Stilese41b4ee2020-09-28 12:28:16 -0400685 // ... and it's an `out` param, or it isn't written to within the inline function...
686 if (isOutParam || !Analysis::StatementWritesToVariable(*function.fBody, *param)) {
John Stilesf201af82020-09-29 16:57:55 -0400687 // ... we don't need to copy it at all! We can just use the existing expression.
688 varMap[param] = arguments[i]->clone();
John Stiles44e96be2020-08-31 13:16:04 -0400689 continue;
690 }
691 }
692
John Stilese41b4ee2020-09-28 12:28:16 -0400693 if (isOutParam) {
694 argsToCopyBack.push_back(i);
695 }
696
Ethan Nicholase2c49992020-10-05 11:49:11 -0400697 varMap[param] = makeInlineVar(String(param->name()), &arguments[i]->type(),
Ethan Nicholas30d30222020-09-11 12:27:26 -0400698 param->fModifiers, &arguments[i]);
John Stiles44e96be2020-08-31 13:16:04 -0400699 }
700
701 const Block& body = function.fBody->as<Block>();
John Stiles44e96be2020-08-31 13:16:04 -0400702 auto inlineBlock = std::make_unique<Block>(offset, std::vector<std::unique_ptr<Statement>>{});
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400703 inlineBlock->children().reserve(body.children().size());
704 for (const std::unique_ptr<Statement>& stmt : body.children()) {
Brian Osman3887a012020-09-30 13:22:27 -0400705 inlineBlock->children().push_back(this->inlineStatement(offset, &varMap, symbolTableForCall,
706 resultExpr.get(), hasEarlyReturn,
707 *stmt, caller->fBuiltin));
John Stiles44e96be2020-08-31 13:16:04 -0400708 }
709 if (hasEarlyReturn) {
710 // Since we output to backends that don't have a goto statement (which would normally be
711 // used to perform an early return), we fake it by wrapping the function in a
712 // do { } while (false); and then use break statements to jump to the end in order to
713 // emulate a goto.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400714 inlinedBody.children().push_back(std::make_unique<DoStatement>(
John Stiles44e96be2020-08-31 13:16:04 -0400715 /*offset=*/-1,
716 std::move(inlineBlock),
717 std::make_unique<BoolLiteral>(*fContext, offset, /*value=*/false)));
718 } else {
John Stiles6eadf132020-09-08 10:16:10 -0400719 // No early returns, so we can just dump the code in. We still need to keep the block so we
720 // don't get name conflicts with locals.
Ethan Nicholas7bd60432020-09-25 14:31:59 -0400721 inlinedBody.children().push_back(std::move(inlineBlock));
John Stiles44e96be2020-08-31 13:16:04 -0400722 }
723
John Stilese41b4ee2020-09-28 12:28:16 -0400724 // Copy back the values of `out` parameters into their real destinations.
725 for (int i : argsToCopyBack) {
John Stiles44e96be2020-08-31 13:16:04 -0400726 const Variable* p = function.fDeclaration.fParameters[i];
John Stilese41b4ee2020-09-28 12:28:16 -0400727 SkASSERT(varMap.find(p) != varMap.end());
728 inlinedBody.children().push_back(
729 std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
730 offset,
731 clone_with_ref_kind(*arguments[i], VariableReference::kWrite_RefKind),
732 Token::Kind::TK_EQ,
733 std::move(varMap[p]),
734 &arguments[i]->type())));
John Stiles44e96be2020-08-31 13:16:04 -0400735 }
736
John Stilese41b4ee2020-09-28 12:28:16 -0400737 if (resultExpr != nullptr) {
738 // Return our result variable as our replacement expression.
739 SkASSERT(resultExpr->as<VariableReference>().fRefKind == VariableReference::kRead_RefKind);
740 inlinedCall.fReplacementExpr = std::move(resultExpr);
John Stiles44e96be2020-08-31 13:16:04 -0400741 } else {
742 // It's a void function, so it doesn't actually result in anything, but we have to return
743 // something non-null as a standin.
744 inlinedCall.fReplacementExpr = std::make_unique<BoolLiteral>(*fContext, offset,
745 /*value=*/false);
746 }
747
John Stiles44e96be2020-08-31 13:16:04 -0400748 return inlinedCall;
749}
750
John Stiles2d7973a2020-10-02 15:01:03 -0400751bool Inliner::isSafeToInline(const FunctionDefinition* functionDef) {
John Stiles44e96be2020-08-31 13:16:04 -0400752 SkASSERT(fSettings);
753
John Stiles2d7973a2020-10-02 15:01:03 -0400754 if (functionDef == nullptr) {
John Stiles44e96be2020-08-31 13:16:04 -0400755 // Can't inline something if we don't actually have its definition.
756 return false;
757 }
John Stiles2d7973a2020-10-02 15:01:03 -0400758
John Stiles44e96be2020-08-31 13:16:04 -0400759 if (!fSettings->fCaps || !fSettings->fCaps->canUseDoLoops()) {
760 // We don't have do-while loops. We use do-while loops to simulate early returns, so we
761 // can't inline functions that have an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400762 bool hasEarlyReturn = has_early_return(*functionDef);
John Stiles44e96be2020-08-31 13:16:04 -0400763
764 // If we didn't detect an early return, there shouldn't be any returns in breakable
765 // constructs either.
John Stiles2d7973a2020-10-02 15:01:03 -0400766 SkASSERT(hasEarlyReturn || count_returns_in_breakable_constructs(*functionDef) == 0);
John Stiles44e96be2020-08-31 13:16:04 -0400767 return !hasEarlyReturn;
768 }
769 // We have do-while loops, but we don't have any mechanism to simulate early returns within a
770 // 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 -0400771 bool hasReturnInBreakableConstruct = (count_returns_in_breakable_constructs(*functionDef) > 0);
John Stiles44e96be2020-08-31 13:16:04 -0400772
773 // If we detected returns in breakable constructs, we should also detect an early return.
John Stiles2d7973a2020-10-02 15:01:03 -0400774 SkASSERT(!hasReturnInBreakableConstruct || has_early_return(*functionDef));
John Stiles44e96be2020-08-31 13:16:04 -0400775 return !hasReturnInBreakableConstruct;
776}
777
John Stiles2d7973a2020-10-02 15:01:03 -0400778// A candidate function for inlining, containing everything that `inlineCall` needs.
779struct InlineCandidate {
780 SymbolTable* fSymbols; // the SymbolTable of the candidate
781 std::unique_ptr<Statement>* fParentStmt; // the parent Statement of the enclosing stmt
782 std::unique_ptr<Statement>* fEnclosingStmt; // the Statement containing the candidate
783 std::unique_ptr<Expression>* fCandidateExpr; // the candidate FunctionCall to be inlined
784 FunctionDefinition* fEnclosingFunction; // the Function containing the candidate
785 bool fIsLargeFunction; // does candidate exceed the inline threshold?
786};
John Stiles93442622020-09-11 12:11:27 -0400787
John Stiles2d7973a2020-10-02 15:01:03 -0400788struct InlineCandidateList {
789 std::vector<InlineCandidate> fCandidates;
790};
791
792class InlineCandidateAnalyzer {
John Stiles70957c82020-10-02 16:42:10 -0400793public:
794 // A list of all the inlining candidates we found during analysis.
795 InlineCandidateList* fCandidateList;
John Stiles2d7973a2020-10-02 15:01:03 -0400796
John Stiles70957c82020-10-02 16:42:10 -0400797 // A stack of the symbol tables; since most nodes don't have one, expected to be shallower than
798 // the enclosing-statement stack.
799 std::vector<SymbolTable*> fSymbolTableStack;
800 // A stack of "enclosing" statements--these would be suitable for the inliner to use for adding
801 // new instructions. Not all statements are suitable (e.g. a for-loop's initializer). The
802 // inliner might replace a statement with a block containing the statement.
803 std::vector<std::unique_ptr<Statement>*> fEnclosingStmtStack;
804 // The function that we're currently processing (i.e. inlining into).
805 FunctionDefinition* fEnclosingFunction = nullptr;
John Stiles93442622020-09-11 12:11:27 -0400806
John Stiles70957c82020-10-02 16:42:10 -0400807 void visit(Program& program, InlineCandidateList* candidateList) {
808 fCandidateList = candidateList;
809 fSymbolTableStack.push_back(program.fSymbols.get());
John Stiles93442622020-09-11 12:11:27 -0400810
John Stiles70957c82020-10-02 16:42:10 -0400811 for (ProgramElement& pe : program) {
812 this->visitProgramElement(&pe);
John Stiles93442622020-09-11 12:11:27 -0400813 }
814
John Stiles70957c82020-10-02 16:42:10 -0400815 fSymbolTableStack.pop_back();
816 fCandidateList = nullptr;
817 }
818
819 void visitProgramElement(ProgramElement* pe) {
820 switch (pe->kind()) {
821 case ProgramElement::Kind::kFunction: {
822 FunctionDefinition& funcDef = pe->as<FunctionDefinition>();
823 fEnclosingFunction = &funcDef;
824 this->visitStatement(&funcDef.fBody);
825 break;
John Stiles93442622020-09-11 12:11:27 -0400826 }
John Stiles70957c82020-10-02 16:42:10 -0400827 default:
828 // The inliner can't operate outside of a function's scope.
829 break;
830 }
831 }
832
833 void visitStatement(std::unique_ptr<Statement>* stmt,
834 bool isViableAsEnclosingStatement = true) {
835 if (!*stmt) {
836 return;
John Stiles93442622020-09-11 12:11:27 -0400837 }
838
John Stiles70957c82020-10-02 16:42:10 -0400839 size_t oldEnclosingStmtStackSize = fEnclosingStmtStack.size();
840 size_t oldSymbolStackSize = fSymbolTableStack.size();
John Stiles93442622020-09-11 12:11:27 -0400841
John Stiles70957c82020-10-02 16:42:10 -0400842 if (isViableAsEnclosingStatement) {
843 fEnclosingStmtStack.push_back(stmt);
John Stiles93442622020-09-11 12:11:27 -0400844 }
845
John Stiles70957c82020-10-02 16:42:10 -0400846 switch ((*stmt)->kind()) {
847 case Statement::Kind::kBreak:
848 case Statement::Kind::kContinue:
849 case Statement::Kind::kDiscard:
850 case Statement::Kind::kInlineMarker:
851 case Statement::Kind::kNop:
852 break;
853
854 case Statement::Kind::kBlock: {
855 Block& block = (*stmt)->as<Block>();
856 if (block.symbolTable()) {
857 fSymbolTableStack.push_back(block.symbolTable().get());
858 }
859
860 for (std::unique_ptr<Statement>& stmt : block.children()) {
861 this->visitStatement(&stmt);
862 }
863 break;
John Stiles93442622020-09-11 12:11:27 -0400864 }
John Stiles70957c82020-10-02 16:42:10 -0400865 case Statement::Kind::kDo: {
866 DoStatement& doStmt = (*stmt)->as<DoStatement>();
867 // The loop body is a candidate for inlining.
868 this->visitStatement(&doStmt.statement());
869 // The inliner isn't smart enough to inline the test-expression for a do-while
870 // loop at this time. There are two limitations:
871 // - We would need to insert the inlined-body block at the very end of the do-
872 // statement's inner fStatement. We don't support that today, but it's doable.
873 // - We cannot inline the test expression if the loop uses `continue` anywhere; that
874 // would skip over the inlined block that evaluates the test expression. There
875 // isn't a good fix for this--any workaround would be more complex than the cost
876 // of a function call. However, loops that don't use `continue` would still be
877 // viable candidates for inlining.
878 break;
John Stiles93442622020-09-11 12:11:27 -0400879 }
John Stiles70957c82020-10-02 16:42:10 -0400880 case Statement::Kind::kExpression: {
881 ExpressionStatement& expr = (*stmt)->as<ExpressionStatement>();
882 this->visitExpression(&expr.expression());
883 break;
884 }
885 case Statement::Kind::kFor: {
886 ForStatement& forStmt = (*stmt)->as<ForStatement>();
887 if (forStmt.fSymbols) {
888 fSymbolTableStack.push_back(forStmt.fSymbols.get());
889 }
890
891 // The initializer and loop body are candidates for inlining.
892 this->visitStatement(&forStmt.fInitializer,
893 /*isViableAsEnclosingStatement=*/false);
894 this->visitStatement(&forStmt.fStatement);
895
896 // The inliner isn't smart enough to inline the test- or increment-expressions
897 // of a for loop loop at this time. There are a handful of limitations:
898 // - We would need to insert the test-expression block at the very beginning of the
899 // for-loop's inner fStatement, and the increment-expression block at the very
900 // end. We don't support that today, but it's doable.
901 // - The for-loop's built-in test-expression would need to be dropped entirely,
902 // and the loop would be halted via a break statement at the end of the inlined
903 // test-expression. This is again something we don't support today, but it could
904 // be implemented.
905 // - We cannot inline the increment-expression if the loop uses `continue` anywhere;
906 // that would skip over the inlined block that evaluates the increment expression.
907 // There isn't a good fix for this--any workaround would be more complex than the
908 // cost of a function call. However, loops that don't use `continue` would still
909 // be viable candidates for increment-expression inlining.
910 break;
911 }
912 case Statement::Kind::kIf: {
913 IfStatement& ifStmt = (*stmt)->as<IfStatement>();
914 this->visitExpression(&ifStmt.fTest);
915 this->visitStatement(&ifStmt.fIfTrue);
916 this->visitStatement(&ifStmt.fIfFalse);
917 break;
918 }
919 case Statement::Kind::kReturn: {
920 ReturnStatement& returnStmt = (*stmt)->as<ReturnStatement>();
921 this->visitExpression(&returnStmt.fExpression);
922 break;
923 }
924 case Statement::Kind::kSwitch: {
925 SwitchStatement& switchStmt = (*stmt)->as<SwitchStatement>();
926 if (switchStmt.fSymbols) {
927 fSymbolTableStack.push_back(switchStmt.fSymbols.get());
928 }
929
930 this->visitExpression(&switchStmt.fValue);
931 for (std::unique_ptr<SwitchCase>& switchCase : switchStmt.fCases) {
932 // The switch-case's fValue cannot be a FunctionCall; skip it.
933 for (std::unique_ptr<Statement>& caseBlock : switchCase->fStatements) {
934 this->visitStatement(&caseBlock);
935 }
936 }
937 break;
938 }
939 case Statement::Kind::kVarDeclaration: {
940 VarDeclaration& varDeclStmt = (*stmt)->as<VarDeclaration>();
941 // Don't need to scan the declaration's sizes; those are always IntLiterals.
942 this->visitExpression(&varDeclStmt.fValue);
943 break;
944 }
945 case Statement::Kind::kVarDeclarations: {
946 VarDeclarationsStatement& varDecls = (*stmt)->as<VarDeclarationsStatement>();
947 for (std::unique_ptr<Statement>& varDecl : varDecls.fDeclaration->fVars) {
948 this->visitStatement(&varDecl, /*isViableAsEnclosingStatement=*/false);
949 }
950 break;
951 }
952 case Statement::Kind::kWhile: {
953 WhileStatement& whileStmt = (*stmt)->as<WhileStatement>();
954 // The loop body is a candidate for inlining.
955 this->visitStatement(&whileStmt.fStatement);
956 // The inliner isn't smart enough to inline the test-expression for a while loop at
957 // this time. There are two limitations:
958 // - We would need to insert the inlined-body block at the very beginning of the
959 // while loop's inner fStatement. We don't support that today, but it's doable.
960 // - The while-loop's built-in test-expression would need to be replaced with a
961 // `true` BoolLiteral, and the loop would be halted via a break statement at the
962 // end of the inlined test-expression. This is again something we don't support
963 // today, but it could be implemented.
964 break;
965 }
966 default:
967 SkUNREACHABLE;
John Stiles93442622020-09-11 12:11:27 -0400968 }
969
John Stiles70957c82020-10-02 16:42:10 -0400970 // Pop our symbol and enclosing-statement stacks.
971 fSymbolTableStack.resize(oldSymbolStackSize);
972 fEnclosingStmtStack.resize(oldEnclosingStmtStackSize);
973 }
974
975 void visitExpression(std::unique_ptr<Expression>* expr) {
976 if (!*expr) {
977 return;
John Stiles93442622020-09-11 12:11:27 -0400978 }
John Stiles70957c82020-10-02 16:42:10 -0400979
980 switch ((*expr)->kind()) {
981 case Expression::Kind::kBoolLiteral:
982 case Expression::Kind::kDefined:
983 case Expression::Kind::kExternalValue:
984 case Expression::Kind::kFieldAccess:
985 case Expression::Kind::kFloatLiteral:
986 case Expression::Kind::kFunctionReference:
987 case Expression::Kind::kIntLiteral:
988 case Expression::Kind::kNullLiteral:
989 case Expression::Kind::kSetting:
990 case Expression::Kind::kTypeReference:
991 case Expression::Kind::kVariableReference:
992 // Nothing to scan here.
993 break;
994
995 case Expression::Kind::kBinary: {
996 BinaryExpression& binaryExpr = (*expr)->as<BinaryExpression>();
997 this->visitExpression(&binaryExpr.leftPointer());
998
999 // Logical-and and logical-or binary expressions do not inline the right side,
1000 // because that would invalidate short-circuiting. That is, when evaluating
1001 // expressions like these:
1002 // (false && x()) // always false
1003 // (true || y()) // always true
1004 // It is illegal for side-effects from x() or y() to occur. The simplest way to
1005 // enforce that rule is to avoid inlining the right side entirely. However, it is
1006 // safe for other types of binary expression to inline both sides.
1007 Token::Kind op = binaryExpr.getOperator();
1008 bool shortCircuitable = (op == Token::Kind::TK_LOGICALAND ||
1009 op == Token::Kind::TK_LOGICALOR);
1010 if (!shortCircuitable) {
1011 this->visitExpression(&binaryExpr.rightPointer());
1012 }
1013 break;
1014 }
1015 case Expression::Kind::kConstructor: {
1016 Constructor& constructorExpr = (*expr)->as<Constructor>();
1017 for (std::unique_ptr<Expression>& arg : constructorExpr.arguments()) {
1018 this->visitExpression(&arg);
1019 }
1020 break;
1021 }
1022 case Expression::Kind::kExternalFunctionCall: {
1023 ExternalFunctionCall& funcCallExpr = (*expr)->as<ExternalFunctionCall>();
1024 for (std::unique_ptr<Expression>& arg : funcCallExpr.arguments()) {
1025 this->visitExpression(&arg);
1026 }
1027 break;
1028 }
1029 case Expression::Kind::kFunctionCall: {
1030 FunctionCall& funcCallExpr = (*expr)->as<FunctionCall>();
1031 for (std::unique_ptr<Expression>& arg : funcCallExpr.fArguments) {
1032 this->visitExpression(&arg);
1033 }
1034 this->addInlineCandidate(expr);
1035 break;
1036 }
1037 case Expression::Kind::kIndex:{
1038 IndexExpression& indexExpr = (*expr)->as<IndexExpression>();
1039 this->visitExpression(&indexExpr.fBase);
1040 this->visitExpression(&indexExpr.fIndex);
1041 break;
1042 }
1043 case Expression::Kind::kPostfix: {
1044 PostfixExpression& postfixExpr = (*expr)->as<PostfixExpression>();
1045 this->visitExpression(&postfixExpr.fOperand);
1046 break;
1047 }
1048 case Expression::Kind::kPrefix: {
1049 PrefixExpression& prefixExpr = (*expr)->as<PrefixExpression>();
1050 this->visitExpression(&prefixExpr.fOperand);
1051 break;
1052 }
1053 case Expression::Kind::kSwizzle: {
1054 Swizzle& swizzleExpr = (*expr)->as<Swizzle>();
1055 this->visitExpression(&swizzleExpr.fBase);
1056 break;
1057 }
1058 case Expression::Kind::kTernary: {
1059 TernaryExpression& ternaryExpr = (*expr)->as<TernaryExpression>();
1060 // The test expression is a candidate for inlining.
1061 this->visitExpression(&ternaryExpr.fTest);
1062 // The true- and false-expressions cannot be inlined, because we are only allowed to
1063 // evaluate one side.
1064 break;
1065 }
1066 default:
1067 SkUNREACHABLE;
1068 }
1069 }
1070
1071 void addInlineCandidate(std::unique_ptr<Expression>* candidate) {
1072 fCandidateList->fCandidates.push_back(
1073 InlineCandidate{fSymbolTableStack.back(),
1074 find_parent_statement(fEnclosingStmtStack),
1075 fEnclosingStmtStack.back(),
1076 candidate,
1077 fEnclosingFunction,
1078 /*isLargeFunction=*/false});
1079 }
John Stiles2d7973a2020-10-02 15:01:03 -04001080};
John Stiles93442622020-09-11 12:11:27 -04001081
John Stiles2d7973a2020-10-02 15:01:03 -04001082bool Inliner::candidateCanBeInlined(const InlineCandidate& candidate, InlinabilityCache* cache) {
1083 const FunctionDeclaration& funcDecl = (*candidate.fCandidateExpr)->as<FunctionCall>().fFunction;
John Stiles915a38c2020-09-14 09:38:13 -04001084
John Stiles2d7973a2020-10-02 15:01:03 -04001085 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
1086 if (wasInserted) {
1087 // Recursion is forbidden here to avoid an infinite death spiral of inlining.
1088 iter->second = this->isSafeToInline(funcDecl.fDefinition) &&
1089 !contains_recursive_call(funcDecl);
John Stiles93442622020-09-11 12:11:27 -04001090 }
1091
John Stiles2d7973a2020-10-02 15:01:03 -04001092 return iter->second;
1093}
1094
1095bool Inliner::isLargeFunction(const FunctionDefinition* functionDef) {
1096 return Analysis::NodeCountExceeds(*functionDef, fSettings->fInlineThreshold);
1097}
1098
1099bool Inliner::isLargeFunction(const InlineCandidate& candidate, LargeFunctionCache* cache) {
1100 const FunctionDeclaration& funcDecl = (*candidate.fCandidateExpr)->as<FunctionCall>().fFunction;
1101
1102 auto [iter, wasInserted] = cache->insert({&funcDecl, false});
1103 if (wasInserted) {
1104 iter->second = this->isLargeFunction(funcDecl.fDefinition);
1105 }
1106
1107 return iter->second;
1108}
1109
1110void Inliner::buildCandidateList(Program& program, InlineCandidateList* candidateList) {
1111 // This is structured much like a ProgramVisitor, but does not actually use ProgramVisitor.
1112 // The analyzer needs to keep track of the `unique_ptr<T>*` of statements and expressions so
1113 // that they can later be replaced, and ProgramVisitor does not provide this; it only provides a
1114 // `const T&`.
1115 InlineCandidateAnalyzer analyzer;
1116 analyzer.visit(program, candidateList);
1117
1118 // Remove candidates that are not safe to inline.
1119 std::vector<InlineCandidate>& candidates = candidateList->fCandidates;
1120 InlinabilityCache cache;
1121 candidates.erase(std::remove_if(candidates.begin(),
1122 candidates.end(),
1123 [&](const InlineCandidate& candidate) {
1124 return !this->candidateCanBeInlined(candidate, &cache);
1125 }),
1126 candidates.end());
1127
1128 // Determine whether each candidate function exceeds our inlining size threshold or not. These
1129 // can still be valid candidates if they are only called one time, so we don't remove them from
1130 // the candidate list, but they will not be inlined if they're called more than once.
1131 LargeFunctionCache largeFunctionCache;
1132 for (InlineCandidate& candidate : candidates) {
1133 candidate.fIsLargeFunction = this->isLargeFunction(candidate, &largeFunctionCache);
1134 }
1135}
1136
1137bool Inliner::analyze(Program& program) {
1138 InlineCandidateList candidateList;
1139 this->buildCandidateList(program, &candidateList);
1140
John Stiles915a38c2020-09-14 09:38:13 -04001141 // Inline the candidates where we've determined that it's safe to do so.
1142 std::unordered_set<const std::unique_ptr<Statement>*> enclosingStmtSet;
1143 bool madeChanges = false;
John Stiles2d7973a2020-10-02 15:01:03 -04001144 for (const InlineCandidate& candidate : candidateList.fCandidates) {
John Stiles915a38c2020-09-14 09:38:13 -04001145 FunctionCall& funcCall = (*candidate.fCandidateExpr)->as<FunctionCall>();
1146 const FunctionDeclaration* funcDecl = &funcCall.fFunction;
1147
John Stiles2d7973a2020-10-02 15:01:03 -04001148 // If the function is large, not marked `inline`, and is called more than once, it's a bad
1149 // idea to inline it.
1150 if (candidate.fIsLargeFunction &&
1151 !(funcDecl->fModifiers.fFlags & Modifiers::kInline_Flag) &&
1152 funcDecl->fCallCount.load() > 1) {
John Stiles915a38c2020-09-14 09:38:13 -04001153 continue;
1154 }
1155
1156 // Inlining two expressions using the same enclosing statement in the same inlining pass
1157 // does not work properly. If this happens, skip it; we'll get it in the next pass.
1158 auto [unusedIter, inserted] = enclosingStmtSet.insert(candidate.fEnclosingStmt);
1159 if (!inserted) {
1160 continue;
1161 }
1162
1163 // Convert the function call to its inlined equivalent.
Brian Osman3887a012020-09-30 13:22:27 -04001164 InlinedCall inlinedCall = this->inlineCall(&funcCall, candidate.fSymbols,
1165 &candidate.fEnclosingFunction->fDeclaration);
John Stiles915a38c2020-09-14 09:38:13 -04001166 if (inlinedCall.fInlinedBody) {
1167 // Ensure that the inlined body has a scope if it needs one.
John Stiles6d696082020-10-01 10:18:54 -04001168 this->ensureScopedBlocks(inlinedCall.fInlinedBody.get(), candidate.fParentStmt->get());
John Stiles915a38c2020-09-14 09:38:13 -04001169
1170 // Move the enclosing statement to the end of the unscoped Block containing the inlined
1171 // function, then replace the enclosing statement with that Block.
1172 // Before:
1173 // fInlinedBody = Block{ stmt1, stmt2, stmt3 }
1174 // fEnclosingStmt = stmt4
1175 // After:
1176 // fInlinedBody = null
1177 // fEnclosingStmt = Block{ stmt1, stmt2, stmt3, stmt4 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001178 inlinedCall.fInlinedBody->children().push_back(std::move(*candidate.fEnclosingStmt));
John Stiles915a38c2020-09-14 09:38:13 -04001179 *candidate.fEnclosingStmt = std::move(inlinedCall.fInlinedBody);
1180 }
1181
1182 // Replace the candidate function call with our replacement expression.
1183 *candidate.fCandidateExpr = std::move(inlinedCall.fReplacementExpr);
1184 madeChanges = true;
1185
1186 // Note that nothing was destroyed except for the FunctionCall. All other nodes should
1187 // remain valid.
1188 }
1189
1190 return madeChanges;
John Stiles93442622020-09-11 12:11:27 -04001191}
1192
John Stiles44e96be2020-08-31 13:16:04 -04001193} // namespace SkSL