1 /* 2 * Copyright 2020 Google LLC 3 * 4 * Use of this source code is governed by a BSD-style license that can be 5 * found in the LICENSE file. 6 */ 7 8 #ifndef SKSL_CONSTANT_FOLDER 9 #define SKSL_CONSTANT_FOLDER 10 11 #include <memory> 12 13 #include "include/private/SkSLDefines.h" 14 #include "include/sksl/SkSLOperator.h" 15 16 namespace SkSL { 17 18 class Context; 19 class Expression; 20 class Position; 21 class Type; 22 23 /** 24 * Performs constant folding on IR expressions. This simplifies expressions containing 25 * compile-time constants, such as replacing `Literal(2) + Literal(2)` with `Literal(4)`. 26 */ 27 class ConstantFolder { 28 public: 29 /** 30 * If value is an int literal or const int variable with a known value, returns true and stores 31 * the value in out. Otherwise returns false. 32 */ 33 static bool GetConstantInt(const Expression& value, SKSL_INT* out); 34 35 /** 36 * If value is a literal or const scalar variable with a known value, returns true and stores 37 * the value in out. Otherwise returns false. 38 */ 39 static bool GetConstantValue(const Expression& value, double* out); 40 41 /** 42 * If the expression is a const variable with a known compile-time-constant value, returns that 43 * value. If not, returns the original expression as-is. 44 */ 45 static const Expression* GetConstantValueForVariable(const Expression& value); 46 47 /** 48 * If the expression is a const variable with a known compile-time-constant value, returns that 49 * value. If not, returns null. 50 */ 51 static const Expression* GetConstantValueOrNullForVariable(const Expression& value); 52 53 /** 54 * If the expression is a const variable with a known compile-time-constant value, returns a 55 * clone of that value. If not, returns the original expression as-is. 56 */ 57 static std::unique_ptr<Expression> MakeConstantValueForVariable(Position pos, 58 std::unique_ptr<Expression> expr); 59 60 /** Simplifies the binary expression `left OP right`. Returns null if it can't be simplified. */ 61 static std::unique_ptr<Expression> Simplify(const Context& context, 62 Position pos, 63 const Expression& left, 64 Operator op, 65 const Expression& right, 66 const Type& resultType); 67 }; 68 69 } // namespace SkSL 70 71 #endif // SKSL_CONSTANT_FOLDER 72