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 SkSLAnalysis_DEFINED 9 #define SkSLAnalysis_DEFINED 10 11 #include "include/private/SkSLSampleUsage.h" 12 #include "include/private/base/SkTArray.h" 13 14 #include <cstdint> 15 #include <memory> 16 #include <vector> 17 18 namespace SkSL { 19 20 class Context; 21 class ErrorReporter; 22 class Expression; 23 class FunctionDeclaration; 24 class FunctionDefinition; 25 class Position; 26 class ProgramElement; 27 class ProgramUsage; 28 class Statement; 29 class SymbolTable; 30 class Variable; 31 class VariableReference; 32 enum class VariableRefKind : int8_t; 33 struct ForLoopPositions; 34 struct LoopUnrollInfo; 35 struct Module; 36 struct Program; 37 38 /** 39 * Provides utilities for analyzing SkSL statically before it's composed into a full program. 40 */ 41 namespace Analysis { 42 43 /** 44 * Determines how `program` samples `child`. By default, assumes that the sample coords might be 45 * modified, so `child.eval(sampleCoords)` is treated as Explicit. If writesToSampleCoords is false, 46 * treats that as PassThrough, instead. If elidedSampleCoordCount is provided, the pointed to value 47 * will be incremented by the number of sample calls where the above rewrite was performed. 48 */ 49 SampleUsage GetSampleUsage(const Program& program, 50 const Variable& child, 51 bool writesToSampleCoords = true, 52 int* elidedSampleCoordCount = nullptr); 53 54 bool ReferencesBuiltin(const Program& program, int builtin); 55 56 bool ReferencesSampleCoords(const Program& program); 57 bool ReferencesFragCoords(const Program& program); 58 59 bool CallsSampleOutsideMain(const Program& program); 60 61 bool CallsColorTransformIntrinsics(const Program& program); 62 63 /** 64 * Determines if `function` always returns an opaque color (a vec4 where the last component is known 65 * to be 1). This is conservative, and based on constant expression analysis. 66 */ 67 bool ReturnsOpaqueColor(const FunctionDefinition& function); 68 69 /** 70 * Determines if `function` is a color filter which returns the alpha component of the input color 71 * unchanged. This is a very conservative analysis, and only supports returning a swizzle of the 72 * input color, or returning a constructor that ends with `input.a`. 73 */ 74 bool ReturnsInputAlpha(const FunctionDefinition& function, const ProgramUsage& usage); 75 76 /** 77 * Checks for recursion or overly-deep function-call chains, and rejects programs which have them. 78 */ 79 bool CheckProgramStructure(const Program& program); 80 81 /** Determines if `expr` contains a reference to the variable sk_RTAdjust. */ 82 bool ContainsRTAdjust(const Expression& expr); 83 84 /** Determines if `expr` contains a reference to variable `var`. */ 85 bool ContainsVariable(const Expression& expr, const Variable& var); 86 87 /** Determines if `expr` has any side effects. (Is the expression state-altering or pure?) */ 88 bool HasSideEffects(const Expression& expr); 89 90 /** Determines if `expr` is a compile-time constant (composed of just constructors and literals). */ 91 bool IsCompileTimeConstant(const Expression& expr); 92 93 /** 94 * Determines if `expr` is a dynamically-uniform expression; this returns true if the expression 95 * could be evaluated at compile time if uniform values were known. 96 */ 97 bool IsDynamicallyUniformExpression(const Expression& expr); 98 99 /** 100 * Detect an orphaned variable declaration outside of a scope, e.g. if (true) int a;. Returns 101 * true if an error was reported. 102 */ 103 bool DetectVarDeclarationWithoutScope(const Statement& stmt, ErrorReporter* errors = nullptr); 104 105 int NodeCountUpToLimit(const FunctionDefinition& function, int limit); 106 107 /** 108 * Finds unconditional exits from a switch-case. Returns true if this statement unconditionally 109 * causes an exit from this switch (via continue, break or return). 110 */ 111 bool SwitchCaseContainsUnconditionalExit(const Statement& stmt); 112 113 /** 114 * Finds conditional exits from a switch-case. Returns true if this statement contains a 115 * conditional that wraps a potential exit from the switch (via continue, break or return). 116 */ 117 bool SwitchCaseContainsConditionalExit(const Statement& stmt); 118 119 std::unique_ptr<ProgramUsage> GetUsage(const Program& program); 120 std::unique_ptr<ProgramUsage> GetUsage(const Module& module); 121 122 /** Returns true if the passed-in statement might alter `var`. */ 123 bool StatementWritesToVariable(const Statement& stmt, const Variable& var); 124 125 /** 126 * Detects if the passed-in block contains a `continue`, `break` or `return` that could directly 127 * affect its control flow. (A `continue` or `break` nested inside an inner loop/switch will not 128 * affect the loop, but a `return` will.) 129 */ 130 struct LoopControlFlowInfo { 131 bool fHasContinue = false; 132 bool fHasBreak = false; 133 bool fHasReturn = false; 134 }; 135 LoopControlFlowInfo GetLoopControlFlowInfo(const Statement& stmt); 136 137 /** 138 * Returns true if the expression can be assigned-into. Pass `info` if you want to know the 139 * VariableReference that will be written to. Pass `errors` to report an error for expressions that 140 * are not actually writable. 141 */ 142 struct AssignmentInfo { 143 VariableReference* fAssignedVar = nullptr; 144 }; 145 bool IsAssignable(Expression& expr, AssignmentInfo* info = nullptr, 146 ErrorReporter* errors = nullptr); 147 148 /** 149 * Updates the `refKind` field of the VariableReference at the top level of `expr`. 150 * If `expr` can be assigned to (`IsAssignable`), true is returned and no errors are reported. 151 * If not, false is returned. and an error is reported if `errors` is non-null. 152 */ 153 bool UpdateVariableRefKind(Expression* expr, VariableRefKind kind, ErrorReporter* errors = nullptr); 154 155 /** 156 * A "trivial" expression is one where we'd feel comfortable cloning it multiple times in 157 * the code, without worrying about incurring a performance penalty. Examples: 158 * - true 159 * - 3.14159265 160 * - myIntVariable 161 * - myColor.rgb 162 * - myArray[123] 163 * - myStruct.myField 164 * - half4(0) 165 * - !myBoolean 166 * - +myValue 167 * - -myValue 168 * - ~myInteger 169 * 170 * Trivial-ness is stackable. Somewhat large expressions can occasionally make the cut: 171 * - half4(myColor.a) 172 * - myStruct.myArrayField[7].xzy 173 */ 174 bool IsTrivialExpression(const Expression& expr); 175 176 /** 177 * Returns true if both expression trees are the same. Used by the optimizer to look for self- 178 * assignment or self-comparison; won't necessarily catch complex cases. Rejects expressions 179 * that may cause side effects. 180 */ 181 bool IsSameExpressionTree(const Expression& left, const Expression& right); 182 183 /** 184 * Returns true if expr is a constant-expression, as defined by GLSL 1.0, section 5.10. 185 * A constant expression is one of: 186 * - A literal value 187 * - A global or local variable qualified as 'const', excluding function parameters 188 * - An expression formed by an operator on operands that are constant expressions, including 189 * getting an element of a constant vector or a constant matrix, or a field of a constant 190 * structure 191 * - A constructor whose arguments are all constant expressions 192 * - A built-in function call whose arguments are all constant expressions, with the exception 193 * of the texture lookup functions 194 */ 195 bool IsConstantExpression(const Expression& expr); 196 197 /** 198 * Ensures that any index-expressions inside of for-loops qualify as 'constant-index-expressions' as 199 * defined by GLSL 1.0, Appendix A, Section 5. A constant-index-expression is: 200 * - A constant-expression 201 * - Loop indices (as defined in Appendix A, Section 4) 202 * - Expressions composed of both of the above 203 */ 204 void ValidateIndexingForES2(const ProgramElement& pe, ErrorReporter& errors); 205 206 /** 207 * Emits an internal error if a VarDeclaration exists without a matching entry in the nearest 208 * SymbolTable. 209 */ 210 void CheckSymbolTableCorrectness(const Program& program); 211 212 /** 213 * Ensures that a for-loop meets the strict requirements of The OpenGL ES Shading Language 1.00, 214 * Appendix A, Section 4. 215 * If the requirements are met, information about the loop's structure is returned. 216 * If the requirements are not met, the problem is reported via `errors` (if not nullptr), and 217 * null is returned. 218 * The loop test-expression may be altered by this check. For example, a loop like this: 219 * for (float x = 1.0; x != 0.0; x -= 0.01) {...} 220 * appears to be ES2-safe, but due to floating-point rounding error, it may not actually terminate. 221 * We rewrite the test condition to `x > 0.0` in order to ensure loop termination. 222 */ 223 std::unique_ptr<LoopUnrollInfo> GetLoopUnrollInfo(const Context& context, 224 Position pos, 225 const ForLoopPositions& positions, 226 const Statement* loopInitializer, 227 std::unique_ptr<Expression>* loopTestPtr, 228 const Expression* loopNext, 229 const Statement* loopStatement, 230 ErrorReporter* errors); 231 232 /** Detects functions that fail to return a value on at least one path. */ 233 bool CanExitWithoutReturningValue(const FunctionDeclaration& funcDecl, const Statement& body); 234 235 /** Determines if a given function has multiple and/or early returns. */ 236 enum class ReturnComplexity { 237 kSingleSafeReturn, 238 kScopedReturns, 239 kEarlyReturns, 240 }; 241 ReturnComplexity GetReturnComplexity(const FunctionDefinition& funcDef); 242 243 /** 244 * Runs at finalization time to perform any last-minute correctness checks: 245 * - Reports dangling FunctionReference or TypeReference expressions 246 * - Reports function `out` params which are never written to (structs are currently exempt) 247 */ 248 void DoFinalizationChecks(const Program& program); 249 250 /** 251 * Error checks compute shader in/outs and returns a vector containing them ordered by location. 252 */ 253 skia_private::TArray<const SkSL::Variable*> GetComputeShaderMainParams(const Context& context, 254 const Program& program); 255 256 /** 257 * Tracks the symbol table stack, in conjunction with a ProgramVisitor. Inside `visitStatement`, 258 * pass the current statement and a symbol-table vector to a SymbolTableStackBuilder and the symbol 259 * table stack will be maintained automatically. 260 */ 261 class SymbolTableStackBuilder { 262 public: 263 // If the passed-in statement holds a symbol table, adds it to the stack. 264 SymbolTableStackBuilder(const Statement* stmt, std::vector<SymbolTable*>* stack); 265 266 // If a symbol table was added to the stack earlier, removes it from the stack. 267 ~SymbolTableStackBuilder(); 268 269 // Returns true if an entry was added to the symbol-table stack. foundSymbolTable()270 bool foundSymbolTable() { 271 return fStackToPop != nullptr; 272 } 273 274 private: 275 std::vector<SymbolTable*>* fStackToPop = nullptr; 276 }; 277 278 } // namespace Analysis 279 } // namespace SkSL 280 281 #endif 282