blob: 465a8a0072191f886589cfe51e665f9cf9a52dac [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#include "src/sksl/SkSLConstantFolder.h"
9
10#include <limits>
11
12#include "src/sksl/SkSLContext.h"
13#include "src/sksl/SkSLErrorReporter.h"
14#include "src/sksl/ir/SkSLBinaryExpression.h"
15#include "src/sksl/ir/SkSLBoolLiteral.h"
16#include "src/sksl/ir/SkSLConstructor.h"
17#include "src/sksl/ir/SkSLExpression.h"
18#include "src/sksl/ir/SkSLFloatLiteral.h"
19#include "src/sksl/ir/SkSLIntLiteral.h"
20#include "src/sksl/ir/SkSLType.h"
21#include "src/sksl/ir/SkSLVariable.h"
22#include "src/sksl/ir/SkSLVariableReference.h"
23
24namespace SkSL {
25
26static std::unique_ptr<Expression> short_circuit_boolean(const Expression& left,
27 Token::Kind op,
28 const Expression& right) {
29 SkASSERT(left.is<BoolLiteral>());
30 bool leftVal = left.as<BoolLiteral>().value();
31
32 if (op == Token::Kind::TK_LOGICALAND) {
33 // (true && expr) -> (expr) and (false && expr) -> (false)
34 return leftVal ? right.clone()
35 : std::make_unique<BoolLiteral>(left.fOffset, /*value=*/false, &left.type());
36 }
37 if (op == Token::Kind::TK_LOGICALOR) {
38 // (true || expr) -> (true) and (false || expr) -> (expr)
39 return leftVal ? std::make_unique<BoolLiteral>(left.fOffset, /*value=*/true, &left.type())
40 : right.clone();
41 }
42 if (op == Token::Kind::TK_LOGICALXOR && !leftVal) {
43 // (false ^^ expr) -> (expr)
44 return right.clone();
45 }
46
47 return nullptr;
48}
49
50template <typename T>
51static std::unique_ptr<Expression> simplify_vector(const Context& context,
John Stilesdc8ec312021-01-11 11:05:21 -050052 const Expression& left,
53 Token::Kind op,
54 const Expression& right) {
John Stiles508eba72021-01-11 13:07:47 -050055 SkASSERT(left.type().isVector());
John Stilesdc8ec312021-01-11 11:05:21 -050056 SkASSERT(left.type() == right.type());
57 const Type& type = left.type();
58
59 // Handle boolean operations: == !=
60 if (op == Token::Kind::TK_EQEQ || op == Token::Kind::TK_NEQ) {
61 bool equality = (op == Token::Kind::TK_EQEQ);
62
63 switch (left.compareConstant(right)) {
64 case Expression::ComparisonResult::kNotEqual:
65 equality = !equality;
66 [[fallthrough]];
67
68 case Expression::ComparisonResult::kEqual:
69 return std::make_unique<BoolLiteral>(context, left.fOffset, equality);
70
71 case Expression::ComparisonResult::kUnknown:
72 return nullptr;
73 }
74 }
75
76 // Handle floating-point arithmetic: + - * /
77 const auto vectorComponentwiseFold = [&](auto foldFn) -> std::unique_ptr<Constructor> {
78 const Type& componentType = type.componentType();
79 ExpressionArray args;
80 args.reserve_back(type.columns());
81 for (int i = 0; i < type.columns(); i++) {
82 T value = foldFn(left.getVecComponent<T>(i), right.getVecComponent<T>(i));
83 args.push_back(std::make_unique<Literal<T>>(left.fOffset, value, &componentType));
84 }
85 return std::make_unique<Constructor>(left.fOffset, &type, std::move(args));
86 };
87
88 const auto isVectorDivisionByZero = [&]() -> bool {
89 for (int i = 0; i < type.columns(); i++) {
90 if (right.getVecComponent<T>(i) == 0) {
91 return true;
92 }
93 }
94 return false;
95 };
96
97 switch (op) {
98 case Token::Kind::TK_PLUS: return vectorComponentwiseFold([](T a, T b) { return a + b; });
99 case Token::Kind::TK_MINUS: return vectorComponentwiseFold([](T a, T b) { return a - b; });
100 case Token::Kind::TK_STAR: return vectorComponentwiseFold([](T a, T b) { return a * b; });
101 case Token::Kind::TK_SLASH: {
102 if (isVectorDivisionByZero()) {
John Stilesb30151e2021-01-11 16:13:08 -0500103 context.fErrors.error(right.fOffset, "division by zero");
John Stilesdc8ec312021-01-11 11:05:21 -0500104 return nullptr;
105 }
106 return vectorComponentwiseFold([](T a, T b) { return a / b; });
107 }
108 default:
109 return nullptr;
110 }
111}
112
John Stiles508eba72021-01-11 13:07:47 -0500113static Constructor splat_scalar(const Expression& scalar, const Type& type) {
114 SkASSERT(type.isVector());
115 SkASSERT(type.componentType() == scalar.type());
116
117 // Use a Constructor to splat the scalar expression across a vector.
118 ExpressionArray arg;
119 arg.push_back(scalar.clone());
120 return Constructor{scalar.fOffset, &type, std::move(arg)};
121}
122
John Stilesdc8ec312021-01-11 11:05:21 -0500123std::unique_ptr<Expression> ConstantFolder::Simplify(const Context& context,
John Stilesdc8ec312021-01-11 11:05:21 -0500124 const Expression& left,
125 Token::Kind op,
126 const Expression& right) {
127 // If the left side is a constant boolean literal, the right side does not need to be constant
128 // for short-circuit optimizations to allow the constant to be folded.
129 if (left.is<BoolLiteral>() && !right.isCompileTimeConstant()) {
130 return short_circuit_boolean(left, op, right);
131 }
132
133 if (right.is<BoolLiteral>() && !left.isCompileTimeConstant()) {
134 // There aren't side effects in SkSL within expressions, so (left OP right) is equivalent to
135 // (right OP left) for short-circuit optimizations
136 // TODO: (true || (a=b)) seems to disqualify the above statement. Test this.
137 return short_circuit_boolean(right, op, left);
138 }
139
140 // Other than the short-circuit cases above, constant folding requires both sides to be constant
141 if (!left.isCompileTimeConstant() || !right.isCompileTimeConstant()) {
142 return nullptr;
143 }
144
145 // Perform constant folding on pairs of Booleans.
146 if (left.is<BoolLiteral>() && right.is<BoolLiteral>()) {
147 bool leftVal = left.as<BoolLiteral>().value();
148 bool rightVal = right.as<BoolLiteral>().value();
149 bool result;
150 switch (op) {
151 case Token::Kind::TK_LOGICALAND: result = leftVal && rightVal; break;
152 case Token::Kind::TK_LOGICALOR: result = leftVal || rightVal; break;
153 case Token::Kind::TK_LOGICALXOR: result = leftVal ^ rightVal; break;
John Stiles26fdcbb2021-01-19 19:00:31 -0500154 case Token::Kind::TK_EQEQ: result = leftVal == rightVal; break;
155 case Token::Kind::TK_NEQ: result = leftVal != rightVal; break;
John Stilesdc8ec312021-01-11 11:05:21 -0500156 default: return nullptr;
157 }
158 return std::make_unique<BoolLiteral>(context, left.fOffset, result);
159 }
160
161 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
162 // precision to calculate the results and hope the result makes sense.
163 // TODO: detect and handle integer overflow properly.
164 #define RESULT(t, op) std::make_unique<t ## Literal>(context, left.fOffset, \
165 leftVal op rightVal)
166 #define URESULT(t, op) std::make_unique<t ## Literal>(context, left.fOffset, \
167 (uint64_t) leftVal op \
168 (uint64_t) rightVal)
169 if (left.is<IntLiteral>() && right.is<IntLiteral>()) {
170 SKSL_INT leftVal = left.as<IntLiteral>().value();
171 SKSL_INT rightVal = right.as<IntLiteral>().value();
172 switch (op) {
173 case Token::Kind::TK_PLUS: return URESULT(Int, +);
174 case Token::Kind::TK_MINUS: return URESULT(Int, -);
175 case Token::Kind::TK_STAR: return URESULT(Int, *);
176 case Token::Kind::TK_SLASH:
177 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
John Stilesb30151e2021-01-11 16:13:08 -0500178 context.fErrors.error(right.fOffset, "arithmetic overflow");
John Stilesdc8ec312021-01-11 11:05:21 -0500179 return nullptr;
180 }
181 if (!rightVal) {
John Stilesb30151e2021-01-11 16:13:08 -0500182 context.fErrors.error(right.fOffset, "division by zero");
John Stilesdc8ec312021-01-11 11:05:21 -0500183 return nullptr;
184 }
185 return RESULT(Int, /);
186 case Token::Kind::TK_PERCENT:
187 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
John Stilesb30151e2021-01-11 16:13:08 -0500188 context.fErrors.error(right.fOffset, "arithmetic overflow");
John Stilesdc8ec312021-01-11 11:05:21 -0500189 return nullptr;
190 }
191 if (!rightVal) {
John Stilesb30151e2021-01-11 16:13:08 -0500192 context.fErrors.error(right.fOffset, "division by zero");
John Stilesdc8ec312021-01-11 11:05:21 -0500193 return nullptr;
194 }
195 return RESULT(Int, %);
196 case Token::Kind::TK_BITWISEAND: return RESULT(Int, &);
197 case Token::Kind::TK_BITWISEOR: return RESULT(Int, |);
198 case Token::Kind::TK_BITWISEXOR: return RESULT(Int, ^);
199 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
200 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
201 case Token::Kind::TK_GT: return RESULT(Bool, >);
202 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
203 case Token::Kind::TK_LT: return RESULT(Bool, <);
204 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
205 case Token::Kind::TK_SHL:
206 if (rightVal >= 0 && rightVal <= 31) {
207 return RESULT(Int, <<);
208 }
John Stilesb30151e2021-01-11 16:13:08 -0500209 context.fErrors.error(right.fOffset, "shift value out of range");
John Stilesdc8ec312021-01-11 11:05:21 -0500210 return nullptr;
211 case Token::Kind::TK_SHR:
212 if (rightVal >= 0 && rightVal <= 31) {
213 return RESULT(Int, >>);
214 }
John Stilesb30151e2021-01-11 16:13:08 -0500215 context.fErrors.error(right.fOffset, "shift value out of range");
John Stilesdc8ec312021-01-11 11:05:21 -0500216 return nullptr;
217
218 default:
219 return nullptr;
220 }
221 }
222
223 // Perform constant folding on pairs of floating-point literals.
224 if (left.is<FloatLiteral>() && right.is<FloatLiteral>()) {
225 SKSL_FLOAT leftVal = left.as<FloatLiteral>().value();
226 SKSL_FLOAT rightVal = right.as<FloatLiteral>().value();
227 switch (op) {
228 case Token::Kind::TK_PLUS: return RESULT(Float, +);
229 case Token::Kind::TK_MINUS: return RESULT(Float, -);
230 case Token::Kind::TK_STAR: return RESULT(Float, *);
231 case Token::Kind::TK_SLASH:
232 if (rightVal) {
233 return RESULT(Float, /);
234 }
John Stilesb30151e2021-01-11 16:13:08 -0500235 context.fErrors.error(right.fOffset, "division by zero");
John Stilesdc8ec312021-01-11 11:05:21 -0500236 return nullptr;
237 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
238 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
239 case Token::Kind::TK_GT: return RESULT(Bool, >);
240 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
241 case Token::Kind::TK_LT: return RESULT(Bool, <);
242 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
243 default: return nullptr;
244 }
245 }
246
247 // Perform constant folding on pairs of vectors.
248 const Type& leftType = left.type();
249 const Type& rightType = right.type();
250 if (leftType.isVector() && leftType == rightType) {
251 if (leftType.componentType().isFloat()) {
John Stilesb30151e2021-01-11 16:13:08 -0500252 return simplify_vector<SKSL_FLOAT>(context, left, op, right);
John Stilesdc8ec312021-01-11 11:05:21 -0500253 }
254 if (leftType.componentType().isInteger()) {
John Stilesb30151e2021-01-11 16:13:08 -0500255 return simplify_vector<SKSL_INT>(context, left, op, right);
John Stilesdc8ec312021-01-11 11:05:21 -0500256 }
257 return nullptr;
258 }
259
John Stiles508eba72021-01-11 13:07:47 -0500260 // Perform constant folding on vectors against scalars, e.g.: half4(2) + 2
261 if (leftType.isVector() && leftType.componentType() == rightType) {
262 if (rightType.isFloat()) {
John Stilesb30151e2021-01-11 16:13:08 -0500263 return simplify_vector<SKSL_FLOAT>(context, left, op, splat_scalar(right, left.type()));
John Stiles508eba72021-01-11 13:07:47 -0500264 }
265 if (rightType.isInteger()) {
John Stilesb30151e2021-01-11 16:13:08 -0500266 return simplify_vector<SKSL_INT>(context, left, op, splat_scalar(right, left.type()));
John Stiles508eba72021-01-11 13:07:47 -0500267 }
268 return nullptr;
269 }
270
271 // Perform constant folding on scalars against vectors, e.g.: 2 + half4(2)
272 if (rightType.isVector() && rightType.componentType() == leftType) {
273 if (leftType.isFloat()) {
John Stilesb30151e2021-01-11 16:13:08 -0500274 return simplify_vector<SKSL_FLOAT>(context, splat_scalar(left, right.type()), op,
275 right);
John Stiles508eba72021-01-11 13:07:47 -0500276 }
277 if (leftType.isInteger()) {
John Stilesb30151e2021-01-11 16:13:08 -0500278 return simplify_vector<SKSL_INT>(context, splat_scalar(left, right.type()), op, right);
John Stiles508eba72021-01-11 13:07:47 -0500279 }
280 return nullptr;
281 }
282
John Stilesdc8ec312021-01-11 11:05:21 -0500283 // Perform constant folding on pairs of matrices.
284 if (leftType.isMatrix() && rightType.isMatrix()) {
285 bool equality;
286 switch (op) {
287 case Token::Kind::TK_EQEQ:
288 equality = true;
289 break;
290 case Token::Kind::TK_NEQ:
291 equality = false;
292 break;
293 default:
294 return nullptr;
295 }
296
297 switch (left.compareConstant(right)) {
298 case Expression::ComparisonResult::kNotEqual:
299 equality = !equality;
300 [[fallthrough]];
301
302 case Expression::ComparisonResult::kEqual:
303 return std::make_unique<BoolLiteral>(context, left.fOffset, equality);
304
305 case Expression::ComparisonResult::kUnknown:
306 return nullptr;
307 }
308 }
309
310 // We aren't able to constant-fold.
311 #undef RESULT
312 #undef URESULT
313 return nullptr;
314}
315
316} // namespace SkSL