• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "src/sksl/SkSLConstantFolder.h"
9 
10 #include <limits>
11 
12 #include "include/sksl/SkSLErrorReporter.h"
13 #include "src/sksl/SkSLAnalysis.h"
14 #include "src/sksl/SkSLContext.h"
15 #include "src/sksl/SkSLProgramSettings.h"
16 #include "src/sksl/ir/SkSLBinaryExpression.h"
17 #include "src/sksl/ir/SkSLConstructor.h"
18 #include "src/sksl/ir/SkSLConstructorCompound.h"
19 #include "src/sksl/ir/SkSLConstructorSplat.h"
20 #include "src/sksl/ir/SkSLExpression.h"
21 #include "src/sksl/ir/SkSLLiteral.h"
22 #include "src/sksl/ir/SkSLPrefixExpression.h"
23 #include "src/sksl/ir/SkSLType.h"
24 #include "src/sksl/ir/SkSLVariable.h"
25 #include "src/sksl/ir/SkSLVariableReference.h"
26 
27 namespace SkSL {
28 
eliminate_no_op_boolean(const Expression & left,Operator op,const Expression & right)29 static std::unique_ptr<Expression> eliminate_no_op_boolean(const Expression& left,
30                                                            Operator op,
31                                                            const Expression& right) {
32     bool rightVal = right.as<Literal>().boolValue();
33 
34     // Detect no-op Boolean expressions and optimize them away.
35     if ((op.kind() == Token::Kind::TK_LOGICALAND && rightVal)  ||  // (expr && true)  -> (expr)
36         (op.kind() == Token::Kind::TK_LOGICALOR  && !rightVal) ||  // (expr || false) -> (expr)
37         (op.kind() == Token::Kind::TK_LOGICALXOR && !rightVal) ||  // (expr ^^ false) -> (expr)
38         (op.kind() == Token::Kind::TK_EQEQ       && rightVal)  ||  // (expr == true)  -> (expr)
39         (op.kind() == Token::Kind::TK_NEQ        && !rightVal)) {  // (expr != false) -> (expr)
40 
41         return left.clone();
42     }
43 
44     return nullptr;
45 }
46 
short_circuit_boolean(const Expression & left,Operator op,const Expression & right)47 static std::unique_ptr<Expression> short_circuit_boolean(const Expression& left,
48                                                          Operator op,
49                                                          const Expression& right) {
50     bool leftVal = left.as<Literal>().boolValue();
51 
52     // When the literal is on the left, we can sometimes eliminate the other expression entirely.
53     if ((op.kind() == Token::Kind::TK_LOGICALAND && !leftVal) ||  // (false && expr) -> (false)
54         (op.kind() == Token::Kind::TK_LOGICALOR  && leftVal)) {   // (true  || expr) -> (true)
55 
56         return left.clone();
57     }
58 
59     // We can't eliminate the right-side expression via short-circuit, but we might still be able to
60     // simplify away a no-op expression.
61     return eliminate_no_op_boolean(right, op, left);
62 }
63 
simplify_vector_equality(const Context & context,const Expression & left,Operator op,const Expression & right)64 static std::unique_ptr<Expression> simplify_vector_equality(const Context& context,
65                                                             const Expression& left,
66                                                             Operator op,
67                                                             const Expression& right) {
68     if (op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ) {
69         bool equality = (op.kind() == Token::Kind::TK_EQEQ);
70 
71         switch (left.compareConstant(right)) {
72             case Expression::ComparisonResult::kNotEqual:
73                 equality = !equality;
74                 [[fallthrough]];
75 
76             case Expression::ComparisonResult::kEqual:
77                 return Literal::MakeBool(context, left.fLine, equality);
78 
79             case Expression::ComparisonResult::kUnknown:
80                 break;
81         }
82     }
83     return nullptr;
84 }
85 
simplify_vector(const Context & context,const Expression & left,Operator op,const Expression & right)86 static std::unique_ptr<Expression> simplify_vector(const Context& context,
87                                                    const Expression& left,
88                                                    Operator op,
89                                                    const Expression& right) {
90     SkASSERT(left.type().isVector());
91     SkASSERT(left.type() == right.type());
92     const Type& type = left.type();
93 
94     // Handle equality operations: == !=
95     if (std::unique_ptr<Expression> result = simplify_vector_equality(context, left, op, right)) {
96         return result;
97     }
98 
99     // Handle floating-point arithmetic: + - * /
100     using FoldFn = double (*)(double, double);
101     FoldFn foldFn;
102     switch (op.kind()) {
103         case Token::Kind::TK_PLUS:  foldFn = +[](double a, double b) { return a + b; }; break;
104         case Token::Kind::TK_MINUS: foldFn = +[](double a, double b) { return a - b; }; break;
105         case Token::Kind::TK_STAR:  foldFn = +[](double a, double b) { return a * b; }; break;
106         case Token::Kind::TK_SLASH: foldFn = +[](double a, double b) { return a / b; }; break;
107         default:
108             return nullptr;
109     }
110 
111     const Type& componentType = type.componentType();
112     double minimumValue = -INFINITY, maximumValue = INFINITY;
113     if (componentType.isInteger()) {
114         minimumValue = componentType.minimumValue();
115         maximumValue = componentType.maximumValue();
116     }
117 
118     ExpressionArray args;
119     args.reserve_back(type.columns());
120     for (int i = 0; i < type.columns(); i++) {
121         double value = foldFn(*left.getConstantValue(i), *right.getConstantValue(i));
122         if (value < minimumValue || value > maximumValue) {
123             return nullptr;
124         }
125 
126         args.push_back(Literal::Make(left.fLine, value, &componentType));
127     }
128     return ConstructorCompound::Make(context, left.fLine, type, std::move(args));
129 }
130 
cast_expression(const Context & context,const Expression & expr,const Type & type)131 static std::unique_ptr<Expression> cast_expression(const Context& context,
132                                                    const Expression& expr,
133                                                    const Type& type) {
134     ExpressionArray ctorArgs;
135     ctorArgs.push_back(expr.clone());
136     return Constructor::Convert(context, expr.fLine, type, std::move(ctorArgs));
137 }
138 
GetConstantInt(const Expression & value,SKSL_INT * out)139 bool ConstantFolder::GetConstantInt(const Expression& value, SKSL_INT* out) {
140     const Expression* expr = GetConstantValueForVariable(value);
141     if (!expr->isIntLiteral()) {
142         return false;
143     }
144     *out = expr->as<Literal>().intValue();
145     return true;
146 }
147 
GetConstantValue(const Expression & value,double * out)148 bool ConstantFolder::GetConstantValue(const Expression& value, double* out) {
149     const Expression* expr = GetConstantValueForVariable(value);
150     if (!expr->is<Literal>()) {
151         return false;
152     }
153     *out = expr->as<Literal>().value();
154     return true;
155 }
156 
contains_constant_zero(const Expression & expr)157 static bool contains_constant_zero(const Expression& expr) {
158     int numSlots = expr.type().slotCount();
159     for (int index = 0; index < numSlots; ++index) {
160         skstd::optional<double> slotVal = expr.getConstantValue(index);
161         if (slotVal.has_value() && *slotVal == 0.0) {
162             return true;
163         }
164     }
165     return false;
166 }
167 
is_constant_value(const Expression & expr,double value)168 static bool is_constant_value(const Expression& expr, double value) {
169     int numSlots = expr.type().slotCount();
170     for (int index = 0; index < numSlots; ++index) {
171         skstd::optional<double> slotVal = expr.getConstantValue(index);
172         if (!slotVal.has_value() || *slotVal != value) {
173             return false;
174         }
175     }
176     return true;
177 }
178 
error_on_divide_by_zero(const Context & context,int line,Operator op,const Expression & right)179 static bool error_on_divide_by_zero(const Context& context, int line, Operator op,
180                                     const Expression& right) {
181     switch (op.kind()) {
182         case Token::Kind::TK_SLASH:
183         case Token::Kind::TK_SLASHEQ:
184         case Token::Kind::TK_PERCENT:
185         case Token::Kind::TK_PERCENTEQ:
186             if (contains_constant_zero(right)) {
187                 context.fErrors->error(line, "division by zero");
188                 return true;
189             }
190             return false;
191         default:
192             return false;
193     }
194 }
195 
GetConstantValueForVariable(const Expression & inExpr)196 const Expression* ConstantFolder::GetConstantValueForVariable(const Expression& inExpr) {
197     for (const Expression* expr = &inExpr;;) {
198         if (!expr->is<VariableReference>()) {
199             break;
200         }
201         const VariableReference& varRef = expr->as<VariableReference>();
202         if (varRef.refKind() != VariableRefKind::kRead) {
203             break;
204         }
205         const Variable& var = *varRef.variable();
206         if (!(var.modifiers().fFlags & Modifiers::kConst_Flag)) {
207             break;
208         }
209         expr = var.initialValue();
210         if (!expr) {
211             // Function parameters can be const but won't have an initial value.
212             break;
213         }
214         if (expr->isCompileTimeConstant()) {
215             return expr;
216         }
217     }
218     // We didn't find a compile-time constant at the end. Return the expression as-is.
219     return &inExpr;
220 }
221 
MakeConstantValueForVariable(std::unique_ptr<Expression> expr)222 std::unique_ptr<Expression> ConstantFolder::MakeConstantValueForVariable(
223         std::unique_ptr<Expression> expr) {
224     const Expression* constantExpr = GetConstantValueForVariable(*expr);
225     if (constantExpr != expr.get()) {
226         expr = constantExpr->clone();
227     }
228     return expr;
229 }
230 
simplify_no_op_arithmetic(const Context & context,const Expression & left,Operator op,const Expression & right,const Type & resultType)231 static std::unique_ptr<Expression> simplify_no_op_arithmetic(const Context& context,
232                                                              const Expression& left,
233                                                              Operator op,
234                                                              const Expression& right,
235                                                              const Type& resultType) {
236     switch (op.kind()) {
237         case Token::Kind::TK_PLUS:
238             if (is_constant_value(right, 0.0)) {  // x + 0
239                 return cast_expression(context, left, resultType);
240             }
241             if (is_constant_value(left, 0.0)) {   // 0 + x
242                 return cast_expression(context, right, resultType);
243             }
244             break;
245 
246         case Token::Kind::TK_STAR:
247             if (is_constant_value(right, 1.0)) {  // x * 1
248                 return cast_expression(context, left, resultType);
249             }
250             if (is_constant_value(left, 1.0)) {   // 1 * x
251                 return cast_expression(context, right, resultType);
252             }
253             if (is_constant_value(right, 0.0) && !left.hasSideEffects()) {  // x * 0
254                 return cast_expression(context, right, resultType);
255             }
256             if (is_constant_value(left, 0.0) && !right.hasSideEffects()) {  // 0 * x
257                 return cast_expression(context, left, resultType);
258             }
259             break;
260 
261         case Token::Kind::TK_MINUS:
262             if (is_constant_value(right, 0.0)) {  // x - 0
263                 return cast_expression(context, left, resultType);
264             }
265             if (is_constant_value(left, 0.0)) {   // 0 - x (to `-x`)
266                 if (std::unique_ptr<Expression> val = cast_expression(context, right, resultType)) {
267                     return PrefixExpression::Make(context, Token::Kind::TK_MINUS, std::move(val));
268                 }
269             }
270             break;
271 
272         case Token::Kind::TK_SLASH:
273             if (is_constant_value(right, 1.0)) {  // x / 1
274                 return cast_expression(context, left, resultType);
275             }
276             break;
277 
278         case Token::Kind::TK_PLUSEQ:
279         case Token::Kind::TK_MINUSEQ:
280             if (is_constant_value(right, 0.0)) {  // x += 0, x -= 0
281                 if (std::unique_ptr<Expression> var = cast_expression(context, left, resultType)) {
282                     Analysis::UpdateVariableRefKind(var.get(), VariableRefKind::kRead);
283                     return var;
284                 }
285             }
286             break;
287 
288         case Token::Kind::TK_STAREQ:
289         case Token::Kind::TK_SLASHEQ:
290             if (is_constant_value(right, 1.0)) {  // x *= 1, x /= 1
291                 if (std::unique_ptr<Expression> var = cast_expression(context, left, resultType)) {
292                     Analysis::UpdateVariableRefKind(var.get(), VariableRefKind::kRead);
293                     return var;
294                 }
295             }
296             break;
297 
298         default:
299             break;
300     }
301 
302     return nullptr;
303 }
304 
305 template <typename T>
fold_float_expression(int line,T result,const Type * resultType)306 static std::unique_ptr<Expression> fold_float_expression(int line,
307                                                          T result,
308                                                          const Type* resultType) {
309     // If constant-folding this expression would generate a NaN/infinite result, leave it as-is.
310     if constexpr (!std::is_same<T, bool>::value) {
311         if (!std::isfinite(result)) {
312             return nullptr;
313         }
314     }
315 
316     return Literal::Make(line, result, resultType);
317 }
318 
319 template <typename T>
fold_int_expression(int line,T result,const Type * resultType)320 static std::unique_ptr<Expression> fold_int_expression(int line,
321                                                        T result,
322                                                        const Type* resultType) {
323     // If constant-folding this expression would overflow the result type, leave it as-is.
324     if constexpr (!std::is_same<T, bool>::value) {
325         if (result < resultType->minimumValue() || result > resultType->maximumValue()) {
326             return nullptr;
327         }
328     }
329 
330     return Literal::Make(line, result, resultType);
331 }
332 
Simplify(const Context & context,int line,const Expression & leftExpr,Operator op,const Expression & rightExpr,const Type & resultType)333 std::unique_ptr<Expression> ConstantFolder::Simplify(const Context& context,
334                                                      int line,
335                                                      const Expression& leftExpr,
336                                                      Operator op,
337                                                      const Expression& rightExpr,
338                                                      const Type& resultType) {
339     // Replace constant variables with their literal values.
340     const Expression* left = GetConstantValueForVariable(leftExpr);
341     const Expression* right = GetConstantValueForVariable(rightExpr);
342 
343     // 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.
345     if (op.kind() == Token::Kind::TK_COMMA && !left->hasSideEffects()) {
346         return right->clone();
347     }
348 
349     // 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.
352     if (op.kind() == Token::Kind::TK_EQ && Analysis::IsSameExpressionTree(*left, *right)) {
353         return right->clone();
354     }
355 
356     // Simplify the expression when both sides are constant Boolean literals.
357     if (left->isBoolLiteral() && right->isBoolLiteral()) {
358         bool leftVal  = left->as<Literal>().boolValue();
359         bool rightVal = right->as<Literal>().boolValue();
360         bool result;
361         switch (op.kind()) {
362             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;
365             case Token::Kind::TK_EQEQ:       result = leftVal == rightVal; break;
366             case Token::Kind::TK_NEQ:        result = leftVal != rightVal; break;
367             default: return nullptr;
368         }
369         return Literal::MakeBool(context, line, result);
370     }
371 
372     // If the left side is a Boolean literal, apply short-circuit optimizations.
373     if (left->isBoolLiteral()) {
374         return short_circuit_boolean(*left, op, *right);
375     }
376 
377     // If the right side is a Boolean literal...
378     if (right->isBoolLiteral()) {
379         // ... and the left side has no side effects...
380         if (!left->hasSideEffects()) {
381             // We can reverse the expressions and short-circuit optimizations are still valid.
382             return short_circuit_boolean(*right, op, *left);
383         }
384 
385         // We can't use short-circuiting, but we can still optimize away no-op Boolean expressions.
386         return eliminate_no_op_boolean(*left, op, *right);
387     }
388 
389     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.)
392         return Literal::MakeBool(context, leftExpr.fLine, /*value=*/true);
393     }
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.)
398         return Literal::MakeBool(context, leftExpr.fLine, /*value=*/false);
399     }
400 
401     if (error_on_divide_by_zero(context, line, op, *right)) {
402         return nullptr;
403     }
404 
405     // 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.
418     if (!left->isCompileTimeConstant() || !right->isCompileTimeConstant()) {
419         return nullptr;
420     }
421 
422     // 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.
424     // TODO(skia:10932): detect and handle integer overflow properly.
425     using SKSL_UINT = uint64_t;
426     if (left->isIntLiteral() && right->isIntLiteral()) {
427         SKSL_INT leftVal  = left->as<Literal>().intValue();
428         SKSL_INT rightVal = right->as<Literal>().intValue();
429 
430         #define RESULT(Op)   fold_int_expression(line, \
431                                         (SKSL_INT)(leftVal) Op (SKSL_INT)(rightVal), &resultType)
432         #define URESULT(Op)  fold_int_expression(line, \
433                              (SKSL_INT)((SKSL_UINT)(leftVal) Op (SKSL_UINT)(rightVal)), &resultType)
434         switch (op.kind()) {
435             case Token::Kind::TK_PLUS:       return URESULT(+);
436             case Token::Kind::TK_MINUS:      return URESULT(-);
437             case Token::Kind::TK_STAR:       return URESULT(*);
438             case Token::Kind::TK_SLASH:
439                 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
440                     context.fErrors->error(line, "arithmetic overflow");
441                     return nullptr;
442                 }
443                 return RESULT(/);
444             case Token::Kind::TK_PERCENT:
445                 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
446                     context.fErrors->error(line, "arithmetic overflow");
447                     return nullptr;
448                 }
449                 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(<=);
459             case Token::Kind::TK_SHL:
460                 if (rightVal >= 0 && rightVal <= 31) {
461                     // 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.
463                     return URESULT(<<);
464                 }
465                 context.fErrors->error(line, "shift value out of range");
466                 return nullptr;
467             case Token::Kind::TK_SHR:
468                 if (rightVal >= 0 && rightVal <= 31) {
469                     return RESULT(>>);
470                 }
471                 context.fErrors->error(line, "shift value out of range");
472                 return nullptr;
473 
474             default:
475                 return nullptr;
476         }
477         #undef RESULT
478         #undef URESULT
479     }
480 
481     // Perform constant folding on pairs of floating-point literals.
482     if (left->isFloatLiteral() && right->isFloatLiteral()) {
483         SKSL_FLOAT leftVal  = left->as<Literal>().floatValue();
484         SKSL_FLOAT rightVal = right->as<Literal>().floatValue();
485 
486         #define RESULT(Op) fold_float_expression(line, leftVal Op rightVal, &resultType)
487         switch (op.kind()) {
488             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;
499         }
500         #undef RESULT
501     }
502 
503     // Perform constant folding on pairs of vectors.
504     if (leftType.isVector() && leftType == rightType) {
505         if (leftType.componentType().isFloat()) {
506             return simplify_vector(context, *left, op, *right);
507         }
508         if (leftType.componentType().isInteger()) {
509             return simplify_vector(context, *left, op, *right);
510         }
511         if (leftType.componentType().isBoolean()) {
512             return simplify_vector_equality(context, *left, op, *right);
513         }
514         return nullptr;
515     }
516 
517     // Perform constant folding on vectors against scalars, e.g.: half4(2) + 2
518     if (leftType.isVector() && leftType.componentType() == rightType) {
519         if (rightType.isFloat()) {
520             return simplify_vector(context, *left, op, ConstructorSplat(*right, left->type()));
521         }
522         if (rightType.isInteger()) {
523             return simplify_vector(context, *left, op, ConstructorSplat(*right, left->type()));
524         }
525         if (rightType.isBoolean()) {
526             return simplify_vector_equality(context, *left, op,
527                                             ConstructorSplat(*right, left->type()));
528         }
529         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()) {
535             return simplify_vector(context, ConstructorSplat(*left, right->type()), op, *right);
536         }
537         if (leftType.isInteger()) {
538             return simplify_vector(context, ConstructorSplat(*left, right->type()), op, *right);
539         }
540         if (leftType.isBoolean()) {
541             return simplify_vector_equality(context, ConstructorSplat(*left, right->type()),
542                                             op, *right);
543         }
544         return nullptr;
545     }
546 
547     // Perform constant folding on pairs of matrices or arrays.
548     if ((leftType.isMatrix() && rightType.isMatrix()) ||
549         (leftType.isArray() && rightType.isArray())) {
550         bool equality;
551         switch (op.kind()) {
552             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 
562         switch (left->compareConstant(*right)) {
563             case Expression::ComparisonResult::kNotEqual:
564                 equality = !equality;
565                 [[fallthrough]];
566 
567             case Expression::ComparisonResult::kEqual:
568                 return Literal::MakeBool(context, line, equality);
569 
570             case Expression::ComparisonResult::kUnknown:
571                 return nullptr;
572         }
573     }
574 
575     // We aren't able to constant-fold.
576     return nullptr;
577 }
578 
579 }  // namespace SkSL
580