blob: 20c9a0c6db30fb47fe72e5edb9e8bc190591eed3 [file] [log] [blame]
John Stilesdc8ec312021-01-11 11:05:21 -05001/*
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#ifndef SKSL_CONSTANT_FOLDER
9#define SKSL_CONSTANT_FOLDER
10
11#include <memory>
12
Ethan Nicholasc0f98152021-02-05 16:21:10 -050013#include "src/sksl/SkSLDefines.h"
John Stilesdc8ec312021-01-11 11:05:21 -050014#include "src/sksl/SkSLLexer.h"
15
16namespace SkSL {
17
18class Context;
19class ErrorReporter;
20class Expression;
21
22/**
23 * Performs constant folding on IR expressions. This simplifies expressions containing
24 * compile-time constants, such as replacing `IntLiteral(2) + IntLiteral(2)` with `IntLiteral(4)`.
25 */
26class ConstantFolder {
27public:
Ethan Nicholasc0f98152021-02-05 16:21:10 -050028 /**
29 * If value is an int literal or const int variable with a known value, returns true and stores
30 * the value in out. Otherwise returns false.
31 */
32 static bool GetConstantInt(const Expression& value, SKSL_INT* out);
33
34 /**
35 * If value is a float literal or const float variable with a known value, returns true and
36 * stores the value in out. Otherwise returns false.
37 */
38 static bool GetConstantFloat(const Expression& value, SKSL_FLOAT* out);
39
40 /**
41 * Reports an error and returns true if op is a division / mod operator and right is zero or
42 * contains a zero element.
43 */
44 static bool ErrorOnDivideByZero(const Context& context, int offset, Token::Kind op,
45 const Expression& right);
46
John Stilesdc8ec312021-01-11 11:05:21 -050047 /** Simplifies the binary expression `left OP right`. Returns null if it can't be simplified. */
48 static std::unique_ptr<Expression> Simplify(const Context& context,
Ethan Nicholasc0f98152021-02-05 16:21:10 -050049 int offset,
John Stilesdc8ec312021-01-11 11:05:21 -050050 const Expression& left,
51 Token::Kind op,
52 const Expression& right);
53};
54
55} // namespace SkSL
56
57#endif // SKSL_CONSTANT_FOLDER