blob: db184ea8fa01fe3c53770692edb21c43ba8e2a21 [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
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040012#include "include/sksl/SkSLErrorReporter.h"
John Stilesdc8ec312021-01-11 11:05:21 -050013#include "src/sksl/SkSLContext.h"
John Stilesdc8ec312021-01-11 11:05:21 -050014#include "src/sksl/ir/SkSLBinaryExpression.h"
John Stilesdc8ec312021-01-11 11:05:21 -050015#include "src/sksl/ir/SkSLConstructor.h"
John Stilesb0ce42d2021-04-09 10:39:42 -040016#include "src/sksl/ir/SkSLConstructorCompound.h"
John Stiles2938eea2021-04-01 18:58:25 -040017#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesdc8ec312021-01-11 11:05:21 -050018#include "src/sksl/ir/SkSLExpression.h"
John Stiles7591d4b2021-09-13 13:32:06 -040019#include "src/sksl/ir/SkSLLiteral.h"
John Stiles8f440b42021-03-05 16:48:56 -050020#include "src/sksl/ir/SkSLPrefixExpression.h"
John Stilesdc8ec312021-01-11 11:05:21 -050021#include "src/sksl/ir/SkSLType.h"
22#include "src/sksl/ir/SkSLVariable.h"
23#include "src/sksl/ir/SkSLVariableReference.h"
24
25namespace SkSL {
26
John Stiles8a9da732021-01-20 14:32:33 -050027static std::unique_ptr<Expression> eliminate_no_op_boolean(const Expression& left,
John Stiles45990502021-02-16 10:55:27 -050028 Operator op,
John Stiles8a9da732021-01-20 14:32:33 -050029 const Expression& right) {
John Stiles7591d4b2021-09-13 13:32:06 -040030 bool rightVal = right.as<Literal>().boolValue();
John Stiles8a9da732021-01-20 14:32:33 -050031
32 // Detect no-op Boolean expressions and optimize them away.
John Stiles45990502021-02-16 10:55:27 -050033 if ((op.kind() == Token::Kind::TK_LOGICALAND && rightVal) || // (expr && true) -> (expr)
34 (op.kind() == Token::Kind::TK_LOGICALOR && !rightVal) || // (expr || false) -> (expr)
35 (op.kind() == Token::Kind::TK_LOGICALXOR && !rightVal) || // (expr ^^ false) -> (expr)
36 (op.kind() == Token::Kind::TK_EQEQ && rightVal) || // (expr == true) -> (expr)
37 (op.kind() == Token::Kind::TK_NEQ && !rightVal)) { // (expr != false) -> (expr)
John Stiles8a9da732021-01-20 14:32:33 -050038
39 return left.clone();
40 }
41
42 return nullptr;
43}
44
John Stilesdc8ec312021-01-11 11:05:21 -050045static std::unique_ptr<Expression> short_circuit_boolean(const Expression& left,
John Stiles45990502021-02-16 10:55:27 -050046 Operator op,
John Stilesdc8ec312021-01-11 11:05:21 -050047 const Expression& right) {
John Stiles7591d4b2021-09-13 13:32:06 -040048 bool leftVal = left.as<Literal>().boolValue();
John Stilesdc8ec312021-01-11 11:05:21 -050049
John Stiles8a9da732021-01-20 14:32:33 -050050 // When the literal is on the left, we can sometimes eliminate the other expression entirely.
John Stiles45990502021-02-16 10:55:27 -050051 if ((op.kind() == Token::Kind::TK_LOGICALAND && !leftVal) || // (false && expr) -> (false)
52 (op.kind() == Token::Kind::TK_LOGICALOR && leftVal)) { // (true || expr) -> (true)
John Stiles8a9da732021-01-20 14:32:33 -050053
54 return left.clone();
John Stilesdc8ec312021-01-11 11:05:21 -050055 }
56
John Stiles8a9da732021-01-20 14:32:33 -050057 // We can't eliminate the right-side expression via short-circuit, but we might still be able to
58 // simplify away a no-op expression.
59 return eliminate_no_op_boolean(right, op, left);
John Stilesdc8ec312021-01-11 11:05:21 -050060}
61
John Stiles878d8fb2021-08-24 11:33:27 -040062static std::unique_ptr<Expression> simplify_vector_equality(const Context& context,
63 const Expression& left,
64 Operator op,
65 const Expression& right) {
66 if (op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ) {
67 bool equality = (op.kind() == Token::Kind::TK_EQEQ);
68
69 switch (left.compareConstant(right)) {
70 case Expression::ComparisonResult::kNotEqual:
71 equality = !equality;
72 [[fallthrough]];
73
74 case Expression::ComparisonResult::kEqual:
John Stiles7591d4b2021-09-13 13:32:06 -040075 return Literal::MakeBool(context, left.fOffset, equality);
John Stiles878d8fb2021-08-24 11:33:27 -040076
77 case Expression::ComparisonResult::kUnknown:
78 break;
79 }
80 }
81 return nullptr;
82}
83
John Stilesdc8ec312021-01-11 11:05:21 -050084static std::unique_ptr<Expression> simplify_vector(const Context& context,
John Stilesdc8ec312021-01-11 11:05:21 -050085 const Expression& left,
John Stiles45990502021-02-16 10:55:27 -050086 Operator op,
John Stilesdc8ec312021-01-11 11:05:21 -050087 const Expression& right) {
John Stiles508eba72021-01-11 13:07:47 -050088 SkASSERT(left.type().isVector());
John Stilesdc8ec312021-01-11 11:05:21 -050089 SkASSERT(left.type() == right.type());
90 const Type& type = left.type();
91
John Stiles878d8fb2021-08-24 11:33:27 -040092 // Handle equality operations: == !=
93 if (std::unique_ptr<Expression> result = simplify_vector_equality(context, left, op, right)) {
94 return result;
John Stilesdc8ec312021-01-11 11:05:21 -050095 }
96
97 // Handle floating-point arithmetic: + - * /
John Stiles7591d4b2021-09-13 13:32:06 -040098 using FoldFn = double (*)(double, double);
99 FoldFn foldFn;
John Stiles45990502021-02-16 10:55:27 -0500100 switch (op.kind()) {
John Stiles7591d4b2021-09-13 13:32:06 -0400101 case Token::Kind::TK_PLUS: foldFn = +[](double a, double b) { return a + b; }; break;
102 case Token::Kind::TK_MINUS: foldFn = +[](double a, double b) { return a - b; }; break;
103 case Token::Kind::TK_STAR: foldFn = +[](double a, double b) { return a * b; }; break;
104 case Token::Kind::TK_SLASH: foldFn = +[](double a, double b) { return a / b; }; break;
John Stilesdc8ec312021-01-11 11:05:21 -0500105 default:
106 return nullptr;
107 }
John Stiles7591d4b2021-09-13 13:32:06 -0400108
109 const Type& componentType = type.componentType();
110 ExpressionArray args;
111 args.reserve_back(type.columns());
112 for (int i = 0; i < type.columns(); i++) {
113 double value = foldFn(left.getConstantSubexpression(i)->as<Literal>().value(),
114 right.getConstantSubexpression(i)->as<Literal>().value());
115 args.push_back(Literal::Make(left.fOffset, value, &componentType));
116 }
117 return ConstructorCompound::Make(context, left.fOffset, type, std::move(args));
John Stilesdc8ec312021-01-11 11:05:21 -0500118}
119
John Stiles8f440b42021-03-05 16:48:56 -0500120static std::unique_ptr<Expression> cast_expression(const Context& context,
121 const Expression& expr,
122 const Type& type) {
123 ExpressionArray ctorArgs;
124 ctorArgs.push_back(expr.clone());
125 std::unique_ptr<Expression> ctor = Constructor::Convert(context, expr.fOffset, type,
126 std::move(ctorArgs));
127 SkASSERT(ctor);
128 return ctor;
129}
130
John Stiles2938eea2021-04-01 18:58:25 -0400131static ConstructorSplat splat_scalar(const Expression& scalar, const Type& type) {
John Stiles508eba72021-01-11 13:07:47 -0500132 SkASSERT(type.isVector());
133 SkASSERT(type.componentType() == scalar.type());
134
John Stiles2938eea2021-04-01 18:58:25 -0400135 // Use a constructor to splat the scalar expression across a vector.
136 return ConstructorSplat{scalar.fOffset, type, scalar.clone()};
John Stiles508eba72021-01-11 13:07:47 -0500137}
138
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500139bool ConstantFolder::GetConstantInt(const Expression& value, SKSL_INT* out) {
John Stilese80e1692021-03-02 17:02:25 -0500140 const Expression* expr = GetConstantValueForVariable(value);
John Stiles7591d4b2021-09-13 13:32:06 -0400141 if (!expr->isIntLiteral()) {
John Stilese80e1692021-03-02 17:02:25 -0500142 return false;
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500143 }
John Stiles7591d4b2021-09-13 13:32:06 -0400144 *out = expr->as<Literal>().intValue();
John Stilese80e1692021-03-02 17:02:25 -0500145 return true;
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500146}
147
John Stiles7591d4b2021-09-13 13:32:06 -0400148static bool is_constant_scalar_value(const Expression& inExpr, double match) {
John Stiles8f440b42021-03-05 16:48:56 -0500149 const Expression* expr = ConstantFolder::GetConstantValueForVariable(inExpr);
John Stiles7591d4b2021-09-13 13:32:06 -0400150 return (expr->is<Literal>() && expr->as<Literal>().value() == match);
John Stiles8f440b42021-03-05 16:48:56 -0500151}
152
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500153static bool contains_constant_zero(const Expression& expr) {
John Stiles55dc5c82021-08-19 18:15:49 -0400154 int numSlots = expr.type().slotCount();
155 for (int index = 0; index < numSlots; ++index) {
156 const Expression* subexpr = expr.getConstantSubexpression(index);
John Stiles7591d4b2021-09-13 13:32:06 -0400157 if (subexpr && is_constant_scalar_value(*subexpr, 0.0)) {
John Stiles55dc5c82021-08-19 18:15:49 -0400158 return true;
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500159 }
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500160 }
John Stiles55dc5c82021-08-19 18:15:49 -0400161 return false;
John Stiles8f440b42021-03-05 16:48:56 -0500162}
163
John Stiles7591d4b2021-09-13 13:32:06 -0400164static bool is_constant_value(const Expression& expr, double value) {
John Stiles55dc5c82021-08-19 18:15:49 -0400165 int numSlots = expr.type().slotCount();
166 for (int index = 0; index < numSlots; ++index) {
167 const Expression* subexpr = expr.getConstantSubexpression(index);
168 if (!subexpr || !is_constant_scalar_value(*subexpr, value)) {
169 return false;
John Stiles8f440b42021-03-05 16:48:56 -0500170 }
John Stiles8f440b42021-03-05 16:48:56 -0500171 }
John Stiles55dc5c82021-08-19 18:15:49 -0400172 return true;
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500173}
174
John Stiles45990502021-02-16 10:55:27 -0500175bool ConstantFolder::ErrorOnDivideByZero(const Context& context, int offset, Operator op,
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500176 const Expression& right) {
John Stiles45990502021-02-16 10:55:27 -0500177 switch (op.kind()) {
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500178 case Token::Kind::TK_SLASH:
179 case Token::Kind::TK_SLASHEQ:
180 case Token::Kind::TK_PERCENT:
181 case Token::Kind::TK_PERCENTEQ:
182 if (contains_constant_zero(right)) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400183 context.fErrors->error(offset, "division by zero");
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500184 return true;
185 }
186 return false;
187 default:
188 return false;
189 }
190}
191
John Stilese80e1692021-03-02 17:02:25 -0500192const Expression* ConstantFolder::GetConstantValueForVariable(const Expression& inExpr) {
193 for (const Expression* expr = &inExpr;;) {
194 if (!expr->is<VariableReference>()) {
195 break;
196 }
197 const VariableReference& varRef = expr->as<VariableReference>();
198 if (varRef.refKind() != VariableRefKind::kRead) {
199 break;
200 }
201 const Variable& var = *varRef.variable();
202 if (!(var.modifiers().fFlags & Modifiers::kConst_Flag)) {
203 break;
204 }
205 expr = var.initialValue();
John Stilesca65f8f2021-03-29 17:14:39 -0400206 if (!expr) {
John Stiles3f373222021-08-23 13:52:17 -0400207 // Function parameters can be const but won't have an initial value.
John Stilesca65f8f2021-03-29 17:14:39 -0400208 break;
209 }
John Stilese80e1692021-03-02 17:02:25 -0500210 if (expr->isCompileTimeConstant()) {
211 return expr;
212 }
John Stilese80e1692021-03-02 17:02:25 -0500213 }
214 // We didn't find a compile-time constant at the end. Return the expression as-is.
215 return &inExpr;
216}
217
John Stilesffba5242021-05-07 10:50:22 -0400218std::unique_ptr<Expression> ConstantFolder::MakeConstantValueForVariable(
219 std::unique_ptr<Expression> expr) {
220 const Expression* constantExpr = GetConstantValueForVariable(*expr);
221 if (constantExpr != expr.get()) {
222 expr = constantExpr->clone();
223 }
224 return expr;
225}
226
John Stiles8f440b42021-03-05 16:48:56 -0500227static std::unique_ptr<Expression> simplify_no_op_arithmetic(const Context& context,
228 const Expression& left,
229 Operator op,
230 const Expression& right,
231 const Type& resultType) {
232 switch (op.kind()) {
233 case Token::Kind::TK_PLUS:
234 if (is_constant_value(right, 0.0)) { // x + 0
235 return cast_expression(context, left, resultType);
236 }
237 if (is_constant_value(left, 0.0)) { // 0 + x
238 return cast_expression(context, right, resultType);
239 }
240 break;
241
242 case Token::Kind::TK_STAR:
243 if (is_constant_value(right, 1.0)) { // x * 1
244 return cast_expression(context, left, resultType);
245 }
246 if (is_constant_value(left, 1.0)) { // 1 * x
247 return cast_expression(context, right, resultType);
248 }
249 if (is_constant_value(right, 0.0) && !left.hasSideEffects()) { // x * 0
250 return cast_expression(context, right, resultType);
251 }
252 if (is_constant_value(left, 0.0) && !right.hasSideEffects()) { // 0 * x
253 return cast_expression(context, left, resultType);
254 }
255 break;
256
257 case Token::Kind::TK_MINUS:
258 if (is_constant_value(right, 0.0)) { // x - 0
259 return cast_expression(context, left, resultType);
260 }
261 if (is_constant_value(left, 0.0)) { // 0 - x (to `-x`)
262 return PrefixExpression::Make(context, Token::Kind::TK_MINUS,
263 cast_expression(context, right, resultType));
264 }
265 break;
266
267 case Token::Kind::TK_SLASH:
268 if (is_constant_value(right, 1.0)) { // x / 1
269 return cast_expression(context, left, resultType);
270 }
John Stiles8f440b42021-03-05 16:48:56 -0500271 break;
272
273 case Token::Kind::TK_PLUSEQ:
274 case Token::Kind::TK_MINUSEQ:
275 if (is_constant_value(right, 0.0)) { // x += 0, x -= 0
276 std::unique_ptr<Expression> result = cast_expression(context, left, resultType);
John Stilesbb8cf582021-08-26 23:34:59 -0400277 Analysis::UpdateVariableRefKind(result.get(), VariableRefKind::kRead);
John Stiles8f440b42021-03-05 16:48:56 -0500278 return result;
279 }
280 break;
281
282 case Token::Kind::TK_STAREQ:
283 case Token::Kind::TK_SLASHEQ:
284 if (is_constant_value(right, 1.0)) { // x *= 1, x /= 1
285 std::unique_ptr<Expression> result = cast_expression(context, left, resultType);
John Stilesbb8cf582021-08-26 23:34:59 -0400286 Analysis::UpdateVariableRefKind(result.get(), VariableRefKind::kRead);
John Stiles8f440b42021-03-05 16:48:56 -0500287 return result;
288 }
289 break;
290
291 default:
292 break;
293 }
294
295 return nullptr;
296}
297
John Stilesafaddc92021-05-26 22:21:42 -0400298template <typename T>
299static std::unique_ptr<Expression> fold_float_expression(int offset,
300 T result,
301 const Type* resultType) {
302 // If constant-folding this expression would generate a NaN/infinite result, leave it as-is.
John Stiles35981292021-05-27 12:26:37 -0400303 if constexpr (!std::is_same<T, bool>::value) {
John Stilesafaddc92021-05-26 22:21:42 -0400304 if (!std::isfinite(result)) {
305 return nullptr;
306 }
307 }
308
John Stiles7591d4b2021-09-13 13:32:06 -0400309 return Literal::Make(offset, result, resultType);
John Stilesafaddc92021-05-26 22:21:42 -0400310}
311
John Stiles35981292021-05-27 12:26:37 -0400312template <typename T>
313static std::unique_ptr<Expression> fold_int_expression(int offset,
314 T result,
315 const Type* resultType) {
316 // If constant-folding this expression would overflow the result type, leave it as-is.
317 if constexpr (!std::is_same<T, bool>::value) {
318 if (result < resultType->minimumValue() || result > resultType->maximumValue()) {
319 return nullptr;
320 }
321 }
322
John Stiles7591d4b2021-09-13 13:32:06 -0400323 return Literal::Make(offset, result, resultType);
John Stiles35981292021-05-27 12:26:37 -0400324}
325
John Stilesdc8ec312021-01-11 11:05:21 -0500326std::unique_ptr<Expression> ConstantFolder::Simplify(const Context& context,
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500327 int offset,
John Stilese80e1692021-03-02 17:02:25 -0500328 const Expression& leftExpr,
John Stiles45990502021-02-16 10:55:27 -0500329 Operator op,
John Stiles8f440b42021-03-05 16:48:56 -0500330 const Expression& rightExpr,
331 const Type& resultType) {
John Stilesbe6cbf32021-03-09 20:15:17 -0500332 // When optimization is enabled, replace constant variables with trivial initial-values.
333 const Expression* left;
334 const Expression* right;
335 if (context.fConfig->fSettings.fOptimize) {
336 left = GetConstantValueForVariable(leftExpr);
337 right = GetConstantValueForVariable(rightExpr);
338 } else {
339 left = &leftExpr;
340 right = &rightExpr;
341 }
John Stilese80e1692021-03-02 17:02:25 -0500342
John Stilesabc3b782021-02-05 10:07:19 -0500343 // If this is the comma operator, the left side is evaluated but not otherwise used in any way.
344 // So if the left side has no side effects, it can just be eliminated entirely.
John Stilese80e1692021-03-02 17:02:25 -0500345 if (op.kind() == Token::Kind::TK_COMMA && !left->hasSideEffects()) {
346 return right->clone();
John Stilesabc3b782021-02-05 10:07:19 -0500347 }
348
John Stiles95d0bad2021-03-01 17:02:28 -0500349 // If this is the assignment operator, and both sides are the same trivial expression, this is
350 // self-assignment (i.e., `var = var`) and can be reduced to just a variable reference (`var`).
351 // This can happen when other parts of the assignment are optimized away.
John Stiles5676c572021-03-08 17:10:52 -0500352 if (op.kind() == Token::Kind::TK_EQ && Analysis::IsSameExpressionTree(*left, *right)) {
John Stilese80e1692021-03-02 17:02:25 -0500353 return right->clone();
John Stiles95d0bad2021-03-01 17:02:28 -0500354 }
355
John Stiles8a9da732021-01-20 14:32:33 -0500356 // Simplify the expression when both sides are constant Boolean literals.
John Stiles7591d4b2021-09-13 13:32:06 -0400357 if (left->isBoolLiteral() && right->isBoolLiteral()) {
358 bool leftVal = left->as<Literal>().boolValue();
359 bool rightVal = right->as<Literal>().boolValue();
John Stilesdc8ec312021-01-11 11:05:21 -0500360 bool result;
John Stiles45990502021-02-16 10:55:27 -0500361 switch (op.kind()) {
John Stilesdc8ec312021-01-11 11:05:21 -0500362 case Token::Kind::TK_LOGICALAND: result = leftVal && rightVal; break;
363 case Token::Kind::TK_LOGICALOR: result = leftVal || rightVal; break;
364 case Token::Kind::TK_LOGICALXOR: result = leftVal ^ rightVal; break;
John Stiles26fdcbb2021-01-19 19:00:31 -0500365 case Token::Kind::TK_EQEQ: result = leftVal == rightVal; break;
366 case Token::Kind::TK_NEQ: result = leftVal != rightVal; break;
John Stilesdc8ec312021-01-11 11:05:21 -0500367 default: return nullptr;
368 }
John Stiles7591d4b2021-09-13 13:32:06 -0400369 return Literal::MakeBool(context, offset, result);
John Stilesdc8ec312021-01-11 11:05:21 -0500370 }
371
John Stiles8a9da732021-01-20 14:32:33 -0500372 // If the left side is a Boolean literal, apply short-circuit optimizations.
John Stiles7591d4b2021-09-13 13:32:06 -0400373 if (left->isBoolLiteral()) {
John Stilese80e1692021-03-02 17:02:25 -0500374 return short_circuit_boolean(*left, op, *right);
John Stiles8a9da732021-01-20 14:32:33 -0500375 }
376
377 // If the right side is a Boolean literal...
John Stiles7591d4b2021-09-13 13:32:06 -0400378 if (right->isBoolLiteral()) {
John Stiles8a9da732021-01-20 14:32:33 -0500379 // ... and the left side has no side effects...
John Stilese80e1692021-03-02 17:02:25 -0500380 if (!left->hasSideEffects()) {
John Stiles8a9da732021-01-20 14:32:33 -0500381 // We can reverse the expressions and short-circuit optimizations are still valid.
John Stilese80e1692021-03-02 17:02:25 -0500382 return short_circuit_boolean(*right, op, *left);
John Stiles8a9da732021-01-20 14:32:33 -0500383 }
384
385 // We can't use short-circuiting, but we can still optimize away no-op Boolean expressions.
John Stilese80e1692021-03-02 17:02:25 -0500386 return eliminate_no_op_boolean(*left, op, *right);
John Stiles8a9da732021-01-20 14:32:33 -0500387 }
388
John Stiles5676c572021-03-08 17:10:52 -0500389 if (op.kind() == Token::Kind::TK_EQEQ && Analysis::IsSameExpressionTree(*left, *right)) {
390 // With == comparison, if both sides are the same trivial expression, this is self-
391 // comparison and is always true. (We are not concerned with NaN.)
John Stiles7591d4b2021-09-13 13:32:06 -0400392 return Literal::MakeBool(context, leftExpr.fOffset, /*value=*/true);
John Stiles5676c572021-03-08 17:10:52 -0500393 }
394
395 if (op.kind() == Token::Kind::TK_NEQ && Analysis::IsSameExpressionTree(*left, *right)) {
396 // With != comparison, if both sides are the same trivial expression, this is self-
397 // comparison and is always false. (We are not concerned with NaN.)
John Stiles7591d4b2021-09-13 13:32:06 -0400398 return Literal::MakeBool(context, leftExpr.fOffset, /*value=*/false);
John Stiles5676c572021-03-08 17:10:52 -0500399 }
400
John Stilese80e1692021-03-02 17:02:25 -0500401 if (ErrorOnDivideByZero(context, offset, op, *right)) {
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500402 return nullptr;
403 }
404
John Stiles8f440b42021-03-05 16:48:56 -0500405 // Optimize away no-op arithmetic like `x * 1`, `x *= 1`, `x + 0`, `x * 0`, `0 / x`, etc.
406 const Type& leftType = left->type();
407 const Type& rightType = right->type();
408 if ((leftType.isScalar() || leftType.isVector()) &&
409 (rightType.isScalar() || rightType.isVector())) {
410 std::unique_ptr<Expression> expr = simplify_no_op_arithmetic(context, *left, op, *right,
411 resultType);
412 if (expr) {
413 return expr;
414 }
415 }
416
417 // Other than the cases above, constant folding requires both sides to be constant.
John Stilese80e1692021-03-02 17:02:25 -0500418 if (!left->isCompileTimeConstant() || !right->isCompileTimeConstant()) {
John Stiles8a9da732021-01-20 14:32:33 -0500419 return nullptr;
420 }
421
John Stilesdc8ec312021-01-11 11:05:21 -0500422 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
423 // precision to calculate the results and hope the result makes sense.
John Stiles9ce80f72021-03-11 22:35:19 -0500424 // TODO(skia:10932): detect and handle integer overflow properly.
Brian Osman21d2b6a2021-02-01 13:48:50 -0500425 using SKSL_UINT = uint64_t;
John Stiles7591d4b2021-09-13 13:32:06 -0400426 if (left->isIntLiteral() && right->isIntLiteral()) {
427 SKSL_INT leftVal = left->as<Literal>().intValue();
428 SKSL_INT rightVal = right->as<Literal>().intValue();
John Stiles35981292021-05-27 12:26:37 -0400429
430 #define RESULT(Op) fold_int_expression(offset, \
431 (SKSL_INT)(leftVal) Op (SKSL_INT)(rightVal), &resultType)
432 #define URESULT(Op) fold_int_expression(offset, \
433 (SKSL_INT)((SKSL_UINT)(leftVal) Op (SKSL_UINT)(rightVal)), &resultType)
John Stiles45990502021-02-16 10:55:27 -0500434 switch (op.kind()) {
John Stiles35981292021-05-27 12:26:37 -0400435 case Token::Kind::TK_PLUS: return URESULT(+);
436 case Token::Kind::TK_MINUS: return URESULT(-);
437 case Token::Kind::TK_STAR: return URESULT(*);
John Stilesdc8ec312021-01-11 11:05:21 -0500438 case Token::Kind::TK_SLASH:
439 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400440 context.fErrors->error(offset, "arithmetic overflow");
John Stilesdc8ec312021-01-11 11:05:21 -0500441 return nullptr;
442 }
John Stiles35981292021-05-27 12:26:37 -0400443 return RESULT(/);
John Stilesdc8ec312021-01-11 11:05:21 -0500444 case Token::Kind::TK_PERCENT:
445 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400446 context.fErrors->error(offset, "arithmetic overflow");
John Stilesdc8ec312021-01-11 11:05:21 -0500447 return nullptr;
448 }
John Stiles35981292021-05-27 12:26:37 -0400449 return RESULT(%);
450 case Token::Kind::TK_BITWISEAND: return RESULT(&);
451 case Token::Kind::TK_BITWISEOR: return RESULT(|);
452 case Token::Kind::TK_BITWISEXOR: return RESULT(^);
453 case Token::Kind::TK_EQEQ: return RESULT(==);
454 case Token::Kind::TK_NEQ: return RESULT(!=);
455 case Token::Kind::TK_GT: return RESULT(>);
456 case Token::Kind::TK_GTEQ: return RESULT(>=);
457 case Token::Kind::TK_LT: return RESULT(<);
458 case Token::Kind::TK_LTEQ: return RESULT(<=);
John Stilesdc8ec312021-01-11 11:05:21 -0500459 case Token::Kind::TK_SHL:
460 if (rightVal >= 0 && rightVal <= 31) {
Brian Osmana7eb6812021-02-01 11:43:05 -0500461 // Left-shifting a negative (or really, any signed) value is undefined behavior
462 // in C++, but not GLSL. Do the shift on unsigned values, to avoid UBSAN.
John Stiles35981292021-05-27 12:26:37 -0400463 return URESULT(<<);
John Stilesdc8ec312021-01-11 11:05:21 -0500464 }
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400465 context.fErrors->error(offset, "shift value out of range");
John Stilesdc8ec312021-01-11 11:05:21 -0500466 return nullptr;
467 case Token::Kind::TK_SHR:
468 if (rightVal >= 0 && rightVal <= 31) {
John Stiles35981292021-05-27 12:26:37 -0400469 return RESULT(>>);
John Stilesdc8ec312021-01-11 11:05:21 -0500470 }
Ethan Nicholas39f6da42021-08-23 13:10:07 -0400471 context.fErrors->error(offset, "shift value out of range");
John Stilesdc8ec312021-01-11 11:05:21 -0500472 return nullptr;
473
474 default:
475 return nullptr;
476 }
John Stilesafaddc92021-05-26 22:21:42 -0400477 #undef RESULT
478 #undef URESULT
John Stilesdc8ec312021-01-11 11:05:21 -0500479 }
480
481 // Perform constant folding on pairs of floating-point literals.
John Stiles7591d4b2021-09-13 13:32:06 -0400482 if (left->isFloatLiteral() && right->isFloatLiteral()) {
483 SKSL_FLOAT leftVal = left->as<Literal>().floatValue();
484 SKSL_FLOAT rightVal = right->as<Literal>().floatValue();
John Stilesafaddc92021-05-26 22:21:42 -0400485
486 #define RESULT(Op) fold_float_expression(offset, leftVal Op rightVal, &resultType)
John Stiles45990502021-02-16 10:55:27 -0500487 switch (op.kind()) {
John Stilesafaddc92021-05-26 22:21:42 -0400488 case Token::Kind::TK_PLUS: return RESULT(+);
489 case Token::Kind::TK_MINUS: return RESULT(-);
490 case Token::Kind::TK_STAR: return RESULT(*);
491 case Token::Kind::TK_SLASH: return RESULT(/);
492 case Token::Kind::TK_EQEQ: return RESULT(==);
493 case Token::Kind::TK_NEQ: return RESULT(!=);
494 case Token::Kind::TK_GT: return RESULT(>);
495 case Token::Kind::TK_GTEQ: return RESULT(>=);
496 case Token::Kind::TK_LT: return RESULT(<);
497 case Token::Kind::TK_LTEQ: return RESULT(<=);
498 default: return nullptr;
John Stilesdc8ec312021-01-11 11:05:21 -0500499 }
John Stilesafaddc92021-05-26 22:21:42 -0400500 #undef RESULT
John Stilesdc8ec312021-01-11 11:05:21 -0500501 }
502
503 // Perform constant folding on pairs of vectors.
John Stilesdc8ec312021-01-11 11:05:21 -0500504 if (leftType.isVector() && leftType == rightType) {
505 if (leftType.componentType().isFloat()) {
John Stiles7591d4b2021-09-13 13:32:06 -0400506 return simplify_vector(context, *left, op, *right);
John Stilesdc8ec312021-01-11 11:05:21 -0500507 }
508 if (leftType.componentType().isInteger()) {
John Stiles7591d4b2021-09-13 13:32:06 -0400509 return simplify_vector(context, *left, op, *right);
John Stilesdc8ec312021-01-11 11:05:21 -0500510 }
John Stiles878d8fb2021-08-24 11:33:27 -0400511 if (leftType.componentType().isBoolean()) {
512 return simplify_vector_equality(context, *left, op, *right);
513 }
John Stilesdc8ec312021-01-11 11:05:21 -0500514 return nullptr;
515 }
516
John Stiles508eba72021-01-11 13:07:47 -0500517 // Perform constant folding on vectors against scalars, e.g.: half4(2) + 2
518 if (leftType.isVector() && leftType.componentType() == rightType) {
519 if (rightType.isFloat()) {
John Stiles7591d4b2021-09-13 13:32:06 -0400520 return simplify_vector(context, *left, op, splat_scalar(*right, left->type()));
John Stiles508eba72021-01-11 13:07:47 -0500521 }
522 if (rightType.isInteger()) {
John Stiles7591d4b2021-09-13 13:32:06 -0400523 return simplify_vector(context, *left, op, splat_scalar(*right, left->type()));
John Stiles508eba72021-01-11 13:07:47 -0500524 }
John Stiles878d8fb2021-08-24 11:33:27 -0400525 if (rightType.isBoolean()) {
526 return simplify_vector_equality(context, *left, op,
527 splat_scalar(*right, left->type()));
528 }
John Stiles508eba72021-01-11 13:07:47 -0500529 return nullptr;
530 }
531
532 // Perform constant folding on scalars against vectors, e.g.: 2 + half4(2)
533 if (rightType.isVector() && rightType.componentType() == leftType) {
534 if (leftType.isFloat()) {
John Stiles7591d4b2021-09-13 13:32:06 -0400535 return simplify_vector(context, splat_scalar(*left, right->type()), op, *right);
John Stiles508eba72021-01-11 13:07:47 -0500536 }
537 if (leftType.isInteger()) {
John Stiles7591d4b2021-09-13 13:32:06 -0400538 return simplify_vector(context, splat_scalar(*left, right->type()), op, *right);
John Stiles508eba72021-01-11 13:07:47 -0500539 }
John Stiles878d8fb2021-08-24 11:33:27 -0400540 if (leftType.isBoolean()) {
541 return simplify_vector_equality(context, splat_scalar(*left, right->type()),
542 op, *right);
543 }
John Stiles508eba72021-01-11 13:07:47 -0500544 return nullptr;
545 }
546
John Stiles22a54542021-03-31 11:33:48 -0400547 // Perform constant folding on pairs of matrices or arrays.
548 if ((leftType.isMatrix() && rightType.isMatrix()) ||
549 (leftType.isArray() && rightType.isArray())) {
John Stilesdc8ec312021-01-11 11:05:21 -0500550 bool equality;
John Stiles45990502021-02-16 10:55:27 -0500551 switch (op.kind()) {
John Stilesdc8ec312021-01-11 11:05:21 -0500552 case Token::Kind::TK_EQEQ:
553 equality = true;
554 break;
555 case Token::Kind::TK_NEQ:
556 equality = false;
557 break;
558 default:
559 return nullptr;
560 }
561
John Stilese80e1692021-03-02 17:02:25 -0500562 switch (left->compareConstant(*right)) {
John Stilesdc8ec312021-01-11 11:05:21 -0500563 case Expression::ComparisonResult::kNotEqual:
564 equality = !equality;
565 [[fallthrough]];
566
567 case Expression::ComparisonResult::kEqual:
John Stiles7591d4b2021-09-13 13:32:06 -0400568 return Literal::MakeBool(context, offset, equality);
John Stilesdc8ec312021-01-11 11:05:21 -0500569
570 case Expression::ComparisonResult::kUnknown:
571 return nullptr;
572 }
573 }
574
575 // We aren't able to constant-fold.
John Stilesdc8ec312021-01-11 11:05:21 -0500576 return nullptr;
577}
578
579} // namespace SkSL