Path: blob/21.2-virgl/src/compiler/glsl/ast_to_hir.cpp
4545 views
/*1* Copyright © 2010 Intel Corporation2*3* Permission is hereby granted, free of charge, to any person obtaining a4* copy of this software and associated documentation files (the "Software"),5* to deal in the Software without restriction, including without limitation6* the rights to use, copy, modify, merge, publish, distribute, sublicense,7* and/or sell copies of the Software, and to permit persons to whom the8* Software is furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice (including the next11* paragraph) shall be included in all copies or substantial portions of the12* Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL17* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING19* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER20* DEALINGS IN THE SOFTWARE.21*/2223/**24* \file ast_to_hir.c25* Convert abstract syntax to to high-level intermediate reprensentation (HIR).26*27* During the conversion to HIR, the majority of the symantic checking is28* preformed on the program. This includes:29*30* * Symbol table management31* * Type checking32* * Function binding33*34* The majority of this work could be done during parsing, and the parser could35* probably generate HIR directly. However, this results in frequent changes36* to the parser code. Since we do not assume that every system this complier37* is built on will have Flex and Bison installed, we have to store the code38* generated by these tools in our version control system. In other parts of39* the system we've seen problems where a parser was changed but the generated40* code was not committed, merge conflicts where created because two developers41* had slightly different versions of Bison installed, etc.42*43* I have also noticed that running Bison generated parsers in GDB is very44* irritating. When you get a segfault on '$$ = $1->foo', you can't very45* well 'print $1' in GDB.46*47* As a result, my preference is to put as little C code as possible in the48* parser (and lexer) sources.49*/5051#include "glsl_symbol_table.h"52#include "glsl_parser_extras.h"53#include "ast.h"54#include "compiler/glsl_types.h"55#include "util/hash_table.h"56#include "main/mtypes.h"57#include "main/macros.h"58#include "main/shaderobj.h"59#include "ir.h"60#include "ir_builder.h"61#include "builtin_functions.h"6263using namespace ir_builder;6465static void66detect_conflicting_assignments(struct _mesa_glsl_parse_state *state,67exec_list *instructions);68static void69verify_subroutine_associated_funcs(struct _mesa_glsl_parse_state *state);7071static void72remove_per_vertex_blocks(exec_list *instructions,73_mesa_glsl_parse_state *state, ir_variable_mode mode);7475/**76* Visitor class that finds the first instance of any write-only variable that77* is ever read, if any78*/79class read_from_write_only_variable_visitor : public ir_hierarchical_visitor80{81public:82read_from_write_only_variable_visitor() : found(NULL)83{84}8586virtual ir_visitor_status visit(ir_dereference_variable *ir)87{88if (this->in_assignee)89return visit_continue;9091ir_variable *var = ir->variable_referenced();92/* We can have memory_write_only set on both images and buffer variables,93* but in the former there is a distinction between reads from94* the variable itself (write_only) and from the memory they point to95* (memory_write_only), while in the case of buffer variables there is96* no such distinction, that is why this check here is limited to97* buffer variables alone.98*/99if (!var || var->data.mode != ir_var_shader_storage)100return visit_continue;101102if (var->data.memory_write_only) {103found = var;104return visit_stop;105}106107return visit_continue;108}109110ir_variable *get_variable() {111return found;112}113114virtual ir_visitor_status visit_enter(ir_expression *ir)115{116/* .length() doesn't actually read anything */117if (ir->operation == ir_unop_ssbo_unsized_array_length)118return visit_continue_with_parent;119120return visit_continue;121}122123private:124ir_variable *found;125};126127void128_mesa_ast_to_hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)129{130_mesa_glsl_initialize_variables(instructions, state);131132state->symbols->separate_function_namespace = state->language_version == 110;133134state->current_function = NULL;135136state->toplevel_ir = instructions;137138state->gs_input_prim_type_specified = false;139state->tcs_output_vertices_specified = false;140state->cs_input_local_size_specified = false;141142/* Section 4.2 of the GLSL 1.20 specification states:143* "The built-in functions are scoped in a scope outside the global scope144* users declare global variables in. That is, a shader's global scope,145* available for user-defined functions and global variables, is nested146* inside the scope containing the built-in functions."147*148* Since built-in functions like ftransform() access built-in variables,149* it follows that those must be in the outer scope as well.150*151* We push scope here to create this nesting effect...but don't pop.152* This way, a shader's globals are still in the symbol table for use153* by the linker.154*/155state->symbols->push_scope();156157foreach_list_typed (ast_node, ast, link, & state->translation_unit)158ast->hir(instructions, state);159160verify_subroutine_associated_funcs(state);161detect_recursion_unlinked(state, instructions);162detect_conflicting_assignments(state, instructions);163164state->toplevel_ir = NULL;165166/* Move all of the variable declarations to the front of the IR list, and167* reverse the order. This has the (intended!) side effect that vertex168* shader inputs and fragment shader outputs will appear in the IR in the169* same order that they appeared in the shader code. This results in the170* locations being assigned in the declared order. Many (arguably buggy)171* applications depend on this behavior, and it matches what nearly all172* other drivers do.173*/174foreach_in_list_safe(ir_instruction, node, instructions) {175ir_variable *const var = node->as_variable();176177if (var == NULL)178continue;179180var->remove();181instructions->push_head(var);182}183184/* Figure out if gl_FragCoord is actually used in fragment shader */185ir_variable *const var = state->symbols->get_variable("gl_FragCoord");186if (var != NULL)187state->fs_uses_gl_fragcoord = var->data.used;188189/* From section 7.1 (Built-In Language Variables) of the GLSL 4.10 spec:190*191* If multiple shaders using members of a built-in block belonging to192* the same interface are linked together in the same program, they193* must all redeclare the built-in block in the same way, as described194* in section 4.3.7 "Interface Blocks" for interface block matching, or195* a link error will result.196*197* The phrase "using members of a built-in block" implies that if two198* shaders are linked together and one of them *does not use* any members199* of the built-in block, then that shader does not need to have a matching200* redeclaration of the built-in block.201*202* This appears to be a clarification to the behaviour established for203* gl_PerVertex by GLSL 1.50, therefore implement it regardless of GLSL204* version.205*206* The definition of "interface" in section 4.3.7 that applies here is as207* follows:208*209* The boundary between adjacent programmable pipeline stages: This210* spans all the outputs in all compilation units of the first stage211* and all the inputs in all compilation units of the second stage.212*213* Therefore this rule applies to both inter- and intra-stage linking.214*215* The easiest way to implement this is to check whether the shader uses216* gl_PerVertex right after ast-to-ir conversion, and if it doesn't, simply217* remove all the relevant variable declaration from the IR, so that the218* linker won't see them and complain about mismatches.219*/220remove_per_vertex_blocks(instructions, state, ir_var_shader_in);221remove_per_vertex_blocks(instructions, state, ir_var_shader_out);222223/* Check that we don't have reads from write-only variables */224read_from_write_only_variable_visitor v;225v.run(instructions);226ir_variable *error_var = v.get_variable();227if (error_var) {228/* It would be nice to have proper location information, but for that229* we would need to check this as we process each kind of AST node230*/231YYLTYPE loc;232memset(&loc, 0, sizeof(loc));233_mesa_glsl_error(&loc, state, "Read from write-only variable `%s'",234error_var->name);235}236}237238239static ir_expression_operation240get_implicit_conversion_operation(const glsl_type *to, const glsl_type *from,241struct _mesa_glsl_parse_state *state)242{243switch (to->base_type) {244case GLSL_TYPE_FLOAT:245switch (from->base_type) {246case GLSL_TYPE_INT: return ir_unop_i2f;247case GLSL_TYPE_UINT: return ir_unop_u2f;248default: return (ir_expression_operation)0;249}250251case GLSL_TYPE_UINT:252if (!state->has_implicit_int_to_uint_conversion())253return (ir_expression_operation)0;254switch (from->base_type) {255case GLSL_TYPE_INT: return ir_unop_i2u;256default: return (ir_expression_operation)0;257}258259case GLSL_TYPE_DOUBLE:260if (!state->has_double())261return (ir_expression_operation)0;262switch (from->base_type) {263case GLSL_TYPE_INT: return ir_unop_i2d;264case GLSL_TYPE_UINT: return ir_unop_u2d;265case GLSL_TYPE_FLOAT: return ir_unop_f2d;266case GLSL_TYPE_INT64: return ir_unop_i642d;267case GLSL_TYPE_UINT64: return ir_unop_u642d;268default: return (ir_expression_operation)0;269}270271case GLSL_TYPE_UINT64:272if (!state->has_int64())273return (ir_expression_operation)0;274switch (from->base_type) {275case GLSL_TYPE_INT: return ir_unop_i2u64;276case GLSL_TYPE_UINT: return ir_unop_u2u64;277case GLSL_TYPE_INT64: return ir_unop_i642u64;278default: return (ir_expression_operation)0;279}280281case GLSL_TYPE_INT64:282if (!state->has_int64())283return (ir_expression_operation)0;284switch (from->base_type) {285case GLSL_TYPE_INT: return ir_unop_i2i64;286default: return (ir_expression_operation)0;287}288289default: return (ir_expression_operation)0;290}291}292293294/**295* If a conversion is available, convert one operand to a different type296*297* The \c from \c ir_rvalue is converted "in place".298*299* \param to Type that the operand it to be converted to300* \param from Operand that is being converted301* \param state GLSL compiler state302*303* \return304* If a conversion is possible (or unnecessary), \c true is returned.305* Otherwise \c false is returned.306*/307static bool308apply_implicit_conversion(const glsl_type *to, ir_rvalue * &from,309struct _mesa_glsl_parse_state *state)310{311void *ctx = state;312if (to->base_type == from->type->base_type)313return true;314315/* Prior to GLSL 1.20, there are no implicit conversions */316if (!state->has_implicit_conversions())317return false;318319/* From page 27 (page 33 of the PDF) of the GLSL 1.50 spec:320*321* "There are no implicit array or structure conversions. For322* example, an array of int cannot be implicitly converted to an323* array of float.324*/325if (!to->is_numeric() || !from->type->is_numeric())326return false;327328/* We don't actually want the specific type `to`, we want a type329* with the same base type as `to`, but the same vector width as330* `from`.331*/332to = glsl_type::get_instance(to->base_type, from->type->vector_elements,333from->type->matrix_columns);334335ir_expression_operation op = get_implicit_conversion_operation(to, from->type, state);336if (op) {337from = new(ctx) ir_expression(op, to, from, NULL);338return true;339} else {340return false;341}342}343344345static const struct glsl_type *346arithmetic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,347bool multiply,348struct _mesa_glsl_parse_state *state, YYLTYPE *loc)349{350const glsl_type *type_a = value_a->type;351const glsl_type *type_b = value_b->type;352353/* From GLSL 1.50 spec, page 56:354*355* "The arithmetic binary operators add (+), subtract (-),356* multiply (*), and divide (/) operate on integer and357* floating-point scalars, vectors, and matrices."358*/359if (!type_a->is_numeric() || !type_b->is_numeric()) {360_mesa_glsl_error(loc, state,361"operands to arithmetic operators must be numeric");362return glsl_type::error_type;363}364365366/* "If one operand is floating-point based and the other is367* not, then the conversions from Section 4.1.10 "Implicit368* Conversions" are applied to the non-floating-point-based operand."369*/370if (!apply_implicit_conversion(type_a, value_b, state)371&& !apply_implicit_conversion(type_b, value_a, state)) {372_mesa_glsl_error(loc, state,373"could not implicitly convert operands to "374"arithmetic operator");375return glsl_type::error_type;376}377type_a = value_a->type;378type_b = value_b->type;379380/* "If the operands are integer types, they must both be signed or381* both be unsigned."382*383* From this rule and the preceeding conversion it can be inferred that384* both types must be GLSL_TYPE_FLOAT, or GLSL_TYPE_UINT, or GLSL_TYPE_INT.385* The is_numeric check above already filtered out the case where either386* type is not one of these, so now the base types need only be tested for387* equality.388*/389if (type_a->base_type != type_b->base_type) {390_mesa_glsl_error(loc, state,391"base type mismatch for arithmetic operator");392return glsl_type::error_type;393}394395/* "All arithmetic binary operators result in the same fundamental type396* (signed integer, unsigned integer, or floating-point) as the397* operands they operate on, after operand type conversion. After398* conversion, the following cases are valid399*400* * The two operands are scalars. In this case the operation is401* applied, resulting in a scalar."402*/403if (type_a->is_scalar() && type_b->is_scalar())404return type_a;405406/* "* One operand is a scalar, and the other is a vector or matrix.407* In this case, the scalar operation is applied independently to each408* component of the vector or matrix, resulting in the same size409* vector or matrix."410*/411if (type_a->is_scalar()) {412if (!type_b->is_scalar())413return type_b;414} else if (type_b->is_scalar()) {415return type_a;416}417418/* All of the combinations of <scalar, scalar>, <vector, scalar>,419* <scalar, vector>, <scalar, matrix>, and <matrix, scalar> have been420* handled.421*/422assert(!type_a->is_scalar());423assert(!type_b->is_scalar());424425/* "* The two operands are vectors of the same size. In this case, the426* operation is done component-wise resulting in the same size427* vector."428*/429if (type_a->is_vector() && type_b->is_vector()) {430if (type_a == type_b) {431return type_a;432} else {433_mesa_glsl_error(loc, state,434"vector size mismatch for arithmetic operator");435return glsl_type::error_type;436}437}438439/* All of the combinations of <scalar, scalar>, <vector, scalar>,440* <scalar, vector>, <scalar, matrix>, <matrix, scalar>, and441* <vector, vector> have been handled. At least one of the operands must442* be matrix. Further, since there are no integer matrix types, the base443* type of both operands must be float.444*/445assert(type_a->is_matrix() || type_b->is_matrix());446assert(type_a->is_float() || type_a->is_double());447assert(type_b->is_float() || type_b->is_double());448449/* "* The operator is add (+), subtract (-), or divide (/), and the450* operands are matrices with the same number of rows and the same451* number of columns. In this case, the operation is done component-452* wise resulting in the same size matrix."453* * The operator is multiply (*), where both operands are matrices or454* one operand is a vector and the other a matrix. A right vector455* operand is treated as a column vector and a left vector operand as a456* row vector. In all these cases, it is required that the number of457* columns of the left operand is equal to the number of rows of the458* right operand. Then, the multiply (*) operation does a linear459* algebraic multiply, yielding an object that has the same number of460* rows as the left operand and the same number of columns as the right461* operand. Section 5.10 "Vector and Matrix Operations" explains in462* more detail how vectors and matrices are operated on."463*/464if (! multiply) {465if (type_a == type_b)466return type_a;467} else {468const glsl_type *type = glsl_type::get_mul_type(type_a, type_b);469470if (type == glsl_type::error_type) {471_mesa_glsl_error(loc, state,472"size mismatch for matrix multiplication");473}474475return type;476}477478479/* "All other cases are illegal."480*/481_mesa_glsl_error(loc, state, "type mismatch");482return glsl_type::error_type;483}484485486static const struct glsl_type *487unary_arithmetic_result_type(const struct glsl_type *type,488struct _mesa_glsl_parse_state *state, YYLTYPE *loc)489{490/* From GLSL 1.50 spec, page 57:491*492* "The arithmetic unary operators negate (-), post- and pre-increment493* and decrement (-- and ++) operate on integer or floating-point494* values (including vectors and matrices). All unary operators work495* component-wise on their operands. These result with the same type496* they operated on."497*/498if (!type->is_numeric()) {499_mesa_glsl_error(loc, state,500"operands to arithmetic operators must be numeric");501return glsl_type::error_type;502}503504return type;505}506507/**508* \brief Return the result type of a bit-logic operation.509*510* If the given types to the bit-logic operator are invalid, return511* glsl_type::error_type.512*513* \param value_a LHS of bit-logic op514* \param value_b RHS of bit-logic op515*/516static const struct glsl_type *517bit_logic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,518ast_operators op,519struct _mesa_glsl_parse_state *state, YYLTYPE *loc)520{521const glsl_type *type_a = value_a->type;522const glsl_type *type_b = value_b->type;523524if (!state->check_bitwise_operations_allowed(loc)) {525return glsl_type::error_type;526}527528/* From page 50 (page 56 of PDF) of GLSL 1.30 spec:529*530* "The bitwise operators and (&), exclusive-or (^), and inclusive-or531* (|). The operands must be of type signed or unsigned integers or532* integer vectors."533*/534if (!type_a->is_integer_32_64()) {535_mesa_glsl_error(loc, state, "LHS of `%s' must be an integer",536ast_expression::operator_string(op));537return glsl_type::error_type;538}539if (!type_b->is_integer_32_64()) {540_mesa_glsl_error(loc, state, "RHS of `%s' must be an integer",541ast_expression::operator_string(op));542return glsl_type::error_type;543}544545/* Prior to GLSL 4.0 / GL_ARB_gpu_shader5, implicit conversions didn't546* make sense for bitwise operations, as they don't operate on floats.547*548* GLSL 4.0 added implicit int -> uint conversions, which are relevant549* here. It wasn't clear whether or not we should apply them to bitwise550* operations. However, Khronos has decided that they should in future551* language revisions. Applications also rely on this behavior. We opt552* to apply them in general, but issue a portability warning.553*554* See https://www.khronos.org/bugzilla/show_bug.cgi?id=1405555*/556if (type_a->base_type != type_b->base_type) {557if (!apply_implicit_conversion(type_a, value_b, state)558&& !apply_implicit_conversion(type_b, value_a, state)) {559_mesa_glsl_error(loc, state,560"could not implicitly convert operands to "561"`%s` operator",562ast_expression::operator_string(op));563return glsl_type::error_type;564} else {565_mesa_glsl_warning(loc, state,566"some implementations may not support implicit "567"int -> uint conversions for `%s' operators; "568"consider casting explicitly for portability",569ast_expression::operator_string(op));570}571type_a = value_a->type;572type_b = value_b->type;573}574575/* "The fundamental types of the operands (signed or unsigned) must576* match,"577*/578if (type_a->base_type != type_b->base_type) {579_mesa_glsl_error(loc, state, "operands of `%s' must have the same "580"base type", ast_expression::operator_string(op));581return glsl_type::error_type;582}583584/* "The operands cannot be vectors of differing size." */585if (type_a->is_vector() &&586type_b->is_vector() &&587type_a->vector_elements != type_b->vector_elements) {588_mesa_glsl_error(loc, state, "operands of `%s' cannot be vectors of "589"different sizes", ast_expression::operator_string(op));590return glsl_type::error_type;591}592593/* "If one operand is a scalar and the other a vector, the scalar is594* applied component-wise to the vector, resulting in the same type as595* the vector. The fundamental types of the operands [...] will be the596* resulting fundamental type."597*/598if (type_a->is_scalar())599return type_b;600else601return type_a;602}603604static const struct glsl_type *605modulus_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,606struct _mesa_glsl_parse_state *state, YYLTYPE *loc)607{608const glsl_type *type_a = value_a->type;609const glsl_type *type_b = value_b->type;610611if (!state->EXT_gpu_shader4_enable &&612!state->check_version(130, 300, loc, "operator '%%' is reserved")) {613return glsl_type::error_type;614}615616/* Section 5.9 (Expressions) of the GLSL 4.00 specification says:617*618* "The operator modulus (%) operates on signed or unsigned integers or619* integer vectors."620*/621if (!type_a->is_integer_32_64()) {622_mesa_glsl_error(loc, state, "LHS of operator %% must be an integer");623return glsl_type::error_type;624}625if (!type_b->is_integer_32_64()) {626_mesa_glsl_error(loc, state, "RHS of operator %% must be an integer");627return glsl_type::error_type;628}629630/* "If the fundamental types in the operands do not match, then the631* conversions from section 4.1.10 "Implicit Conversions" are applied632* to create matching types."633*634* Note that GLSL 4.00 (and GL_ARB_gpu_shader5) introduced implicit635* int -> uint conversion rules. Prior to that, there were no implicit636* conversions. So it's harmless to apply them universally - no implicit637* conversions will exist. If the types don't match, we'll receive false,638* and raise an error, satisfying the GLSL 1.50 spec, page 56:639*640* "The operand types must both be signed or unsigned."641*/642if (!apply_implicit_conversion(type_a, value_b, state) &&643!apply_implicit_conversion(type_b, value_a, state)) {644_mesa_glsl_error(loc, state,645"could not implicitly convert operands to "646"modulus (%%) operator");647return glsl_type::error_type;648}649type_a = value_a->type;650type_b = value_b->type;651652/* "The operands cannot be vectors of differing size. If one operand is653* a scalar and the other vector, then the scalar is applied component-654* wise to the vector, resulting in the same type as the vector. If both655* are vectors of the same size, the result is computed component-wise."656*/657if (type_a->is_vector()) {658if (!type_b->is_vector()659|| (type_a->vector_elements == type_b->vector_elements))660return type_a;661} else662return type_b;663664/* "The operator modulus (%) is not defined for any other data types665* (non-integer types)."666*/667_mesa_glsl_error(loc, state, "type mismatch");668return glsl_type::error_type;669}670671672static const struct glsl_type *673relational_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,674struct _mesa_glsl_parse_state *state, YYLTYPE *loc)675{676const glsl_type *type_a = value_a->type;677const glsl_type *type_b = value_b->type;678679/* From GLSL 1.50 spec, page 56:680* "The relational operators greater than (>), less than (<), greater681* than or equal (>=), and less than or equal (<=) operate only on682* scalar integer and scalar floating-point expressions."683*/684if (!type_a->is_numeric()685|| !type_b->is_numeric()686|| !type_a->is_scalar()687|| !type_b->is_scalar()) {688_mesa_glsl_error(loc, state,689"operands to relational operators must be scalar and "690"numeric");691return glsl_type::error_type;692}693694/* "Either the operands' types must match, or the conversions from695* Section 4.1.10 "Implicit Conversions" will be applied to the integer696* operand, after which the types must match."697*/698if (!apply_implicit_conversion(type_a, value_b, state)699&& !apply_implicit_conversion(type_b, value_a, state)) {700_mesa_glsl_error(loc, state,701"could not implicitly convert operands to "702"relational operator");703return glsl_type::error_type;704}705type_a = value_a->type;706type_b = value_b->type;707708if (type_a->base_type != type_b->base_type) {709_mesa_glsl_error(loc, state, "base type mismatch");710return glsl_type::error_type;711}712713/* "The result is scalar Boolean."714*/715return glsl_type::bool_type;716}717718/**719* \brief Return the result type of a bit-shift operation.720*721* If the given types to the bit-shift operator are invalid, return722* glsl_type::error_type.723*724* \param type_a Type of LHS of bit-shift op725* \param type_b Type of RHS of bit-shift op726*/727static const struct glsl_type *728shift_result_type(const struct glsl_type *type_a,729const struct glsl_type *type_b,730ast_operators op,731struct _mesa_glsl_parse_state *state, YYLTYPE *loc)732{733if (!state->check_bitwise_operations_allowed(loc)) {734return glsl_type::error_type;735}736737/* From page 50 (page 56 of the PDF) of the GLSL 1.30 spec:738*739* "The shift operators (<<) and (>>). For both operators, the operands740* must be signed or unsigned integers or integer vectors. One operand741* can be signed while the other is unsigned."742*/743if (!type_a->is_integer_32_64()) {744_mesa_glsl_error(loc, state, "LHS of operator %s must be an integer or "745"integer vector", ast_expression::operator_string(op));746return glsl_type::error_type;747748}749if (!type_b->is_integer_32()) {750_mesa_glsl_error(loc, state, "RHS of operator %s must be an integer or "751"integer vector", ast_expression::operator_string(op));752return glsl_type::error_type;753}754755/* "If the first operand is a scalar, the second operand has to be756* a scalar as well."757*/758if (type_a->is_scalar() && !type_b->is_scalar()) {759_mesa_glsl_error(loc, state, "if the first operand of %s is scalar, the "760"second must be scalar as well",761ast_expression::operator_string(op));762return glsl_type::error_type;763}764765/* If both operands are vectors, check that they have same number of766* elements.767*/768if (type_a->is_vector() &&769type_b->is_vector() &&770type_a->vector_elements != type_b->vector_elements) {771_mesa_glsl_error(loc, state, "vector operands to operator %s must "772"have same number of elements",773ast_expression::operator_string(op));774return glsl_type::error_type;775}776777/* "In all cases, the resulting type will be the same type as the left778* operand."779*/780return type_a;781}782783/**784* Returns the innermost array index expression in an rvalue tree.785* This is the largest indexing level -- if an array of blocks, then786* it is the block index rather than an indexing expression for an787* array-typed member of an array of blocks.788*/789static ir_rvalue *790find_innermost_array_index(ir_rvalue *rv)791{792ir_dereference_array *last = NULL;793while (rv) {794if (rv->as_dereference_array()) {795last = rv->as_dereference_array();796rv = last->array;797} else if (rv->as_dereference_record())798rv = rv->as_dereference_record()->record;799else if (rv->as_swizzle())800rv = rv->as_swizzle()->val;801else802rv = NULL;803}804805if (last)806return last->array_index;807808return NULL;809}810811/**812* Validates that a value can be assigned to a location with a specified type813*814* Validates that \c rhs can be assigned to some location. If the types are815* not an exact match but an automatic conversion is possible, \c rhs will be816* converted.817*818* \return819* \c NULL if \c rhs cannot be assigned to a location with type \c lhs_type.820* Otherwise the actual RHS to be assigned will be returned. This may be821* \c rhs, or it may be \c rhs after some type conversion.822*823* \note824* In addition to being used for assignments, this function is used to825* type-check return values.826*/827static ir_rvalue *828validate_assignment(struct _mesa_glsl_parse_state *state,829YYLTYPE loc, ir_rvalue *lhs,830ir_rvalue *rhs, bool is_initializer)831{832/* If there is already some error in the RHS, just return it. Anything833* else will lead to an avalanche of error message back to the user.834*/835if (rhs->type->is_error())836return rhs;837838/* In the Tessellation Control Shader:839* If a per-vertex output variable is used as an l-value, it is an error840* if the expression indicating the vertex number is not the identifier841* `gl_InvocationID`.842*/843if (state->stage == MESA_SHADER_TESS_CTRL && !lhs->type->is_error()) {844ir_variable *var = lhs->variable_referenced();845if (var && var->data.mode == ir_var_shader_out && !var->data.patch) {846ir_rvalue *index = find_innermost_array_index(lhs);847ir_variable *index_var = index ? index->variable_referenced() : NULL;848if (!index_var || strcmp(index_var->name, "gl_InvocationID") != 0) {849_mesa_glsl_error(&loc, state,850"Tessellation control shader outputs can only "851"be indexed by gl_InvocationID");852return NULL;853}854}855}856857/* If the types are identical, the assignment can trivially proceed.858*/859if (rhs->type == lhs->type)860return rhs;861862/* If the array element types are the same and the LHS is unsized,863* the assignment is okay for initializers embedded in variable864* declarations.865*866* Note: Whole-array assignments are not permitted in GLSL 1.10, but this867* is handled by ir_dereference::is_lvalue.868*/869const glsl_type *lhs_t = lhs->type;870const glsl_type *rhs_t = rhs->type;871bool unsized_array = false;872while(lhs_t->is_array()) {873if (rhs_t == lhs_t)874break; /* the rest of the inner arrays match so break out early */875if (!rhs_t->is_array()) {876unsized_array = false;877break; /* number of dimensions mismatch */878}879if (lhs_t->length == rhs_t->length) {880lhs_t = lhs_t->fields.array;881rhs_t = rhs_t->fields.array;882continue;883} else if (lhs_t->is_unsized_array()) {884unsized_array = true;885} else {886unsized_array = false;887break; /* sized array mismatch */888}889lhs_t = lhs_t->fields.array;890rhs_t = rhs_t->fields.array;891}892if (unsized_array) {893if (is_initializer) {894if (rhs->type->get_scalar_type() == lhs->type->get_scalar_type())895return rhs;896} else {897_mesa_glsl_error(&loc, state,898"implicitly sized arrays cannot be assigned");899return NULL;900}901}902903/* Check for implicit conversion in GLSL 1.20 */904if (apply_implicit_conversion(lhs->type, rhs, state)) {905if (rhs->type == lhs->type)906return rhs;907}908909_mesa_glsl_error(&loc, state,910"%s of type %s cannot be assigned to "911"variable of type %s",912is_initializer ? "initializer" : "value",913rhs->type->name, lhs->type->name);914915return NULL;916}917918static void919mark_whole_array_access(ir_rvalue *access)920{921ir_dereference_variable *deref = access->as_dereference_variable();922923if (deref && deref->var) {924deref->var->data.max_array_access = deref->type->length - 1;925}926}927928static bool929do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,930const char *non_lvalue_description,931ir_rvalue *lhs, ir_rvalue *rhs,932ir_rvalue **out_rvalue, bool needs_rvalue,933bool is_initializer,934YYLTYPE lhs_loc)935{936void *ctx = state;937bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());938939ir_variable *lhs_var = lhs->variable_referenced();940if (lhs_var)941lhs_var->data.assigned = true;942943bool omit_assignment = false;944if (!error_emitted) {945if (non_lvalue_description != NULL) {946_mesa_glsl_error(&lhs_loc, state,947"assignment to %s",948non_lvalue_description);949error_emitted = true;950} else if (lhs_var != NULL && (lhs_var->data.read_only ||951(lhs_var->data.mode == ir_var_shader_storage &&952lhs_var->data.memory_read_only))) {953/* We can have memory_read_only set on both images and buffer variables,954* but in the former there is a distinction between assignments to955* the variable itself (read_only) and to the memory they point to956* (memory_read_only), while in the case of buffer variables there is957* no such distinction, that is why this check here is limited to958* buffer variables alone.959*/960961if (state->ignore_write_to_readonly_var)962omit_assignment = true;963else {964_mesa_glsl_error(&lhs_loc, state,965"assignment to read-only variable '%s'",966lhs_var->name);967error_emitted = true;968}969} else if (lhs->type->is_array() &&970!state->check_version(state->allow_glsl_120_subset_in_110 ? 110 : 120,971300, &lhs_loc,972"whole array assignment forbidden")) {973/* From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:974*975* "Other binary or unary expressions, non-dereferenced976* arrays, function names, swizzles with repeated fields,977* and constants cannot be l-values."978*979* The restriction on arrays is lifted in GLSL 1.20 and GLSL ES 3.00.980*/981error_emitted = true;982} else if (!lhs->is_lvalue(state)) {983_mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");984error_emitted = true;985}986}987988ir_rvalue *new_rhs =989validate_assignment(state, lhs_loc, lhs, rhs, is_initializer);990if (new_rhs != NULL) {991rhs = new_rhs;992993/* If the LHS array was not declared with a size, it takes it size from994* the RHS. If the LHS is an l-value and a whole array, it must be a995* dereference of a variable. Any other case would require that the LHS996* is either not an l-value or not a whole array.997*/998if (lhs->type->is_unsized_array()) {999ir_dereference *const d = lhs->as_dereference();10001001assert(d != NULL);10021003ir_variable *const var = d->variable_referenced();10041005assert(var != NULL);10061007if (var->data.max_array_access >= rhs->type->array_size()) {1008/* FINISHME: This should actually log the location of the RHS. */1009_mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "1010"previous access",1011var->data.max_array_access);1012}10131014var->type = glsl_type::get_array_instance(lhs->type->fields.array,1015rhs->type->array_size());1016d->type = var->type;1017}1018if (lhs->type->is_array()) {1019mark_whole_array_access(rhs);1020mark_whole_array_access(lhs);1021}1022} else {1023error_emitted = true;1024}10251026if (omit_assignment) {1027*out_rvalue = needs_rvalue ? ir_rvalue::error_value(ctx) : NULL;1028return error_emitted;1029}10301031/* Most callers of do_assignment (assign, add_assign, pre_inc/dec,1032* but not post_inc) need the converted assigned value as an rvalue1033* to handle things like:1034*1035* i = j += 1;1036*/1037if (needs_rvalue) {1038ir_rvalue *rvalue;1039if (!error_emitted) {1040ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",1041ir_var_temporary);1042instructions->push_tail(var);1043instructions->push_tail(assign(var, rhs));10441045ir_dereference_variable *deref_var =1046new(ctx) ir_dereference_variable(var);1047instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var));1048rvalue = new(ctx) ir_dereference_variable(var);1049} else {1050rvalue = ir_rvalue::error_value(ctx);1051}1052*out_rvalue = rvalue;1053} else {1054if (!error_emitted)1055instructions->push_tail(new(ctx) ir_assignment(lhs, rhs));1056*out_rvalue = NULL;1057}10581059return error_emitted;1060}10611062static ir_rvalue *1063get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)1064{1065void *ctx = ralloc_parent(lvalue);1066ir_variable *var;10671068var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",1069ir_var_temporary);1070instructions->push_tail(var);10711072instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),1073lvalue));10741075return new(ctx) ir_dereference_variable(var);1076}107710781079ir_rvalue *1080ast_node::hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)1081{1082(void) instructions;1083(void) state;10841085return NULL;1086}10871088bool1089ast_node::has_sequence_subexpression() const1090{1091return false;1092}10931094void1095ast_node::set_is_lhs(bool /* new_value */)1096{1097}10981099void1100ast_function_expression::hir_no_rvalue(exec_list *instructions,1101struct _mesa_glsl_parse_state *state)1102{1103(void)hir(instructions, state);1104}11051106void1107ast_aggregate_initializer::hir_no_rvalue(exec_list *instructions,1108struct _mesa_glsl_parse_state *state)1109{1110(void)hir(instructions, state);1111}11121113static ir_rvalue *1114do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)1115{1116int join_op;1117ir_rvalue *cmp = NULL;11181119if (operation == ir_binop_all_equal)1120join_op = ir_binop_logic_and;1121else1122join_op = ir_binop_logic_or;11231124switch (op0->type->base_type) {1125case GLSL_TYPE_FLOAT:1126case GLSL_TYPE_FLOAT16:1127case GLSL_TYPE_UINT:1128case GLSL_TYPE_INT:1129case GLSL_TYPE_BOOL:1130case GLSL_TYPE_DOUBLE:1131case GLSL_TYPE_UINT64:1132case GLSL_TYPE_INT64:1133case GLSL_TYPE_UINT16:1134case GLSL_TYPE_INT16:1135case GLSL_TYPE_UINT8:1136case GLSL_TYPE_INT8:1137return new(mem_ctx) ir_expression(operation, op0, op1);11381139case GLSL_TYPE_ARRAY: {1140for (unsigned int i = 0; i < op0->type->length; i++) {1141ir_rvalue *e0, *e1, *result;11421143e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),1144new(mem_ctx) ir_constant(i));1145e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),1146new(mem_ctx) ir_constant(i));1147result = do_comparison(mem_ctx, operation, e0, e1);11481149if (cmp) {1150cmp = new(mem_ctx) ir_expression(join_op, cmp, result);1151} else {1152cmp = result;1153}1154}11551156mark_whole_array_access(op0);1157mark_whole_array_access(op1);1158break;1159}11601161case GLSL_TYPE_STRUCT: {1162for (unsigned int i = 0; i < op0->type->length; i++) {1163ir_rvalue *e0, *e1, *result;1164const char *field_name = op0->type->fields.structure[i].name;11651166e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),1167field_name);1168e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),1169field_name);1170result = do_comparison(mem_ctx, operation, e0, e1);11711172if (cmp) {1173cmp = new(mem_ctx) ir_expression(join_op, cmp, result);1174} else {1175cmp = result;1176}1177}1178break;1179}11801181case GLSL_TYPE_ERROR:1182case GLSL_TYPE_VOID:1183case GLSL_TYPE_SAMPLER:1184case GLSL_TYPE_IMAGE:1185case GLSL_TYPE_INTERFACE:1186case GLSL_TYPE_ATOMIC_UINT:1187case GLSL_TYPE_SUBROUTINE:1188case GLSL_TYPE_FUNCTION:1189/* I assume a comparison of a struct containing a sampler just1190* ignores the sampler present in the type.1191*/1192break;1193}11941195if (cmp == NULL)1196cmp = new(mem_ctx) ir_constant(true);11971198return cmp;1199}12001201/* For logical operations, we want to ensure that the operands are1202* scalar booleans. If it isn't, emit an error and return a constant1203* boolean to avoid triggering cascading error messages.1204*/1205static ir_rvalue *1206get_scalar_boolean_operand(exec_list *instructions,1207struct _mesa_glsl_parse_state *state,1208ast_expression *parent_expr,1209int operand,1210const char *operand_name,1211bool *error_emitted)1212{1213ast_expression *expr = parent_expr->subexpressions[operand];1214void *ctx = state;1215ir_rvalue *val = expr->hir(instructions, state);12161217if (val->type->is_boolean() && val->type->is_scalar())1218return val;12191220if (!*error_emitted) {1221YYLTYPE loc = expr->get_location();1222_mesa_glsl_error(&loc, state, "%s of `%s' must be scalar boolean",1223operand_name,1224parent_expr->operator_string(parent_expr->oper));1225*error_emitted = true;1226}12271228return new(ctx) ir_constant(true);1229}12301231/**1232* If name refers to a builtin array whose maximum allowed size is less than1233* size, report an error and return true. Otherwise return false.1234*/1235void1236check_builtin_array_max_size(const char *name, unsigned size,1237YYLTYPE loc, struct _mesa_glsl_parse_state *state)1238{1239if ((strcmp("gl_TexCoord", name) == 0)1240&& (size > state->Const.MaxTextureCoords)) {1241/* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:1242*1243* "The size [of gl_TexCoord] can be at most1244* gl_MaxTextureCoords."1245*/1246_mesa_glsl_error(&loc, state, "`gl_TexCoord' array size cannot "1247"be larger than gl_MaxTextureCoords (%u)",1248state->Const.MaxTextureCoords);1249} else if (strcmp("gl_ClipDistance", name) == 0) {1250state->clip_dist_size = size;1251if (size + state->cull_dist_size > state->Const.MaxClipPlanes) {1252/* From section 7.1 (Vertex Shader Special Variables) of the1253* GLSL 1.30 spec:1254*1255* "The gl_ClipDistance array is predeclared as unsized and1256* must be sized by the shader either redeclaring it with a1257* size or indexing it only with integral constant1258* expressions. ... The size can be at most1259* gl_MaxClipDistances."1260*/1261_mesa_glsl_error(&loc, state, "`gl_ClipDistance' array size cannot "1262"be larger than gl_MaxClipDistances (%u)",1263state->Const.MaxClipPlanes);1264}1265} else if (strcmp("gl_CullDistance", name) == 0) {1266state->cull_dist_size = size;1267if (size + state->clip_dist_size > state->Const.MaxClipPlanes) {1268/* From the ARB_cull_distance spec:1269*1270* "The gl_CullDistance array is predeclared as unsized and1271* must be sized by the shader either redeclaring it with1272* a size or indexing it only with integral constant1273* expressions. The size determines the number and set of1274* enabled cull distances and can be at most1275* gl_MaxCullDistances."1276*/1277_mesa_glsl_error(&loc, state, "`gl_CullDistance' array size cannot "1278"be larger than gl_MaxCullDistances (%u)",1279state->Const.MaxClipPlanes);1280}1281}1282}12831284/**1285* Create the constant 1, of a which is appropriate for incrementing and1286* decrementing values of the given GLSL type. For example, if type is vec4,1287* this creates a constant value of 1.0 having type float.1288*1289* If the given type is invalid for increment and decrement operators, return1290* a floating point 1--the error will be detected later.1291*/1292static ir_rvalue *1293constant_one_for_inc_dec(void *ctx, const glsl_type *type)1294{1295switch (type->base_type) {1296case GLSL_TYPE_UINT:1297return new(ctx) ir_constant((unsigned) 1);1298case GLSL_TYPE_INT:1299return new(ctx) ir_constant(1);1300case GLSL_TYPE_UINT64:1301return new(ctx) ir_constant((uint64_t) 1);1302case GLSL_TYPE_INT64:1303return new(ctx) ir_constant((int64_t) 1);1304default:1305case GLSL_TYPE_FLOAT:1306return new(ctx) ir_constant(1.0f);1307}1308}13091310ir_rvalue *1311ast_expression::hir(exec_list *instructions,1312struct _mesa_glsl_parse_state *state)1313{1314return do_hir(instructions, state, true);1315}13161317void1318ast_expression::hir_no_rvalue(exec_list *instructions,1319struct _mesa_glsl_parse_state *state)1320{1321do_hir(instructions, state, false);1322}13231324void1325ast_expression::set_is_lhs(bool new_value)1326{1327/* is_lhs is tracked only to print "variable used uninitialized" warnings,1328* if we lack an identifier we can just skip it.1329*/1330if (this->primary_expression.identifier == NULL)1331return;13321333this->is_lhs = new_value;13341335/* We need to go through the subexpressions tree to cover cases like1336* ast_field_selection1337*/1338if (this->subexpressions[0] != NULL)1339this->subexpressions[0]->set_is_lhs(new_value);1340}13411342ir_rvalue *1343ast_expression::do_hir(exec_list *instructions,1344struct _mesa_glsl_parse_state *state,1345bool needs_rvalue)1346{1347void *ctx = state;1348static const int operations[AST_NUM_OPERATORS] = {1349-1, /* ast_assign doesn't convert to ir_expression. */1350-1, /* ast_plus doesn't convert to ir_expression. */1351ir_unop_neg,1352ir_binop_add,1353ir_binop_sub,1354ir_binop_mul,1355ir_binop_div,1356ir_binop_mod,1357ir_binop_lshift,1358ir_binop_rshift,1359ir_binop_less,1360ir_binop_less, /* This is correct. See the ast_greater case below. */1361ir_binop_gequal, /* This is correct. See the ast_lequal case below. */1362ir_binop_gequal,1363ir_binop_all_equal,1364ir_binop_any_nequal,1365ir_binop_bit_and,1366ir_binop_bit_xor,1367ir_binop_bit_or,1368ir_unop_bit_not,1369ir_binop_logic_and,1370ir_binop_logic_xor,1371ir_binop_logic_or,1372ir_unop_logic_not,13731374/* Note: The following block of expression types actually convert1375* to multiple IR instructions.1376*/1377ir_binop_mul, /* ast_mul_assign */1378ir_binop_div, /* ast_div_assign */1379ir_binop_mod, /* ast_mod_assign */1380ir_binop_add, /* ast_add_assign */1381ir_binop_sub, /* ast_sub_assign */1382ir_binop_lshift, /* ast_ls_assign */1383ir_binop_rshift, /* ast_rs_assign */1384ir_binop_bit_and, /* ast_and_assign */1385ir_binop_bit_xor, /* ast_xor_assign */1386ir_binop_bit_or, /* ast_or_assign */13871388-1, /* ast_conditional doesn't convert to ir_expression. */1389ir_binop_add, /* ast_pre_inc. */1390ir_binop_sub, /* ast_pre_dec. */1391ir_binop_add, /* ast_post_inc. */1392ir_binop_sub, /* ast_post_dec. */1393-1, /* ast_field_selection doesn't conv to ir_expression. */1394-1, /* ast_array_index doesn't convert to ir_expression. */1395-1, /* ast_function_call doesn't conv to ir_expression. */1396-1, /* ast_identifier doesn't convert to ir_expression. */1397-1, /* ast_int_constant doesn't convert to ir_expression. */1398-1, /* ast_uint_constant doesn't conv to ir_expression. */1399-1, /* ast_float_constant doesn't conv to ir_expression. */1400-1, /* ast_bool_constant doesn't conv to ir_expression. */1401-1, /* ast_sequence doesn't convert to ir_expression. */1402-1, /* ast_aggregate shouldn't ever even get here. */1403};1404ir_rvalue *result = NULL;1405ir_rvalue *op[3];1406const struct glsl_type *type, *orig_type;1407bool error_emitted = false;1408YYLTYPE loc;14091410loc = this->get_location();14111412switch (this->oper) {1413case ast_aggregate:1414unreachable("ast_aggregate: Should never get here.");14151416case ast_assign: {1417this->subexpressions[0]->set_is_lhs(true);1418op[0] = this->subexpressions[0]->hir(instructions, state);1419op[1] = this->subexpressions[1]->hir(instructions, state);14201421error_emitted =1422do_assignment(instructions, state,1423this->subexpressions[0]->non_lvalue_description,1424op[0], op[1], &result, needs_rvalue, false,1425this->subexpressions[0]->get_location());1426break;1427}14281429case ast_plus:1430op[0] = this->subexpressions[0]->hir(instructions, state);14311432type = unary_arithmetic_result_type(op[0]->type, state, & loc);14331434error_emitted = type->is_error();14351436result = op[0];1437break;14381439case ast_neg:1440op[0] = this->subexpressions[0]->hir(instructions, state);14411442type = unary_arithmetic_result_type(op[0]->type, state, & loc);14431444error_emitted = type->is_error();14451446result = new(ctx) ir_expression(operations[this->oper], type,1447op[0], NULL);1448break;14491450case ast_add:1451case ast_sub:1452case ast_mul:1453case ast_div:1454op[0] = this->subexpressions[0]->hir(instructions, state);1455op[1] = this->subexpressions[1]->hir(instructions, state);14561457type = arithmetic_result_type(op[0], op[1],1458(this->oper == ast_mul),1459state, & loc);1460error_emitted = type->is_error();14611462result = new(ctx) ir_expression(operations[this->oper], type,1463op[0], op[1]);1464break;14651466case ast_mod:1467op[0] = this->subexpressions[0]->hir(instructions, state);1468op[1] = this->subexpressions[1]->hir(instructions, state);14691470type = modulus_result_type(op[0], op[1], state, &loc);14711472assert(operations[this->oper] == ir_binop_mod);14731474result = new(ctx) ir_expression(operations[this->oper], type,1475op[0], op[1]);1476error_emitted = type->is_error();1477break;14781479case ast_lshift:1480case ast_rshift:1481if (!state->check_bitwise_operations_allowed(&loc)) {1482error_emitted = true;1483}14841485op[0] = this->subexpressions[0]->hir(instructions, state);1486op[1] = this->subexpressions[1]->hir(instructions, state);1487type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,1488&loc);1489result = new(ctx) ir_expression(operations[this->oper], type,1490op[0], op[1]);1491error_emitted = op[0]->type->is_error() || op[1]->type->is_error();1492break;14931494case ast_less:1495case ast_greater:1496case ast_lequal:1497case ast_gequal:1498op[0] = this->subexpressions[0]->hir(instructions, state);1499op[1] = this->subexpressions[1]->hir(instructions, state);15001501type = relational_result_type(op[0], op[1], state, & loc);15021503/* The relational operators must either generate an error or result1504* in a scalar boolean. See page 57 of the GLSL 1.50 spec.1505*/1506assert(type->is_error()1507|| (type->is_boolean() && type->is_scalar()));15081509/* Like NIR, GLSL IR does not have opcodes for > or <=. Instead, swap1510* the arguments and use < or >=.1511*/1512if (this->oper == ast_greater || this->oper == ast_lequal) {1513ir_rvalue *const tmp = op[0];1514op[0] = op[1];1515op[1] = tmp;1516}15171518result = new(ctx) ir_expression(operations[this->oper], type,1519op[0], op[1]);1520error_emitted = type->is_error();1521break;15221523case ast_nequal:1524case ast_equal:1525op[0] = this->subexpressions[0]->hir(instructions, state);1526op[1] = this->subexpressions[1]->hir(instructions, state);15271528/* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:1529*1530* "The equality operators equal (==), and not equal (!=)1531* operate on all types. They result in a scalar Boolean. If1532* the operand types do not match, then there must be a1533* conversion from Section 4.1.10 "Implicit Conversions"1534* applied to one operand that can make them match, in which1535* case this conversion is done."1536*/15371538if (op[0]->type == glsl_type::void_type || op[1]->type == glsl_type::void_type) {1539_mesa_glsl_error(& loc, state, "`%s': wrong operand types: "1540"no operation `%1$s' exists that takes a left-hand "1541"operand of type 'void' or a right operand of type "1542"'void'", (this->oper == ast_equal) ? "==" : "!=");1543error_emitted = true;1544} else if ((!apply_implicit_conversion(op[0]->type, op[1], state)1545&& !apply_implicit_conversion(op[1]->type, op[0], state))1546|| (op[0]->type != op[1]->type)) {1547_mesa_glsl_error(& loc, state, "operands of `%s' must have the same "1548"type", (this->oper == ast_equal) ? "==" : "!=");1549error_emitted = true;1550} else if ((op[0]->type->is_array() || op[1]->type->is_array()) &&1551!state->check_version(120, 300, &loc,1552"array comparisons forbidden")) {1553error_emitted = true;1554} else if ((op[0]->type->contains_subroutine() ||1555op[1]->type->contains_subroutine())) {1556_mesa_glsl_error(&loc, state, "subroutine comparisons forbidden");1557error_emitted = true;1558} else if ((op[0]->type->contains_opaque() ||1559op[1]->type->contains_opaque())) {1560_mesa_glsl_error(&loc, state, "opaque type comparisons forbidden");1561error_emitted = true;1562}15631564if (error_emitted) {1565result = new(ctx) ir_constant(false);1566} else {1567result = do_comparison(ctx, operations[this->oper], op[0], op[1]);1568assert(result->type == glsl_type::bool_type);1569}1570break;15711572case ast_bit_and:1573case ast_bit_xor:1574case ast_bit_or:1575op[0] = this->subexpressions[0]->hir(instructions, state);1576op[1] = this->subexpressions[1]->hir(instructions, state);1577type = bit_logic_result_type(op[0], op[1], this->oper, state, &loc);1578result = new(ctx) ir_expression(operations[this->oper], type,1579op[0], op[1]);1580error_emitted = op[0]->type->is_error() || op[1]->type->is_error();1581break;15821583case ast_bit_not:1584op[0] = this->subexpressions[0]->hir(instructions, state);15851586if (!state->check_bitwise_operations_allowed(&loc)) {1587error_emitted = true;1588}15891590if (!op[0]->type->is_integer_32_64()) {1591_mesa_glsl_error(&loc, state, "operand of `~' must be an integer");1592error_emitted = true;1593}15941595type = error_emitted ? glsl_type::error_type : op[0]->type;1596result = new(ctx) ir_expression(ir_unop_bit_not, type, op[0], NULL);1597break;15981599case ast_logic_and: {1600exec_list rhs_instructions;1601op[0] = get_scalar_boolean_operand(instructions, state, this, 0,1602"LHS", &error_emitted);1603op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,1604"RHS", &error_emitted);16051606if (rhs_instructions.is_empty()) {1607result = new(ctx) ir_expression(ir_binop_logic_and, op[0], op[1]);1608} else {1609ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,1610"and_tmp",1611ir_var_temporary);1612instructions->push_tail(tmp);16131614ir_if *const stmt = new(ctx) ir_if(op[0]);1615instructions->push_tail(stmt);16161617stmt->then_instructions.append_list(&rhs_instructions);1618ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);1619ir_assignment *const then_assign =1620new(ctx) ir_assignment(then_deref, op[1]);1621stmt->then_instructions.push_tail(then_assign);16221623ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);1624ir_assignment *const else_assign =1625new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false));1626stmt->else_instructions.push_tail(else_assign);16271628result = new(ctx) ir_dereference_variable(tmp);1629}1630break;1631}16321633case ast_logic_or: {1634exec_list rhs_instructions;1635op[0] = get_scalar_boolean_operand(instructions, state, this, 0,1636"LHS", &error_emitted);1637op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,1638"RHS", &error_emitted);16391640if (rhs_instructions.is_empty()) {1641result = new(ctx) ir_expression(ir_binop_logic_or, op[0], op[1]);1642} else {1643ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,1644"or_tmp",1645ir_var_temporary);1646instructions->push_tail(tmp);16471648ir_if *const stmt = new(ctx) ir_if(op[0]);1649instructions->push_tail(stmt);16501651ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);1652ir_assignment *const then_assign =1653new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true));1654stmt->then_instructions.push_tail(then_assign);16551656stmt->else_instructions.append_list(&rhs_instructions);1657ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);1658ir_assignment *const else_assign =1659new(ctx) ir_assignment(else_deref, op[1]);1660stmt->else_instructions.push_tail(else_assign);16611662result = new(ctx) ir_dereference_variable(tmp);1663}1664break;1665}16661667case ast_logic_xor:1668/* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:1669*1670* "The logical binary operators and (&&), or ( | | ), and1671* exclusive or (^^). They operate only on two Boolean1672* expressions and result in a Boolean expression."1673*/1674op[0] = get_scalar_boolean_operand(instructions, state, this, 0, "LHS",1675&error_emitted);1676op[1] = get_scalar_boolean_operand(instructions, state, this, 1, "RHS",1677&error_emitted);16781679result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,1680op[0], op[1]);1681break;16821683case ast_logic_not:1684op[0] = get_scalar_boolean_operand(instructions, state, this, 0,1685"operand", &error_emitted);16861687result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,1688op[0], NULL);1689break;16901691case ast_mul_assign:1692case ast_div_assign:1693case ast_add_assign:1694case ast_sub_assign: {1695this->subexpressions[0]->set_is_lhs(true);1696op[0] = this->subexpressions[0]->hir(instructions, state);1697op[1] = this->subexpressions[1]->hir(instructions, state);16981699orig_type = op[0]->type;17001701/* Break out if operand types were not parsed successfully. */1702if ((op[0]->type == glsl_type::error_type ||1703op[1]->type == glsl_type::error_type)) {1704error_emitted = true;1705break;1706}17071708type = arithmetic_result_type(op[0], op[1],1709(this->oper == ast_mul_assign),1710state, & loc);17111712if (type != orig_type) {1713_mesa_glsl_error(& loc, state,1714"could not implicitly convert "1715"%s to %s", type->name, orig_type->name);1716type = glsl_type::error_type;1717}17181719ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,1720op[0], op[1]);17211722error_emitted =1723do_assignment(instructions, state,1724this->subexpressions[0]->non_lvalue_description,1725op[0]->clone(ctx, NULL), temp_rhs,1726&result, needs_rvalue, false,1727this->subexpressions[0]->get_location());17281729/* GLSL 1.10 does not allow array assignment. However, we don't have to1730* explicitly test for this because none of the binary expression1731* operators allow array operands either.1732*/17331734break;1735}17361737case ast_mod_assign: {1738this->subexpressions[0]->set_is_lhs(true);1739op[0] = this->subexpressions[0]->hir(instructions, state);1740op[1] = this->subexpressions[1]->hir(instructions, state);17411742orig_type = op[0]->type;1743type = modulus_result_type(op[0], op[1], state, &loc);17441745if (type != orig_type) {1746_mesa_glsl_error(& loc, state,1747"could not implicitly convert "1748"%s to %s", type->name, orig_type->name);1749type = glsl_type::error_type;1750}17511752assert(operations[this->oper] == ir_binop_mod);17531754ir_rvalue *temp_rhs;1755temp_rhs = new(ctx) ir_expression(operations[this->oper], type,1756op[0], op[1]);17571758error_emitted =1759do_assignment(instructions, state,1760this->subexpressions[0]->non_lvalue_description,1761op[0]->clone(ctx, NULL), temp_rhs,1762&result, needs_rvalue, false,1763this->subexpressions[0]->get_location());1764break;1765}17661767case ast_ls_assign:1768case ast_rs_assign: {1769this->subexpressions[0]->set_is_lhs(true);1770op[0] = this->subexpressions[0]->hir(instructions, state);1771op[1] = this->subexpressions[1]->hir(instructions, state);1772type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,1773&loc);1774ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],1775type, op[0], op[1]);1776error_emitted =1777do_assignment(instructions, state,1778this->subexpressions[0]->non_lvalue_description,1779op[0]->clone(ctx, NULL), temp_rhs,1780&result, needs_rvalue, false,1781this->subexpressions[0]->get_location());1782break;1783}17841785case ast_and_assign:1786case ast_xor_assign:1787case ast_or_assign: {1788this->subexpressions[0]->set_is_lhs(true);1789op[0] = this->subexpressions[0]->hir(instructions, state);1790op[1] = this->subexpressions[1]->hir(instructions, state);17911792orig_type = op[0]->type;1793type = bit_logic_result_type(op[0], op[1], this->oper, state, &loc);17941795if (type != orig_type) {1796_mesa_glsl_error(& loc, state,1797"could not implicitly convert "1798"%s to %s", type->name, orig_type->name);1799type = glsl_type::error_type;1800}18011802ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],1803type, op[0], op[1]);1804error_emitted =1805do_assignment(instructions, state,1806this->subexpressions[0]->non_lvalue_description,1807op[0]->clone(ctx, NULL), temp_rhs,1808&result, needs_rvalue, false,1809this->subexpressions[0]->get_location());1810break;1811}18121813case ast_conditional: {1814/* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:1815*1816* "The ternary selection operator (?:). It operates on three1817* expressions (exp1 ? exp2 : exp3). This operator evaluates the1818* first expression, which must result in a scalar Boolean."1819*/1820op[0] = get_scalar_boolean_operand(instructions, state, this, 0,1821"condition", &error_emitted);18221823/* The :? operator is implemented by generating an anonymous temporary1824* followed by an if-statement. The last instruction in each branch of1825* the if-statement assigns a value to the anonymous temporary. This1826* temporary is the r-value of the expression.1827*/1828exec_list then_instructions;1829exec_list else_instructions;18301831op[1] = this->subexpressions[1]->hir(&then_instructions, state);1832op[2] = this->subexpressions[2]->hir(&else_instructions, state);18331834/* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:1835*1836* "The second and third expressions can be any type, as1837* long their types match, or there is a conversion in1838* Section 4.1.10 "Implicit Conversions" that can be applied1839* to one of the expressions to make their types match. This1840* resulting matching type is the type of the entire1841* expression."1842*/1843if ((!apply_implicit_conversion(op[1]->type, op[2], state)1844&& !apply_implicit_conversion(op[2]->type, op[1], state))1845|| (op[1]->type != op[2]->type)) {1846YYLTYPE loc = this->subexpressions[1]->get_location();18471848_mesa_glsl_error(& loc, state, "second and third operands of ?: "1849"operator must have matching types");1850error_emitted = true;1851type = glsl_type::error_type;1852} else {1853type = op[1]->type;1854}18551856/* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:1857*1858* "The second and third expressions must be the same type, but can1859* be of any type other than an array."1860*/1861if (type->is_array() &&1862!state->check_version(120, 300, &loc,1863"second and third operands of ?: operator "1864"cannot be arrays")) {1865error_emitted = true;1866}18671868/* From section 4.1.7 of the GLSL 4.50 spec (Opaque Types):1869*1870* "Except for array indexing, structure member selection, and1871* parentheses, opaque variables are not allowed to be operands in1872* expressions; such use results in a compile-time error."1873*/1874if (type->contains_opaque()) {1875if (!(state->has_bindless() && (type->is_image() || type->is_sampler()))) {1876_mesa_glsl_error(&loc, state, "variables of type %s cannot be "1877"operands of the ?: operator", type->name);1878error_emitted = true;1879}1880}18811882ir_constant *cond_val = op[0]->constant_expression_value(ctx);18831884if (then_instructions.is_empty()1885&& else_instructions.is_empty()1886&& cond_val != NULL) {1887result = cond_val->value.b[0] ? op[1] : op[2];1888} else {1889/* The copy to conditional_tmp reads the whole array. */1890if (type->is_array()) {1891mark_whole_array_access(op[1]);1892mark_whole_array_access(op[2]);1893}18941895ir_variable *const tmp =1896new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);1897instructions->push_tail(tmp);18981899ir_if *const stmt = new(ctx) ir_if(op[0]);1900instructions->push_tail(stmt);19011902then_instructions.move_nodes_to(& stmt->then_instructions);1903ir_dereference *const then_deref =1904new(ctx) ir_dereference_variable(tmp);1905ir_assignment *const then_assign =1906new(ctx) ir_assignment(then_deref, op[1]);1907stmt->then_instructions.push_tail(then_assign);19081909else_instructions.move_nodes_to(& stmt->else_instructions);1910ir_dereference *const else_deref =1911new(ctx) ir_dereference_variable(tmp);1912ir_assignment *const else_assign =1913new(ctx) ir_assignment(else_deref, op[2]);1914stmt->else_instructions.push_tail(else_assign);19151916result = new(ctx) ir_dereference_variable(tmp);1917}1918break;1919}19201921case ast_pre_inc:1922case ast_pre_dec: {1923this->non_lvalue_description = (this->oper == ast_pre_inc)1924? "pre-increment operation" : "pre-decrement operation";19251926op[0] = this->subexpressions[0]->hir(instructions, state);1927op[1] = constant_one_for_inc_dec(ctx, op[0]->type);19281929type = arithmetic_result_type(op[0], op[1], false, state, & loc);19301931ir_rvalue *temp_rhs;1932temp_rhs = new(ctx) ir_expression(operations[this->oper], type,1933op[0], op[1]);19341935error_emitted =1936do_assignment(instructions, state,1937this->subexpressions[0]->non_lvalue_description,1938op[0]->clone(ctx, NULL), temp_rhs,1939&result, needs_rvalue, false,1940this->subexpressions[0]->get_location());1941break;1942}19431944case ast_post_inc:1945case ast_post_dec: {1946this->non_lvalue_description = (this->oper == ast_post_inc)1947? "post-increment operation" : "post-decrement operation";1948op[0] = this->subexpressions[0]->hir(instructions, state);1949op[1] = constant_one_for_inc_dec(ctx, op[0]->type);19501951error_emitted = op[0]->type->is_error() || op[1]->type->is_error();19521953if (error_emitted) {1954result = ir_rvalue::error_value(ctx);1955break;1956}19571958type = arithmetic_result_type(op[0], op[1], false, state, & loc);19591960ir_rvalue *temp_rhs;1961temp_rhs = new(ctx) ir_expression(operations[this->oper], type,1962op[0], op[1]);19631964/* Get a temporary of a copy of the lvalue before it's modified.1965* This may get thrown away later.1966*/1967result = get_lvalue_copy(instructions, op[0]->clone(ctx, NULL));19681969ir_rvalue *junk_rvalue;1970error_emitted =1971do_assignment(instructions, state,1972this->subexpressions[0]->non_lvalue_description,1973op[0]->clone(ctx, NULL), temp_rhs,1974&junk_rvalue, false, false,1975this->subexpressions[0]->get_location());19761977break;1978}19791980case ast_field_selection:1981result = _mesa_ast_field_selection_to_hir(this, instructions, state);1982break;19831984case ast_array_index: {1985YYLTYPE index_loc = subexpressions[1]->get_location();19861987/* Getting if an array is being used uninitialized is beyond what we get1988* from ir_value.data.assigned. Setting is_lhs as true would force to1989* not raise a uninitialized warning when using an array1990*/1991subexpressions[0]->set_is_lhs(true);1992op[0] = subexpressions[0]->hir(instructions, state);1993op[1] = subexpressions[1]->hir(instructions, state);19941995result = _mesa_ast_array_index_to_hir(ctx, state, op[0], op[1],1996loc, index_loc);19971998if (result->type->is_error())1999error_emitted = true;20002001break;2002}20032004case ast_unsized_array_dim:2005unreachable("ast_unsized_array_dim: Should never get here.");20062007case ast_function_call:2008/* Should *NEVER* get here. ast_function_call should always be handled2009* by ast_function_expression::hir.2010*/2011unreachable("ast_function_call: handled elsewhere ");20122013case ast_identifier: {2014/* ast_identifier can appear several places in a full abstract syntax2015* tree. This particular use must be at location specified in the grammar2016* as 'variable_identifier'.2017*/2018ir_variable *var =2019state->symbols->get_variable(this->primary_expression.identifier);20202021if (var == NULL) {2022/* the identifier might be a subroutine name */2023char *sub_name;2024sub_name = ralloc_asprintf(ctx, "%s_%s", _mesa_shader_stage_to_subroutine_prefix(state->stage), this->primary_expression.identifier);2025var = state->symbols->get_variable(sub_name);2026ralloc_free(sub_name);2027}20282029if (var != NULL) {2030var->data.used = true;2031result = new(ctx) ir_dereference_variable(var);20322033if ((var->data.mode == ir_var_auto || var->data.mode == ir_var_shader_out)2034&& !this->is_lhs2035&& result->variable_referenced()->data.assigned != true2036&& !is_gl_identifier(var->name)) {2037_mesa_glsl_warning(&loc, state, "`%s' used uninitialized",2038this->primary_expression.identifier);2039}20402041/* From the EXT_shader_framebuffer_fetch spec:2042*2043* "Unless the GL_EXT_shader_framebuffer_fetch extension has been2044* enabled in addition, it's an error to use gl_LastFragData if it2045* hasn't been explicitly redeclared with layout(noncoherent)."2046*/2047if (var->data.fb_fetch_output && var->data.memory_coherent &&2048!state->EXT_shader_framebuffer_fetch_enable) {2049_mesa_glsl_error(&loc, state,2050"invalid use of framebuffer fetch output not "2051"qualified with layout(noncoherent)");2052}20532054} else {2055_mesa_glsl_error(& loc, state, "`%s' undeclared",2056this->primary_expression.identifier);20572058result = ir_rvalue::error_value(ctx);2059error_emitted = true;2060}2061break;2062}20632064case ast_int_constant:2065result = new(ctx) ir_constant(this->primary_expression.int_constant);2066break;20672068case ast_uint_constant:2069result = new(ctx) ir_constant(this->primary_expression.uint_constant);2070break;20712072case ast_float_constant:2073result = new(ctx) ir_constant(this->primary_expression.float_constant);2074break;20752076case ast_bool_constant:2077result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));2078break;20792080case ast_double_constant:2081result = new(ctx) ir_constant(this->primary_expression.double_constant);2082break;20832084case ast_uint64_constant:2085result = new(ctx) ir_constant(this->primary_expression.uint64_constant);2086break;20872088case ast_int64_constant:2089result = new(ctx) ir_constant(this->primary_expression.int64_constant);2090break;20912092case ast_sequence: {2093/* It should not be possible to generate a sequence in the AST without2094* any expressions in it.2095*/2096assert(!this->expressions.is_empty());20972098/* The r-value of a sequence is the last expression in the sequence. If2099* the other expressions in the sequence do not have side-effects (and2100* therefore add instructions to the instruction list), they get dropped2101* on the floor.2102*/2103exec_node *previous_tail = NULL;2104YYLTYPE previous_operand_loc = loc;21052106foreach_list_typed (ast_node, ast, link, &this->expressions) {2107/* If one of the operands of comma operator does not generate any2108* code, we want to emit a warning. At each pass through the loop2109* previous_tail will point to the last instruction in the stream2110* *before* processing the previous operand. Naturally,2111* instructions->get_tail_raw() will point to the last instruction in2112* the stream *after* processing the previous operand. If the two2113* pointers match, then the previous operand had no effect.2114*2115* The warning behavior here differs slightly from GCC. GCC will2116* only emit a warning if none of the left-hand operands have an2117* effect. However, it will emit a warning for each. I believe that2118* there are some cases in C (especially with GCC extensions) where2119* it is useful to have an intermediate step in a sequence have no2120* effect, but I don't think these cases exist in GLSL. Either way,2121* it would be a giant hassle to replicate that behavior.2122*/2123if (previous_tail == instructions->get_tail_raw()) {2124_mesa_glsl_warning(&previous_operand_loc, state,2125"left-hand operand of comma expression has "2126"no effect");2127}21282129/* The tail is directly accessed instead of using the get_tail()2130* method for performance reasons. get_tail() has extra code to2131* return NULL when the list is empty. We don't care about that2132* here, so using get_tail_raw() is fine.2133*/2134previous_tail = instructions->get_tail_raw();2135previous_operand_loc = ast->get_location();21362137result = ast->hir(instructions, state);2138}21392140/* Any errors should have already been emitted in the loop above.2141*/2142error_emitted = true;2143break;2144}2145}2146type = NULL; /* use result->type, not type. */2147assert(error_emitted || (result != NULL || !needs_rvalue));21482149if (result && result->type->is_error() && !error_emitted)2150_mesa_glsl_error(& loc, state, "type mismatch");21512152return result;2153}21542155bool2156ast_expression::has_sequence_subexpression() const2157{2158switch (this->oper) {2159case ast_plus:2160case ast_neg:2161case ast_bit_not:2162case ast_logic_not:2163case ast_pre_inc:2164case ast_pre_dec:2165case ast_post_inc:2166case ast_post_dec:2167return this->subexpressions[0]->has_sequence_subexpression();21682169case ast_assign:2170case ast_add:2171case ast_sub:2172case ast_mul:2173case ast_div:2174case ast_mod:2175case ast_lshift:2176case ast_rshift:2177case ast_less:2178case ast_greater:2179case ast_lequal:2180case ast_gequal:2181case ast_nequal:2182case ast_equal:2183case ast_bit_and:2184case ast_bit_xor:2185case ast_bit_or:2186case ast_logic_and:2187case ast_logic_or:2188case ast_logic_xor:2189case ast_array_index:2190case ast_mul_assign:2191case ast_div_assign:2192case ast_add_assign:2193case ast_sub_assign:2194case ast_mod_assign:2195case ast_ls_assign:2196case ast_rs_assign:2197case ast_and_assign:2198case ast_xor_assign:2199case ast_or_assign:2200return this->subexpressions[0]->has_sequence_subexpression() ||2201this->subexpressions[1]->has_sequence_subexpression();22022203case ast_conditional:2204return this->subexpressions[0]->has_sequence_subexpression() ||2205this->subexpressions[1]->has_sequence_subexpression() ||2206this->subexpressions[2]->has_sequence_subexpression();22072208case ast_sequence:2209return true;22102211case ast_field_selection:2212case ast_identifier:2213case ast_int_constant:2214case ast_uint_constant:2215case ast_float_constant:2216case ast_bool_constant:2217case ast_double_constant:2218case ast_int64_constant:2219case ast_uint64_constant:2220return false;22212222case ast_aggregate:2223return false;22242225case ast_function_call:2226unreachable("should be handled by ast_function_expression::hir");22272228case ast_unsized_array_dim:2229unreachable("ast_unsized_array_dim: Should never get here.");2230}22312232return false;2233}22342235ir_rvalue *2236ast_expression_statement::hir(exec_list *instructions,2237struct _mesa_glsl_parse_state *state)2238{2239/* It is possible to have expression statements that don't have an2240* expression. This is the solitary semicolon:2241*2242* for (i = 0; i < 5; i++)2243* ;2244*2245* In this case the expression will be NULL. Test for NULL and don't do2246* anything in that case.2247*/2248if (expression != NULL)2249expression->hir_no_rvalue(instructions, state);22502251/* Statements do not have r-values.2252*/2253return NULL;2254}225522562257ir_rvalue *2258ast_compound_statement::hir(exec_list *instructions,2259struct _mesa_glsl_parse_state *state)2260{2261if (new_scope)2262state->symbols->push_scope();22632264foreach_list_typed (ast_node, ast, link, &this->statements)2265ast->hir(instructions, state);22662267if (new_scope)2268state->symbols->pop_scope();22692270/* Compound statements do not have r-values.2271*/2272return NULL;2273}22742275/**2276* Evaluate the given exec_node (which should be an ast_node representing2277* a single array dimension) and return its integer value.2278*/2279static unsigned2280process_array_size(exec_node *node,2281struct _mesa_glsl_parse_state *state)2282{2283void *mem_ctx = state;22842285exec_list dummy_instructions;22862287ast_node *array_size = exec_node_data(ast_node, node, link);22882289/**2290* Dimensions other than the outermost dimension can by unsized if they2291* are immediately sized by a constructor or initializer.2292*/2293if (((ast_expression*)array_size)->oper == ast_unsized_array_dim)2294return 0;22952296ir_rvalue *const ir = array_size->hir(& dummy_instructions, state);2297YYLTYPE loc = array_size->get_location();22982299if (ir == NULL) {2300_mesa_glsl_error(& loc, state,2301"array size could not be resolved");2302return 0;2303}23042305if (!ir->type->is_integer_32()) {2306_mesa_glsl_error(& loc, state,2307"array size must be integer type");2308return 0;2309}23102311if (!ir->type->is_scalar()) {2312_mesa_glsl_error(& loc, state,2313"array size must be scalar type");2314return 0;2315}23162317ir_constant *const size = ir->constant_expression_value(mem_ctx);2318if (size == NULL ||2319(state->is_version(120, 300) &&2320array_size->has_sequence_subexpression())) {2321_mesa_glsl_error(& loc, state, "array size must be a "2322"constant valued expression");2323return 0;2324}23252326if (size->value.i[0] <= 0) {2327_mesa_glsl_error(& loc, state, "array size must be > 0");2328return 0;2329}23302331assert(size->type == ir->type);23322333/* If the array size is const (and we've verified that2334* it is) then no instructions should have been emitted2335* when we converted it to HIR. If they were emitted,2336* then either the array size isn't const after all, or2337* we are emitting unnecessary instructions.2338*/2339assert(dummy_instructions.is_empty());23402341return size->value.u[0];2342}23432344static const glsl_type *2345process_array_type(YYLTYPE *loc, const glsl_type *base,2346ast_array_specifier *array_specifier,2347struct _mesa_glsl_parse_state *state)2348{2349const glsl_type *array_type = base;23502351if (array_specifier != NULL) {2352if (base->is_array()) {23532354/* From page 19 (page 25) of the GLSL 1.20 spec:2355*2356* "Only one-dimensional arrays may be declared."2357*/2358if (!state->check_arrays_of_arrays_allowed(loc)) {2359return glsl_type::error_type;2360}2361}23622363for (exec_node *node = array_specifier->array_dimensions.get_tail_raw();2364!node->is_head_sentinel(); node = node->prev) {2365unsigned array_size = process_array_size(node, state);2366array_type = glsl_type::get_array_instance(array_type, array_size);2367}2368}23692370return array_type;2371}23722373static bool2374precision_qualifier_allowed(const glsl_type *type)2375{2376/* Precision qualifiers apply to floating point, integer and opaque2377* types.2378*2379* Section 4.5.2 (Precision Qualifiers) of the GLSL 1.30 spec says:2380* "Any floating point or any integer declaration can have the type2381* preceded by one of these precision qualifiers [...] Literal2382* constants do not have precision qualifiers. Neither do Boolean2383* variables.2384*2385* Section 4.5 (Precision and Precision Qualifiers) of the GLSL 1.302386* spec also says:2387*2388* "Precision qualifiers are added for code portability with OpenGL2389* ES, not for functionality. They have the same syntax as in OpenGL2390* ES."2391*2392* Section 8 (Built-In Functions) of the GLSL ES 1.00 spec says:2393*2394* "uniform lowp sampler2D sampler;2395* highp vec2 coord;2396* ...2397* lowp vec4 col = texture2D (sampler, coord);2398* // texture2D returns lowp"2399*2400* From this, we infer that GLSL 1.30 (and later) should allow precision2401* qualifiers on sampler types just like float and integer types.2402*/2403const glsl_type *const t = type->without_array();24042405return (t->is_float() || t->is_integer_32() || t->contains_opaque()) &&2406!t->is_struct();2407}24082409const glsl_type *2410ast_type_specifier::glsl_type(const char **name,2411struct _mesa_glsl_parse_state *state) const2412{2413const struct glsl_type *type;24142415if (this->type != NULL)2416type = this->type;2417else if (structure)2418type = structure->type;2419else2420type = state->symbols->get_type(this->type_name);2421*name = this->type_name;24222423YYLTYPE loc = this->get_location();2424type = process_array_type(&loc, type, this->array_specifier, state);24252426return type;2427}24282429/**2430* From the OpenGL ES 3.0 spec, 4.5.4 Default Precision Qualifiers:2431*2432* "The precision statement2433*2434* precision precision-qualifier type;2435*2436* can be used to establish a default precision qualifier. The type field can2437* be either int or float or any of the sampler types, (...) If type is float,2438* the directive applies to non-precision-qualified floating point type2439* (scalar, vector, and matrix) declarations. If type is int, the directive2440* applies to all non-precision-qualified integer type (scalar, vector, signed,2441* and unsigned) declarations."2442*2443* We use the symbol table to keep the values of the default precisions for2444* each 'type' in each scope and we use the 'type' string from the precision2445* statement as key in the symbol table. When we want to retrieve the default2446* precision associated with a given glsl_type we need to know the type string2447* associated with it. This is what this function returns.2448*/2449static const char *2450get_type_name_for_precision_qualifier(const glsl_type *type)2451{2452switch (type->base_type) {2453case GLSL_TYPE_FLOAT:2454return "float";2455case GLSL_TYPE_UINT:2456case GLSL_TYPE_INT:2457return "int";2458case GLSL_TYPE_ATOMIC_UINT:2459return "atomic_uint";2460case GLSL_TYPE_IMAGE:2461FALLTHROUGH;2462case GLSL_TYPE_SAMPLER: {2463const unsigned type_idx =2464type->sampler_array + 2 * type->sampler_shadow;2465const unsigned offset = type->is_sampler() ? 0 : 4;2466assert(type_idx < 4);2467switch (type->sampled_type) {2468case GLSL_TYPE_FLOAT:2469switch (type->sampler_dimensionality) {2470case GLSL_SAMPLER_DIM_1D: {2471assert(type->is_sampler());2472static const char *const names[4] = {2473"sampler1D", "sampler1DArray",2474"sampler1DShadow", "sampler1DArrayShadow"2475};2476return names[type_idx];2477}2478case GLSL_SAMPLER_DIM_2D: {2479static const char *const names[8] = {2480"sampler2D", "sampler2DArray",2481"sampler2DShadow", "sampler2DArrayShadow",2482"image2D", "image2DArray", NULL, NULL2483};2484return names[offset + type_idx];2485}2486case GLSL_SAMPLER_DIM_3D: {2487static const char *const names[8] = {2488"sampler3D", NULL, NULL, NULL,2489"image3D", NULL, NULL, NULL2490};2491return names[offset + type_idx];2492}2493case GLSL_SAMPLER_DIM_CUBE: {2494static const char *const names[8] = {2495"samplerCube", "samplerCubeArray",2496"samplerCubeShadow", "samplerCubeArrayShadow",2497"imageCube", NULL, NULL, NULL2498};2499return names[offset + type_idx];2500}2501case GLSL_SAMPLER_DIM_MS: {2502assert(type->is_sampler());2503static const char *const names[4] = {2504"sampler2DMS", "sampler2DMSArray", NULL, NULL2505};2506return names[type_idx];2507}2508case GLSL_SAMPLER_DIM_RECT: {2509assert(type->is_sampler());2510static const char *const names[4] = {2511"samplerRect", NULL, "samplerRectShadow", NULL2512};2513return names[type_idx];2514}2515case GLSL_SAMPLER_DIM_BUF: {2516static const char *const names[8] = {2517"samplerBuffer", NULL, NULL, NULL,2518"imageBuffer", NULL, NULL, NULL2519};2520return names[offset + type_idx];2521}2522case GLSL_SAMPLER_DIM_EXTERNAL: {2523assert(type->is_sampler());2524static const char *const names[4] = {2525"samplerExternalOES", NULL, NULL, NULL2526};2527return names[type_idx];2528}2529default:2530unreachable("Unsupported sampler/image dimensionality");2531} /* sampler/image float dimensionality */2532break;2533case GLSL_TYPE_INT:2534switch (type->sampler_dimensionality) {2535case GLSL_SAMPLER_DIM_1D: {2536assert(type->is_sampler());2537static const char *const names[4] = {2538"isampler1D", "isampler1DArray", NULL, NULL2539};2540return names[type_idx];2541}2542case GLSL_SAMPLER_DIM_2D: {2543static const char *const names[8] = {2544"isampler2D", "isampler2DArray", NULL, NULL,2545"iimage2D", "iimage2DArray", NULL, NULL2546};2547return names[offset + type_idx];2548}2549case GLSL_SAMPLER_DIM_3D: {2550static const char *const names[8] = {2551"isampler3D", NULL, NULL, NULL,2552"iimage3D", NULL, NULL, NULL2553};2554return names[offset + type_idx];2555}2556case GLSL_SAMPLER_DIM_CUBE: {2557static const char *const names[8] = {2558"isamplerCube", "isamplerCubeArray", NULL, NULL,2559"iimageCube", NULL, NULL, NULL2560};2561return names[offset + type_idx];2562}2563case GLSL_SAMPLER_DIM_MS: {2564assert(type->is_sampler());2565static const char *const names[4] = {2566"isampler2DMS", "isampler2DMSArray", NULL, NULL2567};2568return names[type_idx];2569}2570case GLSL_SAMPLER_DIM_RECT: {2571assert(type->is_sampler());2572static const char *const names[4] = {2573"isamplerRect", NULL, "isamplerRectShadow", NULL2574};2575return names[type_idx];2576}2577case GLSL_SAMPLER_DIM_BUF: {2578static const char *const names[8] = {2579"isamplerBuffer", NULL, NULL, NULL,2580"iimageBuffer", NULL, NULL, NULL2581};2582return names[offset + type_idx];2583}2584default:2585unreachable("Unsupported isampler/iimage dimensionality");2586} /* sampler/image int dimensionality */2587break;2588case GLSL_TYPE_UINT:2589switch (type->sampler_dimensionality) {2590case GLSL_SAMPLER_DIM_1D: {2591assert(type->is_sampler());2592static const char *const names[4] = {2593"usampler1D", "usampler1DArray", NULL, NULL2594};2595return names[type_idx];2596}2597case GLSL_SAMPLER_DIM_2D: {2598static const char *const names[8] = {2599"usampler2D", "usampler2DArray", NULL, NULL,2600"uimage2D", "uimage2DArray", NULL, NULL2601};2602return names[offset + type_idx];2603}2604case GLSL_SAMPLER_DIM_3D: {2605static const char *const names[8] = {2606"usampler3D", NULL, NULL, NULL,2607"uimage3D", NULL, NULL, NULL2608};2609return names[offset + type_idx];2610}2611case GLSL_SAMPLER_DIM_CUBE: {2612static const char *const names[8] = {2613"usamplerCube", "usamplerCubeArray", NULL, NULL,2614"uimageCube", NULL, NULL, NULL2615};2616return names[offset + type_idx];2617}2618case GLSL_SAMPLER_DIM_MS: {2619assert(type->is_sampler());2620static const char *const names[4] = {2621"usampler2DMS", "usampler2DMSArray", NULL, NULL2622};2623return names[type_idx];2624}2625case GLSL_SAMPLER_DIM_RECT: {2626assert(type->is_sampler());2627static const char *const names[4] = {2628"usamplerRect", NULL, "usamplerRectShadow", NULL2629};2630return names[type_idx];2631}2632case GLSL_SAMPLER_DIM_BUF: {2633static const char *const names[8] = {2634"usamplerBuffer", NULL, NULL, NULL,2635"uimageBuffer", NULL, NULL, NULL2636};2637return names[offset + type_idx];2638}2639default:2640unreachable("Unsupported usampler/uimage dimensionality");2641} /* sampler/image uint dimensionality */2642break;2643default:2644unreachable("Unsupported sampler/image type");2645} /* sampler/image type */2646break;2647} /* GLSL_TYPE_SAMPLER/GLSL_TYPE_IMAGE */2648break;2649default:2650unreachable("Unsupported type");2651} /* base type */2652}26532654static unsigned2655select_gles_precision(unsigned qual_precision,2656const glsl_type *type,2657struct _mesa_glsl_parse_state *state, YYLTYPE *loc)2658{2659/* Precision qualifiers do not have any meaning in Desktop GLSL.2660* In GLES we take the precision from the type qualifier if present,2661* otherwise, if the type of the variable allows precision qualifiers at2662* all, we look for the default precision qualifier for that type in the2663* current scope.2664*/2665assert(state->es_shader);26662667unsigned precision = GLSL_PRECISION_NONE;2668if (qual_precision) {2669precision = qual_precision;2670} else if (precision_qualifier_allowed(type)) {2671const char *type_name =2672get_type_name_for_precision_qualifier(type->without_array());2673assert(type_name != NULL);26742675precision =2676state->symbols->get_default_precision_qualifier(type_name);2677if (precision == ast_precision_none) {2678_mesa_glsl_error(loc, state,2679"No precision specified in this scope for type `%s'",2680type->name);2681}2682}268326842685/* Section 4.1.7.3 (Atomic Counters) of the GLSL ES 3.10 spec says:2686*2687* "The default precision of all atomic types is highp. It is an error to2688* declare an atomic type with a different precision or to specify the2689* default precision for an atomic type to be lowp or mediump."2690*/2691if (type->is_atomic_uint() && precision != ast_precision_high) {2692_mesa_glsl_error(loc, state,2693"atomic_uint can only have highp precision qualifier");2694}26952696return precision;2697}26982699const glsl_type *2700ast_fully_specified_type::glsl_type(const char **name,2701struct _mesa_glsl_parse_state *state) const2702{2703return this->specifier->glsl_type(name, state);2704}27052706/**2707* Determine whether a toplevel variable declaration declares a varying. This2708* function operates by examining the variable's mode and the shader target,2709* so it correctly identifies linkage variables regardless of whether they are2710* declared using the deprecated "varying" syntax or the new "in/out" syntax.2711*2712* Passing a non-toplevel variable declaration (e.g. a function parameter) to2713* this function will produce undefined results.2714*/2715static bool2716is_varying_var(ir_variable *var, gl_shader_stage target)2717{2718switch (target) {2719case MESA_SHADER_VERTEX:2720return var->data.mode == ir_var_shader_out;2721case MESA_SHADER_FRAGMENT:2722return var->data.mode == ir_var_shader_in ||2723(var->data.mode == ir_var_system_value &&2724var->data.location == SYSTEM_VALUE_FRAG_COORD);2725default:2726return var->data.mode == ir_var_shader_out || var->data.mode == ir_var_shader_in;2727}2728}27292730static bool2731is_allowed_invariant(ir_variable *var, struct _mesa_glsl_parse_state *state)2732{2733if (is_varying_var(var, state->stage))2734return true;27352736/* From Section 4.6.1 ("The Invariant Qualifier") GLSL 1.20 spec:2737* "Only variables output from a vertex shader can be candidates2738* for invariance".2739*/2740if (!state->is_version(130, 100))2741return false;27422743/*2744* Later specs remove this language - so allowed invariant2745* on fragment shader outputs as well.2746*/2747if (state->stage == MESA_SHADER_FRAGMENT &&2748var->data.mode == ir_var_shader_out)2749return true;2750return false;2751}27522753static void2754validate_component_layout_for_type(struct _mesa_glsl_parse_state *state,2755YYLTYPE *loc, const glsl_type *type,2756unsigned qual_component)2757{2758type = type->without_array();2759unsigned components = type->component_slots();27602761if (type->is_matrix() || type->is_struct()) {2762_mesa_glsl_error(loc, state, "component layout qualifier "2763"cannot be applied to a matrix, a structure, "2764"a block, or an array containing any of these.");2765} else if (components > 4 && type->is_64bit()) {2766_mesa_glsl_error(loc, state, "component layout qualifier "2767"cannot be applied to dvec%u.",2768components / 2);2769} else if (qual_component != 0 && (qual_component + components - 1) > 3) {2770_mesa_glsl_error(loc, state, "component overflow (%u > 3)",2771(qual_component + components - 1));2772} else if (qual_component == 1 && type->is_64bit()) {2773/* We don't bother checking for 3 as it should be caught by the2774* overflow check above.2775*/2776_mesa_glsl_error(loc, state, "doubles cannot begin at component 1 or 3");2777}2778}27792780/**2781* Matrix layout qualifiers are only allowed on certain types2782*/2783static void2784validate_matrix_layout_for_type(struct _mesa_glsl_parse_state *state,2785YYLTYPE *loc,2786const glsl_type *type,2787ir_variable *var)2788{2789if (var && !var->is_in_buffer_block()) {2790/* Layout qualifiers may only apply to interface blocks and fields in2791* them.2792*/2793_mesa_glsl_error(loc, state,2794"uniform block layout qualifiers row_major and "2795"column_major may not be applied to variables "2796"outside of uniform blocks");2797} else if (!type->without_array()->is_matrix()) {2798/* The OpenGL ES 3.0 conformance tests did not originally allow2799* matrix layout qualifiers on non-matrices. However, the OpenGL2800* 4.4 and OpenGL ES 3.0 (revision TBD) specifications were2801* amended to specifically allow these layouts on all types. Emit2802* a warning so that people know their code may not be portable.2803*/2804_mesa_glsl_warning(loc, state,2805"uniform block layout qualifiers row_major and "2806"column_major applied to non-matrix types may "2807"be rejected by older compilers");2808}2809}28102811static bool2812validate_xfb_buffer_qualifier(YYLTYPE *loc,2813struct _mesa_glsl_parse_state *state,2814unsigned xfb_buffer) {2815if (xfb_buffer >= state->Const.MaxTransformFeedbackBuffers) {2816_mesa_glsl_error(loc, state,2817"invalid xfb_buffer specified %d is larger than "2818"MAX_TRANSFORM_FEEDBACK_BUFFERS - 1 (%d).",2819xfb_buffer,2820state->Const.MaxTransformFeedbackBuffers - 1);2821return false;2822}28232824return true;2825}28262827/* From the ARB_enhanced_layouts spec:2828*2829* "Variables and block members qualified with *xfb_offset* can be2830* scalars, vectors, matrices, structures, and (sized) arrays of these.2831* The offset must be a multiple of the size of the first component of2832* the first qualified variable or block member, or a compile-time error2833* results. Further, if applied to an aggregate containing a double,2834* the offset must also be a multiple of 8, and the space taken in the2835* buffer will be a multiple of 8.2836*/2837static bool2838validate_xfb_offset_qualifier(YYLTYPE *loc,2839struct _mesa_glsl_parse_state *state,2840int xfb_offset, const glsl_type *type,2841unsigned component_size) {2842const glsl_type *t_without_array = type->without_array();28432844if (xfb_offset != -1 && type->is_unsized_array()) {2845_mesa_glsl_error(loc, state,2846"xfb_offset can't be used with unsized arrays.");2847return false;2848}28492850/* Make sure nested structs don't contain unsized arrays, and validate2851* any xfb_offsets on interface members.2852*/2853if (t_without_array->is_struct() || t_without_array->is_interface())2854for (unsigned int i = 0; i < t_without_array->length; i++) {2855const glsl_type *member_t = t_without_array->fields.structure[i].type;28562857/* When the interface block doesn't have an xfb_offset qualifier then2858* we apply the component size rules at the member level.2859*/2860if (xfb_offset == -1)2861component_size = member_t->contains_double() ? 8 : 4;28622863int xfb_offset = t_without_array->fields.structure[i].offset;2864validate_xfb_offset_qualifier(loc, state, xfb_offset, member_t,2865component_size);2866}28672868/* Nested structs or interface block without offset may not have had an2869* offset applied yet so return.2870*/2871if (xfb_offset == -1) {2872return true;2873}28742875if (xfb_offset % component_size) {2876_mesa_glsl_error(loc, state,2877"invalid qualifier xfb_offset=%d must be a multiple "2878"of the first component size of the first qualified "2879"variable or block member. Or double if an aggregate "2880"that contains a double (%d).",2881xfb_offset, component_size);2882return false;2883}28842885return true;2886}28872888static bool2889validate_stream_qualifier(YYLTYPE *loc, struct _mesa_glsl_parse_state *state,2890unsigned stream)2891{2892if (stream >= state->ctx->Const.MaxVertexStreams) {2893_mesa_glsl_error(loc, state,2894"invalid stream specified %d is larger than "2895"MAX_VERTEX_STREAMS - 1 (%d).",2896stream, state->ctx->Const.MaxVertexStreams - 1);2897return false;2898}28992900return true;2901}29022903static void2904apply_explicit_binding(struct _mesa_glsl_parse_state *state,2905YYLTYPE *loc,2906ir_variable *var,2907const glsl_type *type,2908const ast_type_qualifier *qual)2909{2910if (!qual->flags.q.uniform && !qual->flags.q.buffer) {2911_mesa_glsl_error(loc, state,2912"the \"binding\" qualifier only applies to uniforms and "2913"shader storage buffer objects");2914return;2915}29162917unsigned qual_binding;2918if (!process_qualifier_constant(state, loc, "binding", qual->binding,2919&qual_binding)) {2920return;2921}29222923const struct gl_context *const ctx = state->ctx;2924unsigned elements = type->is_array() ? type->arrays_of_arrays_size() : 1;2925unsigned max_index = qual_binding + elements - 1;2926const glsl_type *base_type = type->without_array();29272928if (base_type->is_interface()) {2929/* UBOs. From page 60 of the GLSL 4.20 specification:2930* "If the binding point for any uniform block instance is less than zero,2931* or greater than or equal to the implementation-dependent maximum2932* number of uniform buffer bindings, a compilation error will occur.2933* When the binding identifier is used with a uniform block instanced as2934* an array of size N, all elements of the array from binding through2935* binding + N – 1 must be within this range."2936*2937* The implementation-dependent maximum is GL_MAX_UNIFORM_BUFFER_BINDINGS.2938*/2939if (qual->flags.q.uniform &&2940max_index >= ctx->Const.MaxUniformBufferBindings) {2941_mesa_glsl_error(loc, state, "layout(binding = %u) for %d UBOs exceeds "2942"the maximum number of UBO binding points (%d)",2943qual_binding, elements,2944ctx->Const.MaxUniformBufferBindings);2945return;2946}29472948/* SSBOs. From page 67 of the GLSL 4.30 specification:2949* "If the binding point for any uniform or shader storage block instance2950* is less than zero, or greater than or equal to the2951* implementation-dependent maximum number of uniform buffer bindings, a2952* compile-time error will occur. When the binding identifier is used2953* with a uniform or shader storage block instanced as an array of size2954* N, all elements of the array from binding through binding + N – 1 must2955* be within this range."2956*/2957if (qual->flags.q.buffer &&2958max_index >= ctx->Const.MaxShaderStorageBufferBindings) {2959_mesa_glsl_error(loc, state, "layout(binding = %u) for %d SSBOs exceeds "2960"the maximum number of SSBO binding points (%d)",2961qual_binding, elements,2962ctx->Const.MaxShaderStorageBufferBindings);2963return;2964}2965} else if (base_type->is_sampler()) {2966/* Samplers. From page 63 of the GLSL 4.20 specification:2967* "If the binding is less than zero, or greater than or equal to the2968* implementation-dependent maximum supported number of units, a2969* compilation error will occur. When the binding identifier is used2970* with an array of size N, all elements of the array from binding2971* through binding + N - 1 must be within this range."2972*/2973unsigned limit = ctx->Const.MaxCombinedTextureImageUnits;29742975if (max_index >= limit) {2976_mesa_glsl_error(loc, state, "layout(binding = %d) for %d samplers "2977"exceeds the maximum number of texture image units "2978"(%u)", qual_binding, elements, limit);29792980return;2981}2982} else if (base_type->contains_atomic()) {2983assert(ctx->Const.MaxAtomicBufferBindings <= MAX_COMBINED_ATOMIC_BUFFERS);2984if (qual_binding >= ctx->Const.MaxAtomicBufferBindings) {2985_mesa_glsl_error(loc, state, "layout(binding = %d) exceeds the "2986"maximum number of atomic counter buffer bindings "2987"(%u)", qual_binding,2988ctx->Const.MaxAtomicBufferBindings);29892990return;2991}2992} else if ((state->is_version(420, 310) ||2993state->ARB_shading_language_420pack_enable) &&2994base_type->is_image()) {2995assert(ctx->Const.MaxImageUnits <= MAX_IMAGE_UNITS);2996if (max_index >= ctx->Const.MaxImageUnits) {2997_mesa_glsl_error(loc, state, "Image binding %d exceeds the "2998"maximum number of image units (%d)", max_index,2999ctx->Const.MaxImageUnits);3000return;3001}30023003} else {3004_mesa_glsl_error(loc, state,3005"the \"binding\" qualifier only applies to uniform "3006"blocks, storage blocks, opaque variables, or arrays "3007"thereof");3008return;3009}30103011var->data.explicit_binding = true;3012var->data.binding = qual_binding;30133014return;3015}30163017static void3018validate_fragment_flat_interpolation_input(struct _mesa_glsl_parse_state *state,3019YYLTYPE *loc,3020const glsl_interp_mode interpolation,3021const struct glsl_type *var_type,3022ir_variable_mode mode)3023{3024if (state->stage != MESA_SHADER_FRAGMENT ||3025interpolation == INTERP_MODE_FLAT ||3026mode != ir_var_shader_in)3027return;30283029/* Integer fragment inputs must be qualified with 'flat'. In GLSL ES,3030* so must integer vertex outputs.3031*3032* From section 4.3.4 ("Inputs") of the GLSL 1.50 spec:3033* "Fragment shader inputs that are signed or unsigned integers or3034* integer vectors must be qualified with the interpolation qualifier3035* flat."3036*3037* From section 4.3.4 ("Input Variables") of the GLSL 3.00 ES spec:3038* "Fragment shader inputs that are, or contain, signed or unsigned3039* integers or integer vectors must be qualified with the3040* interpolation qualifier flat."3041*3042* From section 4.3.6 ("Output Variables") of the GLSL 3.00 ES spec:3043* "Vertex shader outputs that are, or contain, signed or unsigned3044* integers or integer vectors must be qualified with the3045* interpolation qualifier flat."3046*3047* Note that prior to GLSL 1.50, this requirement applied to vertex3048* outputs rather than fragment inputs. That creates problems in the3049* presence of geometry shaders, so we adopt the GLSL 1.50 rule for all3050* desktop GL shaders. For GLSL ES shaders, we follow the spec and3051* apply the restriction to both vertex outputs and fragment inputs.3052*3053* Note also that the desktop GLSL specs are missing the text "or3054* contain"; this is presumably an oversight, since there is no3055* reasonable way to interpolate a fragment shader input that contains3056* an integer. See Khronos bug #15671.3057*/3058if ((state->is_version(130, 300) || state->EXT_gpu_shader4_enable)3059&& var_type->contains_integer()) {3060_mesa_glsl_error(loc, state, "if a fragment input is (or contains) "3061"an integer, then it must be qualified with 'flat'");3062}30633064/* Double fragment inputs must be qualified with 'flat'.3065*3066* From the "Overview" of the ARB_gpu_shader_fp64 extension spec:3067* "This extension does not support interpolation of double-precision3068* values; doubles used as fragment shader inputs must be qualified as3069* "flat"."3070*3071* From section 4.3.4 ("Inputs") of the GLSL 4.00 spec:3072* "Fragment shader inputs that are signed or unsigned integers, integer3073* vectors, or any double-precision floating-point type must be3074* qualified with the interpolation qualifier flat."3075*3076* Note that the GLSL specs are missing the text "or contain"; this is3077* presumably an oversight. See Khronos bug #15671.3078*3079* The 'double' type does not exist in GLSL ES so far.3080*/3081if (state->has_double()3082&& var_type->contains_double()) {3083_mesa_glsl_error(loc, state, "if a fragment input is (or contains) "3084"a double, then it must be qualified with 'flat'");3085}30863087/* Bindless sampler/image fragment inputs must be qualified with 'flat'.3088*3089* From section 4.3.4 of the ARB_bindless_texture spec:3090*3091* "(modify last paragraph, p. 35, allowing samplers and images as3092* fragment shader inputs) ... Fragment inputs can only be signed and3093* unsigned integers and integer vectors, floating point scalars,3094* floating-point vectors, matrices, sampler and image types, or arrays3095* or structures of these. Fragment shader inputs that are signed or3096* unsigned integers, integer vectors, or any double-precision floating-3097* point type, or any sampler or image type must be qualified with the3098* interpolation qualifier "flat"."3099*/3100if (state->has_bindless()3101&& (var_type->contains_sampler() || var_type->contains_image())) {3102_mesa_glsl_error(loc, state, "if a fragment input is (or contains) "3103"a bindless sampler (or image), then it must be "3104"qualified with 'flat'");3105}3106}31073108static void3109validate_interpolation_qualifier(struct _mesa_glsl_parse_state *state,3110YYLTYPE *loc,3111const glsl_interp_mode interpolation,3112const struct ast_type_qualifier *qual,3113const struct glsl_type *var_type,3114ir_variable_mode mode)3115{3116/* Interpolation qualifiers can only apply to shader inputs or outputs, but3117* not to vertex shader inputs nor fragment shader outputs.3118*3119* From section 4.3 ("Storage Qualifiers") of the GLSL 1.30 spec:3120* "Outputs from a vertex shader (out) and inputs to a fragment3121* shader (in) can be further qualified with one or more of these3122* interpolation qualifiers"3123* ...3124* "These interpolation qualifiers may only precede the qualifiers in,3125* centroid in, out, or centroid out in a declaration. They do not apply3126* to the deprecated storage qualifiers varying or centroid3127* varying. They also do not apply to inputs into a vertex shader or3128* outputs from a fragment shader."3129*3130* From section 4.3 ("Storage Qualifiers") of the GLSL ES 3.00 spec:3131* "Outputs from a shader (out) and inputs to a shader (in) can be3132* further qualified with one of these interpolation qualifiers."3133* ...3134* "These interpolation qualifiers may only precede the qualifiers3135* in, centroid in, out, or centroid out in a declaration. They do3136* not apply to inputs into a vertex shader or outputs from a3137* fragment shader."3138*/3139if ((state->is_version(130, 300) || state->EXT_gpu_shader4_enable)3140&& interpolation != INTERP_MODE_NONE) {3141const char *i = interpolation_string(interpolation);3142if (mode != ir_var_shader_in && mode != ir_var_shader_out)3143_mesa_glsl_error(loc, state,3144"interpolation qualifier `%s' can only be applied to "3145"shader inputs or outputs.", i);31463147switch (state->stage) {3148case MESA_SHADER_VERTEX:3149if (mode == ir_var_shader_in) {3150_mesa_glsl_error(loc, state,3151"interpolation qualifier '%s' cannot be applied to "3152"vertex shader inputs", i);3153}3154break;3155case MESA_SHADER_FRAGMENT:3156if (mode == ir_var_shader_out) {3157_mesa_glsl_error(loc, state,3158"interpolation qualifier '%s' cannot be applied to "3159"fragment shader outputs", i);3160}3161break;3162default:3163break;3164}3165}31663167/* Interpolation qualifiers cannot be applied to 'centroid' and3168* 'centroid varying'.3169*3170* From section 4.3 ("Storage Qualifiers") of the GLSL 1.30 spec:3171* "interpolation qualifiers may only precede the qualifiers in,3172* centroid in, out, or centroid out in a declaration. They do not apply3173* to the deprecated storage qualifiers varying or centroid varying."3174*3175* These deprecated storage qualifiers do not exist in GLSL ES 3.00.3176*3177* GL_EXT_gpu_shader4 allows this.3178*/3179if (state->is_version(130, 0) && !state->EXT_gpu_shader4_enable3180&& interpolation != INTERP_MODE_NONE3181&& qual->flags.q.varying) {31823183const char *i = interpolation_string(interpolation);3184const char *s;3185if (qual->flags.q.centroid)3186s = "centroid varying";3187else3188s = "varying";31893190_mesa_glsl_error(loc, state,3191"qualifier '%s' cannot be applied to the "3192"deprecated storage qualifier '%s'", i, s);3193}31943195validate_fragment_flat_interpolation_input(state, loc, interpolation,3196var_type, mode);3197}31983199static glsl_interp_mode3200interpret_interpolation_qualifier(const struct ast_type_qualifier *qual,3201const struct glsl_type *var_type,3202ir_variable_mode mode,3203struct _mesa_glsl_parse_state *state,3204YYLTYPE *loc)3205{3206glsl_interp_mode interpolation;3207if (qual->flags.q.flat)3208interpolation = INTERP_MODE_FLAT;3209else if (qual->flags.q.noperspective)3210interpolation = INTERP_MODE_NOPERSPECTIVE;3211else if (qual->flags.q.smooth)3212interpolation = INTERP_MODE_SMOOTH;3213else3214interpolation = INTERP_MODE_NONE;32153216validate_interpolation_qualifier(state, loc,3217interpolation,3218qual, var_type, mode);32193220return interpolation;3221}322232233224static void3225apply_explicit_location(const struct ast_type_qualifier *qual,3226ir_variable *var,3227struct _mesa_glsl_parse_state *state,3228YYLTYPE *loc)3229{3230bool fail = false;32313232unsigned qual_location;3233if (!process_qualifier_constant(state, loc, "location", qual->location,3234&qual_location)) {3235return;3236}32373238/* Checks for GL_ARB_explicit_uniform_location. */3239if (qual->flags.q.uniform) {3240if (!state->check_explicit_uniform_location_allowed(loc, var))3241return;32423243const struct gl_context *const ctx = state->ctx;3244unsigned max_loc = qual_location + var->type->uniform_locations() - 1;32453246if (max_loc >= ctx->Const.MaxUserAssignableUniformLocations) {3247_mesa_glsl_error(loc, state, "location(s) consumed by uniform %s "3248">= MAX_UNIFORM_LOCATIONS (%u)", var->name,3249ctx->Const.MaxUserAssignableUniformLocations);3250return;3251}32523253var->data.explicit_location = true;3254var->data.location = qual_location;3255return;3256}32573258/* Between GL_ARB_explicit_attrib_location an3259* GL_ARB_separate_shader_objects, the inputs and outputs of any shader3260* stage can be assigned explicit locations. The checking here associates3261* the correct extension with the correct stage's input / output:3262*3263* input output3264* ----- ------3265* vertex explicit_loc sso3266* tess control sso sso3267* tess eval sso sso3268* geometry sso sso3269* fragment sso explicit_loc3270*/3271switch (state->stage) {3272case MESA_SHADER_VERTEX:3273if (var->data.mode == ir_var_shader_in) {3274if (!state->check_explicit_attrib_location_allowed(loc, var))3275return;32763277break;3278}32793280if (var->data.mode == ir_var_shader_out) {3281if (!state->check_separate_shader_objects_allowed(loc, var))3282return;32833284break;3285}32863287fail = true;3288break;32893290case MESA_SHADER_TESS_CTRL:3291case MESA_SHADER_TESS_EVAL:3292case MESA_SHADER_GEOMETRY:3293if (var->data.mode == ir_var_shader_in || var->data.mode == ir_var_shader_out) {3294if (!state->check_separate_shader_objects_allowed(loc, var))3295return;32963297break;3298}32993300fail = true;3301break;33023303case MESA_SHADER_FRAGMENT:3304if (var->data.mode == ir_var_shader_in) {3305if (!state->check_separate_shader_objects_allowed(loc, var))3306return;33073308break;3309}33103311if (var->data.mode == ir_var_shader_out) {3312if (!state->check_explicit_attrib_location_allowed(loc, var))3313return;33143315break;3316}33173318fail = true;3319break;33203321case MESA_SHADER_COMPUTE:3322_mesa_glsl_error(loc, state,3323"compute shader variables cannot be given "3324"explicit locations");3325return;3326default:3327fail = true;3328break;3329};33303331if (fail) {3332_mesa_glsl_error(loc, state,3333"%s cannot be given an explicit location in %s shader",3334mode_string(var),3335_mesa_shader_stage_to_string(state->stage));3336} else {3337var->data.explicit_location = true;33383339switch (state->stage) {3340case MESA_SHADER_VERTEX:3341var->data.location = (var->data.mode == ir_var_shader_in)3342? (qual_location + VERT_ATTRIB_GENERIC0)3343: (qual_location + VARYING_SLOT_VAR0);3344break;33453346case MESA_SHADER_TESS_CTRL:3347case MESA_SHADER_TESS_EVAL:3348case MESA_SHADER_GEOMETRY:3349if (var->data.patch)3350var->data.location = qual_location + VARYING_SLOT_PATCH0;3351else3352var->data.location = qual_location + VARYING_SLOT_VAR0;3353break;33543355case MESA_SHADER_FRAGMENT:3356var->data.location = (var->data.mode == ir_var_shader_out)3357? (qual_location + FRAG_RESULT_DATA0)3358: (qual_location + VARYING_SLOT_VAR0);3359break;3360default:3361assert(!"Unexpected shader type");3362break;3363}33643365/* Check if index was set for the uniform instead of the function */3366if (qual->flags.q.explicit_index && qual->is_subroutine_decl()) {3367_mesa_glsl_error(loc, state, "an index qualifier can only be "3368"used with subroutine functions");3369return;3370}33713372unsigned qual_index;3373if (qual->flags.q.explicit_index &&3374process_qualifier_constant(state, loc, "index", qual->index,3375&qual_index)) {3376/* From the GLSL 4.30 specification, section 4.4.2 (Output3377* Layout Qualifiers):3378*3379* "It is also a compile-time error if a fragment shader3380* sets a layout index to less than 0 or greater than 1."3381*3382* Older specifications don't mandate a behavior; we take3383* this as a clarification and always generate the error.3384*/3385if (qual_index > 1) {3386_mesa_glsl_error(loc, state,3387"explicit index may only be 0 or 1");3388} else {3389var->data.explicit_index = true;3390var->data.index = qual_index;3391}3392}3393}3394}33953396static bool3397validate_storage_for_sampler_image_types(ir_variable *var,3398struct _mesa_glsl_parse_state *state,3399YYLTYPE *loc)3400{3401/* From section 4.1.7 of the GLSL 4.40 spec:3402*3403* "[Opaque types] can only be declared as function3404* parameters or uniform-qualified variables."3405*3406* From section 4.1.7 of the ARB_bindless_texture spec:3407*3408* "Samplers may be declared as shader inputs and outputs, as uniform3409* variables, as temporary variables, and as function parameters."3410*3411* From section 4.1.X of the ARB_bindless_texture spec:3412*3413* "Images may be declared as shader inputs and outputs, as uniform3414* variables, as temporary variables, and as function parameters."3415*/3416if (state->has_bindless()) {3417if (var->data.mode != ir_var_auto &&3418var->data.mode != ir_var_uniform &&3419var->data.mode != ir_var_shader_in &&3420var->data.mode != ir_var_shader_out &&3421var->data.mode != ir_var_function_in &&3422var->data.mode != ir_var_function_out &&3423var->data.mode != ir_var_function_inout) {3424_mesa_glsl_error(loc, state, "bindless image/sampler variables may "3425"only be declared as shader inputs and outputs, as "3426"uniform variables, as temporary variables and as "3427"function parameters");3428return false;3429}3430} else {3431if (var->data.mode != ir_var_uniform &&3432var->data.mode != ir_var_function_in) {3433_mesa_glsl_error(loc, state, "image/sampler variables may only be "3434"declared as function parameters or "3435"uniform-qualified global variables");3436return false;3437}3438}3439return true;3440}34413442static bool3443validate_memory_qualifier_for_type(struct _mesa_glsl_parse_state *state,3444YYLTYPE *loc,3445const struct ast_type_qualifier *qual,3446const glsl_type *type)3447{3448/* From Section 4.10 (Memory Qualifiers) of the GLSL 4.50 spec:3449*3450* "Memory qualifiers are only supported in the declarations of image3451* variables, buffer variables, and shader storage blocks; it is an error3452* to use such qualifiers in any other declarations.3453*/3454if (!type->is_image() && !qual->flags.q.buffer) {3455if (qual->flags.q.read_only ||3456qual->flags.q.write_only ||3457qual->flags.q.coherent ||3458qual->flags.q._volatile ||3459qual->flags.q.restrict_flag) {3460_mesa_glsl_error(loc, state, "memory qualifiers may only be applied "3461"in the declarations of image variables, buffer "3462"variables, and shader storage blocks");3463return false;3464}3465}3466return true;3467}34683469static bool3470validate_image_format_qualifier_for_type(struct _mesa_glsl_parse_state *state,3471YYLTYPE *loc,3472const struct ast_type_qualifier *qual,3473const glsl_type *type)3474{3475/* From section 4.4.6.2 (Format Layout Qualifiers) of the GLSL 4.50 spec:3476*3477* "Format layout qualifiers can be used on image variable declarations3478* (those declared with a basic type having “image ” in its keyword)."3479*/3480if (!type->is_image() && qual->flags.q.explicit_image_format) {3481_mesa_glsl_error(loc, state, "format layout qualifiers may only be "3482"applied to images");3483return false;3484}3485return true;3486}34873488static void3489apply_image_qualifier_to_variable(const struct ast_type_qualifier *qual,3490ir_variable *var,3491struct _mesa_glsl_parse_state *state,3492YYLTYPE *loc)3493{3494const glsl_type *base_type = var->type->without_array();34953496if (!validate_image_format_qualifier_for_type(state, loc, qual, base_type) ||3497!validate_memory_qualifier_for_type(state, loc, qual, base_type))3498return;34993500if (!base_type->is_image())3501return;35023503if (!validate_storage_for_sampler_image_types(var, state, loc))3504return;35053506var->data.memory_read_only |= qual->flags.q.read_only;3507var->data.memory_write_only |= qual->flags.q.write_only;3508var->data.memory_coherent |= qual->flags.q.coherent;3509var->data.memory_volatile |= qual->flags.q._volatile;3510var->data.memory_restrict |= qual->flags.q.restrict_flag;35113512if (qual->flags.q.explicit_image_format) {3513if (var->data.mode == ir_var_function_in) {3514_mesa_glsl_error(loc, state, "format qualifiers cannot be used on "3515"image function parameters");3516}35173518if (qual->image_base_type != base_type->sampled_type) {3519_mesa_glsl_error(loc, state, "format qualifier doesn't match the base "3520"data type of the image");3521}35223523var->data.image_format = qual->image_format;3524} else if (state->has_image_load_formatted()) {3525if (var->data.mode == ir_var_uniform &&3526state->EXT_shader_image_load_formatted_warn) {3527_mesa_glsl_warning(loc, state, "GL_EXT_image_load_formatted used");3528}3529} else {3530if (var->data.mode == ir_var_uniform) {3531if (state->es_shader ||3532!(state->is_version(420, 310) || state->ARB_shader_image_load_store_enable)) {3533_mesa_glsl_error(loc, state, "all image uniforms must have a "3534"format layout qualifier");3535} else if (!qual->flags.q.write_only) {3536_mesa_glsl_error(loc, state, "image uniforms not qualified with "3537"`writeonly' must have a format layout qualifier");3538}3539}3540var->data.image_format = PIPE_FORMAT_NONE;3541}35423543/* From page 70 of the GLSL ES 3.1 specification:3544*3545* "Except for image variables qualified with the format qualifiers r32f,3546* r32i, and r32ui, image variables must specify either memory qualifier3547* readonly or the memory qualifier writeonly."3548*/3549if (state->es_shader &&3550var->data.image_format != PIPE_FORMAT_R32_FLOAT &&3551var->data.image_format != PIPE_FORMAT_R32_SINT &&3552var->data.image_format != PIPE_FORMAT_R32_UINT &&3553!var->data.memory_read_only &&3554!var->data.memory_write_only) {3555_mesa_glsl_error(loc, state, "image variables of format other than r32f, "3556"r32i or r32ui must be qualified `readonly' or "3557"`writeonly'");3558}3559}35603561static inline const char*3562get_layout_qualifier_string(bool origin_upper_left, bool pixel_center_integer)3563{3564if (origin_upper_left && pixel_center_integer)3565return "origin_upper_left, pixel_center_integer";3566else if (origin_upper_left)3567return "origin_upper_left";3568else if (pixel_center_integer)3569return "pixel_center_integer";3570else3571return " ";3572}35733574static inline bool3575is_conflicting_fragcoord_redeclaration(struct _mesa_glsl_parse_state *state,3576const struct ast_type_qualifier *qual)3577{3578/* If gl_FragCoord was previously declared, and the qualifiers were3579* different in any way, return true.3580*/3581if (state->fs_redeclares_gl_fragcoord) {3582return (state->fs_pixel_center_integer != qual->flags.q.pixel_center_integer3583|| state->fs_origin_upper_left != qual->flags.q.origin_upper_left);3584}35853586return false;3587}35883589static inline bool3590is_conflicting_layer_redeclaration(struct _mesa_glsl_parse_state *state,3591const struct ast_type_qualifier *qual)3592{3593if (state->redeclares_gl_layer) {3594return state->layer_viewport_relative != qual->flags.q.viewport_relative;3595}3596return false;3597}35983599static inline void3600validate_array_dimensions(const glsl_type *t,3601struct _mesa_glsl_parse_state *state,3602YYLTYPE *loc) {3603if (t->is_array()) {3604t = t->fields.array;3605while (t->is_array()) {3606if (t->is_unsized_array()) {3607_mesa_glsl_error(loc, state,3608"only the outermost array dimension can "3609"be unsized",3610t->name);3611break;3612}3613t = t->fields.array;3614}3615}3616}36173618static void3619apply_bindless_qualifier_to_variable(const struct ast_type_qualifier *qual,3620ir_variable *var,3621struct _mesa_glsl_parse_state *state,3622YYLTYPE *loc)3623{3624bool has_local_qualifiers = qual->flags.q.bindless_sampler ||3625qual->flags.q.bindless_image ||3626qual->flags.q.bound_sampler ||3627qual->flags.q.bound_image;36283629/* The ARB_bindless_texture spec says:3630*3631* "Modify Section 4.4.6 Opaque-Uniform Layout Qualifiers of the GLSL 4.303632* spec"3633*3634* "If these layout qualifiers are applied to other types of default block3635* uniforms, or variables with non-uniform storage, a compile-time error3636* will be generated."3637*/3638if (has_local_qualifiers && !qual->flags.q.uniform) {3639_mesa_glsl_error(loc, state, "ARB_bindless_texture layout qualifiers "3640"can only be applied to default block uniforms or "3641"variables with uniform storage");3642return;3643}36443645/* The ARB_bindless_texture spec doesn't state anything in this situation,3646* but it makes sense to only allow bindless_sampler/bound_sampler for3647* sampler types, and respectively bindless_image/bound_image for image3648* types.3649*/3650if ((qual->flags.q.bindless_sampler || qual->flags.q.bound_sampler) &&3651!var->type->contains_sampler()) {3652_mesa_glsl_error(loc, state, "bindless_sampler or bound_sampler can only "3653"be applied to sampler types");3654return;3655}36563657if ((qual->flags.q.bindless_image || qual->flags.q.bound_image) &&3658!var->type->contains_image()) {3659_mesa_glsl_error(loc, state, "bindless_image or bound_image can only be "3660"applied to image types");3661return;3662}36633664/* The bindless_sampler/bindless_image (and respectively3665* bound_sampler/bound_image) layout qualifiers can be set at global and at3666* local scope.3667*/3668if (var->type->contains_sampler() || var->type->contains_image()) {3669var->data.bindless = qual->flags.q.bindless_sampler ||3670qual->flags.q.bindless_image ||3671state->bindless_sampler_specified ||3672state->bindless_image_specified;36733674var->data.bound = qual->flags.q.bound_sampler ||3675qual->flags.q.bound_image ||3676state->bound_sampler_specified ||3677state->bound_image_specified;3678}3679}36803681static void3682apply_layout_qualifier_to_variable(const struct ast_type_qualifier *qual,3683ir_variable *var,3684struct _mesa_glsl_parse_state *state,3685YYLTYPE *loc)3686{3687if (var->name != NULL && strcmp(var->name, "gl_FragCoord") == 0) {36883689/* Section 4.3.8.1, page 39 of GLSL 1.50 spec says:3690*3691* "Within any shader, the first redeclarations of gl_FragCoord3692* must appear before any use of gl_FragCoord."3693*3694* Generate a compiler error if above condition is not met by the3695* fragment shader.3696*/3697ir_variable *earlier = state->symbols->get_variable("gl_FragCoord");3698if (earlier != NULL &&3699earlier->data.used &&3700!state->fs_redeclares_gl_fragcoord) {3701_mesa_glsl_error(loc, state,3702"gl_FragCoord used before its first redeclaration "3703"in fragment shader");3704}37053706/* Make sure all gl_FragCoord redeclarations specify the same layout3707* qualifiers.3708*/3709if (is_conflicting_fragcoord_redeclaration(state, qual)) {3710const char *const qual_string =3711get_layout_qualifier_string(qual->flags.q.origin_upper_left,3712qual->flags.q.pixel_center_integer);37133714const char *const state_string =3715get_layout_qualifier_string(state->fs_origin_upper_left,3716state->fs_pixel_center_integer);37173718_mesa_glsl_error(loc, state,3719"gl_FragCoord redeclared with different layout "3720"qualifiers (%s) and (%s) ",3721state_string,3722qual_string);3723}3724state->fs_origin_upper_left = qual->flags.q.origin_upper_left;3725state->fs_pixel_center_integer = qual->flags.q.pixel_center_integer;3726state->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers =3727!qual->flags.q.origin_upper_left && !qual->flags.q.pixel_center_integer;3728state->fs_redeclares_gl_fragcoord =3729state->fs_origin_upper_left ||3730state->fs_pixel_center_integer ||3731state->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers;3732}37333734if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)3735&& (strcmp(var->name, "gl_FragCoord") != 0)) {3736const char *const qual_string = (qual->flags.q.origin_upper_left)3737? "origin_upper_left" : "pixel_center_integer";37383739_mesa_glsl_error(loc, state,3740"layout qualifier `%s' can only be applied to "3741"fragment shader input `gl_FragCoord'",3742qual_string);3743}37443745if (qual->flags.q.explicit_location) {3746apply_explicit_location(qual, var, state, loc);37473748if (qual->flags.q.explicit_component) {3749unsigned qual_component;3750if (process_qualifier_constant(state, loc, "component",3751qual->component, &qual_component)) {3752validate_component_layout_for_type(state, loc, var->type,3753qual_component);3754var->data.explicit_component = true;3755var->data.location_frac = qual_component;3756}3757}3758} else if (qual->flags.q.explicit_index) {3759if (!qual->subroutine_list)3760_mesa_glsl_error(loc, state,3761"explicit index requires explicit location");3762} else if (qual->flags.q.explicit_component) {3763_mesa_glsl_error(loc, state,3764"explicit component requires explicit location");3765}37663767if (qual->flags.q.explicit_binding) {3768apply_explicit_binding(state, loc, var, var->type, qual);3769}37703771if (state->stage == MESA_SHADER_GEOMETRY &&3772qual->flags.q.out && qual->flags.q.stream) {3773unsigned qual_stream;3774if (process_qualifier_constant(state, loc, "stream", qual->stream,3775&qual_stream) &&3776validate_stream_qualifier(loc, state, qual_stream)) {3777var->data.stream = qual_stream;3778}3779}37803781if (qual->flags.q.out && qual->flags.q.xfb_buffer) {3782unsigned qual_xfb_buffer;3783if (process_qualifier_constant(state, loc, "xfb_buffer",3784qual->xfb_buffer, &qual_xfb_buffer) &&3785validate_xfb_buffer_qualifier(loc, state, qual_xfb_buffer)) {3786var->data.xfb_buffer = qual_xfb_buffer;3787if (qual->flags.q.explicit_xfb_buffer)3788var->data.explicit_xfb_buffer = true;3789}3790}37913792if (qual->flags.q.explicit_xfb_offset) {3793unsigned qual_xfb_offset;3794unsigned component_size = var->type->contains_double() ? 8 : 4;37953796if (process_qualifier_constant(state, loc, "xfb_offset",3797qual->offset, &qual_xfb_offset) &&3798validate_xfb_offset_qualifier(loc, state, (int) qual_xfb_offset,3799var->type, component_size)) {3800var->data.offset = qual_xfb_offset;3801var->data.explicit_xfb_offset = true;3802}3803}38043805if (qual->flags.q.explicit_xfb_stride) {3806unsigned qual_xfb_stride;3807if (process_qualifier_constant(state, loc, "xfb_stride",3808qual->xfb_stride, &qual_xfb_stride)) {3809var->data.xfb_stride = qual_xfb_stride;3810var->data.explicit_xfb_stride = true;3811}3812}38133814if (var->type->contains_atomic()) {3815if (var->data.mode == ir_var_uniform) {3816if (var->data.explicit_binding) {3817unsigned *offset =3818&state->atomic_counter_offsets[var->data.binding];38193820if (*offset % ATOMIC_COUNTER_SIZE)3821_mesa_glsl_error(loc, state,3822"misaligned atomic counter offset");38233824var->data.offset = *offset;3825*offset += var->type->atomic_size();38263827} else {3828_mesa_glsl_error(loc, state,3829"atomic counters require explicit binding point");3830}3831} else if (var->data.mode != ir_var_function_in) {3832_mesa_glsl_error(loc, state, "atomic counters may only be declared as "3833"function parameters or uniform-qualified "3834"global variables");3835}3836}38373838if (var->type->contains_sampler() &&3839!validate_storage_for_sampler_image_types(var, state, loc))3840return;38413842/* Is the 'layout' keyword used with parameters that allow relaxed checking.3843* Many implementations of GL_ARB_fragment_coord_conventions_enable and some3844* implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable3845* allowed the layout qualifier to be used with 'varying' and 'attribute'.3846* These extensions and all following extensions that add the 'layout'3847* keyword have been modified to require the use of 'in' or 'out'.3848*3849* The following extension do not allow the deprecated keywords:3850*3851* GL_AMD_conservative_depth3852* GL_ARB_conservative_depth3853* GL_ARB_gpu_shader53854* GL_ARB_separate_shader_objects3855* GL_ARB_tessellation_shader3856* GL_ARB_transform_feedback33857* GL_ARB_uniform_buffer_object3858*3859* It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader53860* allow layout with the deprecated keywords.3861*/3862const bool relaxed_layout_qualifier_checking =3863state->ARB_fragment_coord_conventions_enable;38643865const bool uses_deprecated_qualifier = qual->flags.q.attribute3866|| qual->flags.q.varying;3867if (qual->has_layout() && uses_deprecated_qualifier) {3868if (relaxed_layout_qualifier_checking) {3869_mesa_glsl_warning(loc, state,3870"`layout' qualifier may not be used with "3871"`attribute' or `varying'");3872} else {3873_mesa_glsl_error(loc, state,3874"`layout' qualifier may not be used with "3875"`attribute' or `varying'");3876}3877}38783879/* Layout qualifiers for gl_FragDepth, which are enabled by extension3880* AMD_conservative_depth.3881*/3882if (qual->flags.q.depth_type3883&& !state->is_version(420, 0)3884&& !state->AMD_conservative_depth_enable3885&& !state->ARB_conservative_depth_enable) {3886_mesa_glsl_error(loc, state,3887"extension GL_AMD_conservative_depth or "3888"GL_ARB_conservative_depth must be enabled "3889"to use depth layout qualifiers");3890} else if (qual->flags.q.depth_type3891&& strcmp(var->name, "gl_FragDepth") != 0) {3892_mesa_glsl_error(loc, state,3893"depth layout qualifiers can be applied only to "3894"gl_FragDepth");3895}38963897switch (qual->depth_type) {3898case ast_depth_any:3899var->data.depth_layout = ir_depth_layout_any;3900break;3901case ast_depth_greater:3902var->data.depth_layout = ir_depth_layout_greater;3903break;3904case ast_depth_less:3905var->data.depth_layout = ir_depth_layout_less;3906break;3907case ast_depth_unchanged:3908var->data.depth_layout = ir_depth_layout_unchanged;3909break;3910default:3911var->data.depth_layout = ir_depth_layout_none;3912break;3913}39143915if (qual->flags.q.std140 ||3916qual->flags.q.std430 ||3917qual->flags.q.packed ||3918qual->flags.q.shared) {3919_mesa_glsl_error(loc, state,3920"uniform and shader storage block layout qualifiers "3921"std140, std430, packed, and shared can only be "3922"applied to uniform or shader storage blocks, not "3923"members");3924}39253926if (qual->flags.q.row_major || qual->flags.q.column_major) {3927validate_matrix_layout_for_type(state, loc, var->type, var);3928}39293930/* From section 4.4.1.3 of the GLSL 4.50 specification (Fragment Shader3931* Inputs):3932*3933* "Fragment shaders also allow the following layout qualifier on in only3934* (not with variable declarations)3935* layout-qualifier-id3936* early_fragment_tests3937* [...]"3938*/3939if (qual->flags.q.early_fragment_tests) {3940_mesa_glsl_error(loc, state, "early_fragment_tests layout qualifier only "3941"valid in fragment shader input layout declaration.");3942}39433944if (qual->flags.q.inner_coverage) {3945_mesa_glsl_error(loc, state, "inner_coverage layout qualifier only "3946"valid in fragment shader input layout declaration.");3947}39483949if (qual->flags.q.post_depth_coverage) {3950_mesa_glsl_error(loc, state, "post_depth_coverage layout qualifier only "3951"valid in fragment shader input layout declaration.");3952}39533954if (state->has_bindless())3955apply_bindless_qualifier_to_variable(qual, var, state, loc);39563957if (qual->flags.q.pixel_interlock_ordered ||3958qual->flags.q.pixel_interlock_unordered ||3959qual->flags.q.sample_interlock_ordered ||3960qual->flags.q.sample_interlock_unordered) {3961_mesa_glsl_error(loc, state, "interlock layout qualifiers: "3962"pixel_interlock_ordered, pixel_interlock_unordered, "3963"sample_interlock_ordered and sample_interlock_unordered, "3964"only valid in fragment shader input layout declaration.");3965}39663967if (var->name != NULL && strcmp(var->name, "gl_Layer") == 0) {3968if (is_conflicting_layer_redeclaration(state, qual)) {3969_mesa_glsl_error(loc, state, "gl_Layer redeclaration with "3970"different viewport_relative setting than earlier");3971}3972state->redeclares_gl_layer = 1;3973if (qual->flags.q.viewport_relative) {3974state->layer_viewport_relative = 1;3975}3976} else if (qual->flags.q.viewport_relative) {3977_mesa_glsl_error(loc, state,3978"viewport_relative qualifier "3979"can only be applied to gl_Layer.");3980}3981}39823983static void3984apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,3985ir_variable *var,3986struct _mesa_glsl_parse_state *state,3987YYLTYPE *loc,3988bool is_parameter)3989{3990STATIC_ASSERT(sizeof(qual->flags.q) <= sizeof(qual->flags.i));39913992if (qual->flags.q.invariant) {3993if (var->data.used) {3994_mesa_glsl_error(loc, state,3995"variable `%s' may not be redeclared "3996"`invariant' after being used",3997var->name);3998} else {3999var->data.explicit_invariant = true;4000var->data.invariant = true;4001}4002}40034004if (qual->flags.q.precise) {4005if (var->data.used) {4006_mesa_glsl_error(loc, state,4007"variable `%s' may not be redeclared "4008"`precise' after being used",4009var->name);4010} else {4011var->data.precise = 1;4012}4013}40144015if (qual->is_subroutine_decl() && !qual->flags.q.uniform) {4016_mesa_glsl_error(loc, state,4017"`subroutine' may only be applied to uniforms, "4018"subroutine type declarations, or function definitions");4019}40204021if (qual->flags.q.constant || qual->flags.q.attribute4022|| qual->flags.q.uniform4023|| (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))4024var->data.read_only = 1;40254026if (qual->flags.q.centroid)4027var->data.centroid = 1;40284029if (qual->flags.q.sample)4030var->data.sample = 1;40314032/* Precision qualifiers do not hold any meaning in Desktop GLSL */4033if (state->es_shader) {4034var->data.precision =4035select_gles_precision(qual->precision, var->type, state, loc);4036}40374038if (qual->flags.q.patch)4039var->data.patch = 1;40404041if (qual->flags.q.attribute && state->stage != MESA_SHADER_VERTEX) {4042var->type = glsl_type::error_type;4043_mesa_glsl_error(loc, state,4044"`attribute' variables may not be declared in the "4045"%s shader",4046_mesa_shader_stage_to_string(state->stage));4047}40484049/* Disallow layout qualifiers which may only appear on layout declarations. */4050if (qual->flags.q.prim_type) {4051_mesa_glsl_error(loc, state,4052"Primitive type may only be specified on GS input or output "4053"layout declaration, not on variables.");4054}40554056/* Section 6.1.1 (Function Calling Conventions) of the GLSL 1.10 spec says:4057*4058* "However, the const qualifier cannot be used with out or inout."4059*4060* The same section of the GLSL 4.40 spec further clarifies this saying:4061*4062* "The const qualifier cannot be used with out or inout, or a4063* compile-time error results."4064*/4065if (is_parameter && qual->flags.q.constant && qual->flags.q.out) {4066_mesa_glsl_error(loc, state,4067"`const' may not be applied to `out' or `inout' "4068"function parameters");4069}40704071/* If there is no qualifier that changes the mode of the variable, leave4072* the setting alone.4073*/4074assert(var->data.mode != ir_var_temporary);4075if (qual->flags.q.in && qual->flags.q.out)4076var->data.mode = is_parameter ? ir_var_function_inout : ir_var_shader_out;4077else if (qual->flags.q.in)4078var->data.mode = is_parameter ? ir_var_function_in : ir_var_shader_in;4079else if (qual->flags.q.attribute4080|| (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))4081var->data.mode = ir_var_shader_in;4082else if (qual->flags.q.out)4083var->data.mode = is_parameter ? ir_var_function_out : ir_var_shader_out;4084else if (qual->flags.q.varying && (state->stage == MESA_SHADER_VERTEX))4085var->data.mode = ir_var_shader_out;4086else if (qual->flags.q.uniform)4087var->data.mode = ir_var_uniform;4088else if (qual->flags.q.buffer)4089var->data.mode = ir_var_shader_storage;4090else if (qual->flags.q.shared_storage)4091var->data.mode = ir_var_shader_shared;40924093if (!is_parameter && state->has_framebuffer_fetch() &&4094state->stage == MESA_SHADER_FRAGMENT) {4095if (state->is_version(130, 300))4096var->data.fb_fetch_output = qual->flags.q.in && qual->flags.q.out;4097else4098var->data.fb_fetch_output = (strcmp(var->name, "gl_LastFragData") == 0);4099}41004101if (var->data.fb_fetch_output) {4102var->data.assigned = true;4103var->data.memory_coherent = !qual->flags.q.non_coherent;41044105/* From the EXT_shader_framebuffer_fetch spec:4106*4107* "It is an error to declare an inout fragment output not qualified4108* with layout(noncoherent) if the GL_EXT_shader_framebuffer_fetch4109* extension hasn't been enabled."4110*/4111if (var->data.memory_coherent &&4112!state->EXT_shader_framebuffer_fetch_enable)4113_mesa_glsl_error(loc, state,4114"invalid declaration of framebuffer fetch output not "4115"qualified with layout(noncoherent)");41164117} else {4118/* From the EXT_shader_framebuffer_fetch spec:4119*4120* "Fragment outputs declared inout may specify the following layout4121* qualifier: [...] noncoherent"4122*/4123if (qual->flags.q.non_coherent)4124_mesa_glsl_error(loc, state,4125"invalid layout(noncoherent) qualifier not part of "4126"framebuffer fetch output declaration");4127}41284129if (!is_parameter && is_varying_var(var, state->stage)) {4130/* User-defined ins/outs are not permitted in compute shaders. */4131if (state->stage == MESA_SHADER_COMPUTE) {4132_mesa_glsl_error(loc, state,4133"user-defined input and output variables are not "4134"permitted in compute shaders");4135}41364137/* This variable is being used to link data between shader stages (in4138* pre-glsl-1.30 parlance, it's a "varying"). Check that it has a type4139* that is allowed for such purposes.4140*4141* From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:4142*4143* "The varying qualifier can be used only with the data types4144* float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of4145* these."4146*4147* This was relaxed in GLSL version 1.30 and GLSL ES version 3.00. From4148* page 31 (page 37 of the PDF) of the GLSL 1.30 spec:4149*4150* "Fragment inputs can only be signed and unsigned integers and4151* integer vectors, float, floating-point vectors, matrices, or4152* arrays of these. Structures cannot be input.4153*4154* Similar text exists in the section on vertex shader outputs.4155*4156* Similar text exists in the GLSL ES 3.00 spec, except that the GLSL ES4157* 3.00 spec allows structs as well. Varying structs are also allowed4158* in GLSL 1.50.4159*4160* From section 4.3.4 of the ARB_bindless_texture spec:4161*4162* "(modify third paragraph of the section to allow sampler and image4163* types) ... Vertex shader inputs can only be float,4164* single-precision floating-point scalars, single-precision4165* floating-point vectors, matrices, signed and unsigned integers4166* and integer vectors, sampler and image types."4167*4168* From section 4.3.6 of the ARB_bindless_texture spec:4169*4170* "Output variables can only be floating-point scalars,4171* floating-point vectors, matrices, signed or unsigned integers or4172* integer vectors, sampler or image types, or arrays or structures4173* of any these."4174*/4175switch (var->type->without_array()->base_type) {4176case GLSL_TYPE_FLOAT:4177/* Ok in all GLSL versions */4178break;4179case GLSL_TYPE_UINT:4180case GLSL_TYPE_INT:4181if (state->is_version(130, 300) || state->EXT_gpu_shader4_enable)4182break;4183_mesa_glsl_error(loc, state,4184"varying variables must be of base type float in %s",4185state->get_version_string());4186break;4187case GLSL_TYPE_STRUCT:4188if (state->is_version(150, 300))4189break;4190_mesa_glsl_error(loc, state,4191"varying variables may not be of type struct");4192break;4193case GLSL_TYPE_DOUBLE:4194case GLSL_TYPE_UINT64:4195case GLSL_TYPE_INT64:4196break;4197case GLSL_TYPE_SAMPLER:4198case GLSL_TYPE_IMAGE:4199if (state->has_bindless())4200break;4201FALLTHROUGH;4202default:4203_mesa_glsl_error(loc, state, "illegal type for a varying variable");4204break;4205}4206}42074208if (state->all_invariant && var->data.mode == ir_var_shader_out) {4209var->data.explicit_invariant = true;4210var->data.invariant = true;4211}42124213var->data.interpolation =4214interpret_interpolation_qualifier(qual, var->type,4215(ir_variable_mode) var->data.mode,4216state, loc);42174218/* Does the declaration use the deprecated 'attribute' or 'varying'4219* keywords?4220*/4221const bool uses_deprecated_qualifier = qual->flags.q.attribute4222|| qual->flags.q.varying;422342244225/* Validate auxiliary storage qualifiers */42264227/* From section 4.3.4 of the GLSL 1.30 spec:4228* "It is an error to use centroid in in a vertex shader."4229*4230* From section 4.3.4 of the GLSL ES 3.00 spec:4231* "It is an error to use centroid in or interpolation qualifiers in4232* a vertex shader input."4233*/42344235/* Section 4.3.6 of the GLSL 1.30 specification states:4236* "It is an error to use centroid out in a fragment shader."4237*4238* The GL_ARB_shading_language_420pack extension specification states:4239* "It is an error to use auxiliary storage qualifiers or interpolation4240* qualifiers on an output in a fragment shader."4241*/4242if (qual->flags.q.sample && (!is_varying_var(var, state->stage) || uses_deprecated_qualifier)) {4243_mesa_glsl_error(loc, state,4244"sample qualifier may only be used on `in` or `out` "4245"variables between shader stages");4246}4247if (qual->flags.q.centroid && !is_varying_var(var, state->stage)) {4248_mesa_glsl_error(loc, state,4249"centroid qualifier may only be used with `in', "4250"`out' or `varying' variables between shader stages");4251}42524253if (qual->flags.q.shared_storage && state->stage != MESA_SHADER_COMPUTE) {4254_mesa_glsl_error(loc, state,4255"the shared storage qualifiers can only be used with "4256"compute shaders");4257}42584259apply_image_qualifier_to_variable(qual, var, state, loc);4260}42614262/**4263* Get the variable that is being redeclared by this declaration or if it4264* does not exist, the current declared variable.4265*4266* Semantic checks to verify the validity of the redeclaration are also4267* performed. If semantic checks fail, compilation error will be emitted via4268* \c _mesa_glsl_error, but a non-\c NULL pointer will still be returned.4269*4270* \returns4271* A pointer to an existing variable in the current scope if the declaration4272* is a redeclaration, current variable otherwise. \c is_declared boolean4273* will return \c true if the declaration is a redeclaration, \c false4274* otherwise.4275*/4276static ir_variable *4277get_variable_being_redeclared(ir_variable **var_ptr, YYLTYPE loc,4278struct _mesa_glsl_parse_state *state,4279bool allow_all_redeclarations,4280bool *is_redeclaration)4281{4282ir_variable *var = *var_ptr;42834284/* Check if this declaration is actually a re-declaration, either to4285* resize an array or add qualifiers to an existing variable.4286*4287* This is allowed for variables in the current scope, or when at4288* global scope (for built-ins in the implicit outer scope).4289*/4290ir_variable *earlier = state->symbols->get_variable(var->name);4291if (earlier == NULL ||4292(state->current_function != NULL &&4293!state->symbols->name_declared_this_scope(var->name))) {4294*is_redeclaration = false;4295return var;4296}42974298*is_redeclaration = true;42994300if (earlier->data.how_declared == ir_var_declared_implicitly) {4301/* Verify that the redeclaration of a built-in does not change the4302* storage qualifier. There are a couple special cases.4303*4304* 1. Some built-in variables that are defined as 'in' in the4305* specification are implemented as system values. Allow4306* ir_var_system_value -> ir_var_shader_in.4307*4308* 2. gl_LastFragData is implemented as a ir_var_shader_out, but the4309* specification requires that redeclarations omit any qualifier.4310* Allow ir_var_shader_out -> ir_var_auto for this one variable.4311*/4312if (earlier->data.mode != var->data.mode &&4313!(earlier->data.mode == ir_var_system_value &&4314var->data.mode == ir_var_shader_in) &&4315!(strcmp(var->name, "gl_LastFragData") == 0 &&4316var->data.mode == ir_var_auto)) {4317_mesa_glsl_error(&loc, state,4318"redeclaration cannot change qualification of `%s'",4319var->name);4320}4321}43224323/* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,4324*4325* "It is legal to declare an array without a size and then4326* later re-declare the same name as an array of the same4327* type and specify a size."4328*/4329if (earlier->type->is_unsized_array() && var->type->is_array()4330&& (var->type->fields.array == earlier->type->fields.array)) {4331const int size = var->type->array_size();4332check_builtin_array_max_size(var->name, size, loc, state);4333if ((size > 0) && (size <= earlier->data.max_array_access)) {4334_mesa_glsl_error(& loc, state, "array size must be > %u due to "4335"previous access",4336earlier->data.max_array_access);4337}43384339earlier->type = var->type;4340delete var;4341var = NULL;4342*var_ptr = NULL;4343} else if (earlier->type != var->type) {4344_mesa_glsl_error(&loc, state,4345"redeclaration of `%s' has incorrect type",4346var->name);4347} else if ((state->ARB_fragment_coord_conventions_enable ||4348state->is_version(150, 0))4349&& strcmp(var->name, "gl_FragCoord") == 0) {4350/* Allow redeclaration of gl_FragCoord for ARB_fcc layout4351* qualifiers.4352*4353* We don't really need to do anything here, just allow the4354* redeclaration. Any error on the gl_FragCoord is handled on the ast4355* level at apply_layout_qualifier_to_variable using the4356* ast_type_qualifier and _mesa_glsl_parse_state, or later at4357* linker.cpp.4358*/4359/* According to section 4.3.7 of the GLSL 1.30 spec,4360* the following built-in varaibles can be redeclared with an4361* interpolation qualifier:4362* * gl_FrontColor4363* * gl_BackColor4364* * gl_FrontSecondaryColor4365* * gl_BackSecondaryColor4366* * gl_Color4367* * gl_SecondaryColor4368*/4369} else if (state->is_version(130, 0)4370&& (strcmp(var->name, "gl_FrontColor") == 04371|| strcmp(var->name, "gl_BackColor") == 04372|| strcmp(var->name, "gl_FrontSecondaryColor") == 04373|| strcmp(var->name, "gl_BackSecondaryColor") == 04374|| strcmp(var->name, "gl_Color") == 04375|| strcmp(var->name, "gl_SecondaryColor") == 0)) {4376earlier->data.interpolation = var->data.interpolation;43774378/* Layout qualifiers for gl_FragDepth. */4379} else if ((state->is_version(420, 0) ||4380state->AMD_conservative_depth_enable ||4381state->ARB_conservative_depth_enable)4382&& strcmp(var->name, "gl_FragDepth") == 0) {43834384/** From the AMD_conservative_depth spec:4385* Within any shader, the first redeclarations of gl_FragDepth4386* must appear before any use of gl_FragDepth.4387*/4388if (earlier->data.used) {4389_mesa_glsl_error(&loc, state,4390"the first redeclaration of gl_FragDepth "4391"must appear before any use of gl_FragDepth");4392}43934394/* Prevent inconsistent redeclaration of depth layout qualifier. */4395if (earlier->data.depth_layout != ir_depth_layout_none4396&& earlier->data.depth_layout != var->data.depth_layout) {4397_mesa_glsl_error(&loc, state,4398"gl_FragDepth: depth layout is declared here "4399"as '%s, but it was previously declared as "4400"'%s'",4401depth_layout_string(var->data.depth_layout),4402depth_layout_string(earlier->data.depth_layout));4403}44044405earlier->data.depth_layout = var->data.depth_layout;44064407} else if (state->has_framebuffer_fetch() &&4408strcmp(var->name, "gl_LastFragData") == 0 &&4409var->data.mode == ir_var_auto) {4410/* According to the EXT_shader_framebuffer_fetch spec:4411*4412* "By default, gl_LastFragData is declared with the mediump precision4413* qualifier. This can be changed by redeclaring the corresponding4414* variables with the desired precision qualifier."4415*4416* "Fragment shaders may specify the following layout qualifier only for4417* redeclaring the built-in gl_LastFragData array [...]: noncoherent"4418*/4419earlier->data.precision = var->data.precision;4420earlier->data.memory_coherent = var->data.memory_coherent;44214422} else if (state->NV_viewport_array2_enable &&4423strcmp(var->name, "gl_Layer") == 0 &&4424earlier->data.how_declared == ir_var_declared_implicitly) {4425/* No need to do anything, just allow it. Qualifier is stored in state */44264427} else if (state->is_version(0, 300) &&4428state->has_separate_shader_objects() &&4429(strcmp(var->name, "gl_Position") == 0 ||4430strcmp(var->name, "gl_PointSize") == 0)) {44314432/* EXT_separate_shader_objects spec says:4433*4434* "The following vertex shader outputs may be redeclared4435* at global scope to specify a built-in output interface,4436* with or without special qualifiers:4437*4438* gl_Position4439* gl_PointSize4440*4441* When compiling shaders using either of the above variables,4442* both such variables must be redeclared prior to use."4443*/4444if (earlier->data.used) {4445_mesa_glsl_error(&loc, state, "the first redeclaration of "4446"%s must appear before any use", var->name);4447}4448} else if ((earlier->data.how_declared == ir_var_declared_implicitly &&4449state->allow_builtin_variable_redeclaration) ||4450allow_all_redeclarations) {4451/* Allow verbatim redeclarations of built-in variables. Not explicitly4452* valid, but some applications do it.4453*/4454} else {4455_mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);4456}44574458return earlier;4459}44604461/**4462* Generate the IR for an initializer in a variable declaration4463*/4464static ir_rvalue *4465process_initializer(ir_variable *var, ast_declaration *decl,4466ast_fully_specified_type *type,4467exec_list *initializer_instructions,4468struct _mesa_glsl_parse_state *state)4469{4470void *mem_ctx = state;4471ir_rvalue *result = NULL;44724473YYLTYPE initializer_loc = decl->initializer->get_location();44744475/* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:4476*4477* "All uniform variables are read-only and are initialized either4478* directly by an application via API commands, or indirectly by4479* OpenGL."4480*/4481if (var->data.mode == ir_var_uniform) {4482state->check_version(120, 0, &initializer_loc,4483"cannot initialize uniform %s",4484var->name);4485}44864487/* Section 4.3.7 "Buffer Variables" of the GLSL 4.30 spec:4488*4489* "Buffer variables cannot have initializers."4490*/4491if (var->data.mode == ir_var_shader_storage) {4492_mesa_glsl_error(&initializer_loc, state,4493"cannot initialize buffer variable %s",4494var->name);4495}44964497/* From section 4.1.7 of the GLSL 4.40 spec:4498*4499* "Opaque variables [...] are initialized only through the4500* OpenGL API; they cannot be declared with an initializer in a4501* shader."4502*4503* From section 4.1.7 of the ARB_bindless_texture spec:4504*4505* "Samplers may be declared as shader inputs and outputs, as uniform4506* variables, as temporary variables, and as function parameters."4507*4508* From section 4.1.X of the ARB_bindless_texture spec:4509*4510* "Images may be declared as shader inputs and outputs, as uniform4511* variables, as temporary variables, and as function parameters."4512*/4513if (var->type->contains_atomic() ||4514(!state->has_bindless() && var->type->contains_opaque())) {4515_mesa_glsl_error(&initializer_loc, state,4516"cannot initialize %s variable %s",4517var->name, state->has_bindless() ? "atomic" : "opaque");4518}45194520if ((var->data.mode == ir_var_shader_in) && (state->current_function == NULL)) {4521_mesa_glsl_error(&initializer_loc, state,4522"cannot initialize %s shader input / %s %s",4523_mesa_shader_stage_to_string(state->stage),4524(state->stage == MESA_SHADER_VERTEX)4525? "attribute" : "varying",4526var->name);4527}45284529if (var->data.mode == ir_var_shader_out && state->current_function == NULL) {4530_mesa_glsl_error(&initializer_loc, state,4531"cannot initialize %s shader output %s",4532_mesa_shader_stage_to_string(state->stage),4533var->name);4534}45354536/* If the initializer is an ast_aggregate_initializer, recursively store4537* type information from the LHS into it, so that its hir() function can do4538* type checking.4539*/4540if (decl->initializer->oper == ast_aggregate)4541_mesa_ast_set_aggregate_type(var->type, decl->initializer);45424543ir_dereference *const lhs = new(state) ir_dereference_variable(var);4544ir_rvalue *rhs = decl->initializer->hir(initializer_instructions, state);45454546/* Calculate the constant value if this is a const or uniform4547* declaration.4548*4549* Section 4.3 (Storage Qualifiers) of the GLSL ES 1.00.17 spec says:4550*4551* "Declarations of globals without a storage qualifier, or with4552* just the const qualifier, may include initializers, in which case4553* they will be initialized before the first line of main() is4554* executed. Such initializers must be a constant expression."4555*4556* The same section of the GLSL ES 3.00.4 spec has similar language.4557*/4558if (type->qualifier.flags.q.constant4559|| type->qualifier.flags.q.uniform4560|| (state->es_shader && state->current_function == NULL)) {4561ir_rvalue *new_rhs = validate_assignment(state, initializer_loc,4562lhs, rhs, true);4563if (new_rhs != NULL) {4564rhs = new_rhs;45654566/* Section 4.3.3 (Constant Expressions) of the GLSL ES 3.00.4 spec4567* says:4568*4569* "A constant expression is one of4570*4571* ...4572*4573* - an expression formed by an operator on operands that are4574* all constant expressions, including getting an element of4575* a constant array, or a field of a constant structure, or4576* components of a constant vector. However, the sequence4577* operator ( , ) and the assignment operators ( =, +=, ...)4578* are not included in the operators that can create a4579* constant expression."4580*4581* Section 12.43 (Sequence operator and constant expressions) says:4582*4583* "Should the following construct be allowed?4584*4585* float a[2,3];4586*4587* The expression within the brackets uses the sequence operator4588* (',') and returns the integer 3 so the construct is declaring4589* a single-dimensional array of size 3. In some languages, the4590* construct declares a two-dimensional array. It would be4591* preferable to make this construct illegal to avoid confusion.4592*4593* One possibility is to change the definition of the sequence4594* operator so that it does not return a constant-expression and4595* hence cannot be used to declare an array size.4596*4597* RESOLUTION: The result of a sequence operator is not a4598* constant-expression."4599*4600* Section 4.3.3 (Constant Expressions) of the GLSL 4.30.9 spec4601* contains language almost identical to the section 4.3.3 in the4602* GLSL ES 3.00.4 spec. This is a new limitation for these GLSL4603* versions.4604*/4605ir_constant *constant_value =4606rhs->constant_expression_value(mem_ctx);46074608if (!constant_value ||4609(state->is_version(430, 300) &&4610decl->initializer->has_sequence_subexpression())) {4611const char *const variable_mode =4612(type->qualifier.flags.q.constant)4613? "const"4614: ((type->qualifier.flags.q.uniform) ? "uniform" : "global");46154616/* If ARB_shading_language_420pack is enabled, initializers of4617* const-qualified local variables do not have to be constant4618* expressions. Const-qualified global variables must still be4619* initialized with constant expressions.4620*/4621if (!state->has_420pack()4622|| state->current_function == NULL) {4623_mesa_glsl_error(& initializer_loc, state,4624"initializer of %s variable `%s' must be a "4625"constant expression",4626variable_mode,4627decl->identifier);4628if (var->type->is_numeric()) {4629/* Reduce cascading errors. */4630var->constant_value = type->qualifier.flags.q.constant4631? ir_constant::zero(state, var->type) : NULL;4632}4633}4634} else {4635rhs = constant_value;4636var->constant_value = type->qualifier.flags.q.constant4637? constant_value : NULL;4638}4639} else {4640if (var->type->is_numeric()) {4641/* Reduce cascading errors. */4642rhs = var->constant_value = type->qualifier.flags.q.constant4643? ir_constant::zero(state, var->type) : NULL;4644}4645}4646}46474648if (rhs && !rhs->type->is_error()) {4649bool temp = var->data.read_only;4650if (type->qualifier.flags.q.constant)4651var->data.read_only = false;46524653/* Never emit code to initialize a uniform.4654*/4655const glsl_type *initializer_type;4656bool error_emitted = false;4657if (!type->qualifier.flags.q.uniform) {4658error_emitted =4659do_assignment(initializer_instructions, state,4660NULL, lhs, rhs,4661&result, true, true,4662type->get_location());4663initializer_type = result->type;4664} else4665initializer_type = rhs->type;46664667if (!error_emitted) {4668var->constant_initializer = rhs->constant_expression_value(mem_ctx);4669var->data.has_initializer = true;4670var->data.is_implicit_initializer = false;46714672/* If the declared variable is an unsized array, it must inherrit4673* its full type from the initializer. A declaration such as4674*4675* uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);4676*4677* becomes4678*4679* uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);4680*4681* The assignment generated in the if-statement (below) will also4682* automatically handle this case for non-uniforms.4683*4684* If the declared variable is not an array, the types must4685* already match exactly. As a result, the type assignment4686* here can be done unconditionally. For non-uniforms the call4687* to do_assignment can change the type of the initializer (via4688* the implicit conversion rules). For uniforms the initializer4689* must be a constant expression, and the type of that expression4690* was validated above.4691*/4692var->type = initializer_type;4693}46944695var->data.read_only = temp;4696}46974698return result;4699}47004701static void4702validate_layout_qualifier_vertex_count(struct _mesa_glsl_parse_state *state,4703YYLTYPE loc, ir_variable *var,4704unsigned num_vertices,4705unsigned *size,4706const char *var_category)4707{4708if (var->type->is_unsized_array()) {4709/* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec says:4710*4711* All geometry shader input unsized array declarations will be4712* sized by an earlier input layout qualifier, when present, as per4713* the following table.4714*4715* Followed by a table mapping each allowed input layout qualifier to4716* the corresponding input length.4717*4718* Similarly for tessellation control shader outputs.4719*/4720if (num_vertices != 0)4721var->type = glsl_type::get_array_instance(var->type->fields.array,4722num_vertices);4723} else {4724/* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec4725* includes the following examples of compile-time errors:4726*4727* // code sequence within one shader...4728* in vec4 Color1[]; // size unknown4729* ...Color1.length()...// illegal, length() unknown4730* in vec4 Color2[2]; // size is 24731* ...Color1.length()...// illegal, Color1 still has no size4732* in vec4 Color3[3]; // illegal, input sizes are inconsistent4733* layout(lines) in; // legal, input size is 2, matching4734* in vec4 Color4[3]; // illegal, contradicts layout4735* ...4736*4737* To detect the case illustrated by Color3, we verify that the size of4738* an explicitly-sized array matches the size of any previously declared4739* explicitly-sized array. To detect the case illustrated by Color4, we4740* verify that the size of an explicitly-sized array is consistent with4741* any previously declared input layout.4742*/4743if (num_vertices != 0 && var->type->length != num_vertices) {4744_mesa_glsl_error(&loc, state,4745"%s size contradicts previously declared layout "4746"(size is %u, but layout requires a size of %u)",4747var_category, var->type->length, num_vertices);4748} else if (*size != 0 && var->type->length != *size) {4749_mesa_glsl_error(&loc, state,4750"%s sizes are inconsistent (size is %u, but a "4751"previous declaration has size %u)",4752var_category, var->type->length, *size);4753} else {4754*size = var->type->length;4755}4756}4757}47584759static void4760handle_tess_ctrl_shader_output_decl(struct _mesa_glsl_parse_state *state,4761YYLTYPE loc, ir_variable *var)4762{4763unsigned num_vertices = 0;47644765if (state->tcs_output_vertices_specified) {4766if (!state->out_qualifier->vertices->4767process_qualifier_constant(state, "vertices",4768&num_vertices, false)) {4769return;4770}47714772if (num_vertices > state->Const.MaxPatchVertices) {4773_mesa_glsl_error(&loc, state, "vertices (%d) exceeds "4774"GL_MAX_PATCH_VERTICES", num_vertices);4775return;4776}4777}47784779if (!var->type->is_array() && !var->data.patch) {4780_mesa_glsl_error(&loc, state,4781"tessellation control shader outputs must be arrays");47824783/* To avoid cascading failures, short circuit the checks below. */4784return;4785}47864787if (var->data.patch)4788return;47894790validate_layout_qualifier_vertex_count(state, loc, var, num_vertices,4791&state->tcs_output_size,4792"tessellation control shader output");4793}47944795/**4796* Do additional processing necessary for tessellation control/evaluation shader4797* input declarations. This covers both interface block arrays and bare input4798* variables.4799*/4800static void4801handle_tess_shader_input_decl(struct _mesa_glsl_parse_state *state,4802YYLTYPE loc, ir_variable *var)4803{4804if (!var->type->is_array() && !var->data.patch) {4805_mesa_glsl_error(&loc, state,4806"per-vertex tessellation shader inputs must be arrays");4807/* Avoid cascading failures. */4808return;4809}48104811if (var->data.patch)4812return;48134814/* The ARB_tessellation_shader spec says:4815*4816* "Declaring an array size is optional. If no size is specified, it4817* will be taken from the implementation-dependent maximum patch size4818* (gl_MaxPatchVertices). If a size is specified, it must match the4819* maximum patch size; otherwise, a compile or link error will occur."4820*4821* This text appears twice, once for TCS inputs, and again for TES inputs.4822*/4823if (var->type->is_unsized_array()) {4824var->type = glsl_type::get_array_instance(var->type->fields.array,4825state->Const.MaxPatchVertices);4826} else if (var->type->length != state->Const.MaxPatchVertices) {4827_mesa_glsl_error(&loc, state,4828"per-vertex tessellation shader input arrays must be "4829"sized to gl_MaxPatchVertices (%d).",4830state->Const.MaxPatchVertices);4831}4832}483348344835/**4836* Do additional processing necessary for geometry shader input declarations4837* (this covers both interface blocks arrays and bare input variables).4838*/4839static void4840handle_geometry_shader_input_decl(struct _mesa_glsl_parse_state *state,4841YYLTYPE loc, ir_variable *var)4842{4843unsigned num_vertices = 0;48444845if (state->gs_input_prim_type_specified) {4846num_vertices = vertices_per_prim(state->in_qualifier->prim_type);4847}48484849/* Geometry shader input variables must be arrays. Caller should have4850* reported an error for this.4851*/4852if (!var->type->is_array()) {4853assert(state->error);48544855/* To avoid cascading failures, short circuit the checks below. */4856return;4857}48584859validate_layout_qualifier_vertex_count(state, loc, var, num_vertices,4860&state->gs_input_size,4861"geometry shader input");4862}48634864static void4865validate_identifier(const char *identifier, YYLTYPE loc,4866struct _mesa_glsl_parse_state *state)4867{4868/* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,4869*4870* "Identifiers starting with "gl_" are reserved for use by4871* OpenGL, and may not be declared in a shader as either a4872* variable or a function."4873*/4874if (is_gl_identifier(identifier)) {4875_mesa_glsl_error(&loc, state,4876"identifier `%s' uses reserved `gl_' prefix",4877identifier);4878} else if (strstr(identifier, "__")) {4879/* From page 14 (page 20 of the PDF) of the GLSL 1.104880* spec:4881*4882* "In addition, all identifiers containing two4883* consecutive underscores (__) are reserved as4884* possible future keywords."4885*4886* The intention is that names containing __ are reserved for internal4887* use by the implementation, and names prefixed with GL_ are reserved4888* for use by Khronos. Names simply containing __ are dangerous to use,4889* but should be allowed.4890*4891* A future version of the GLSL specification will clarify this.4892*/4893_mesa_glsl_warning(&loc, state,4894"identifier `%s' uses reserved `__' string",4895identifier);4896}4897}48984899ir_rvalue *4900ast_declarator_list::hir(exec_list *instructions,4901struct _mesa_glsl_parse_state *state)4902{4903void *ctx = state;4904const struct glsl_type *decl_type;4905const char *type_name = NULL;4906ir_rvalue *result = NULL;4907YYLTYPE loc = this->get_location();49084909/* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:4910*4911* "To ensure that a particular output variable is invariant, it is4912* necessary to use the invariant qualifier. It can either be used to4913* qualify a previously declared variable as being invariant4914*4915* invariant gl_Position; // make existing gl_Position be invariant"4916*4917* In these cases the parser will set the 'invariant' flag in the declarator4918* list, and the type will be NULL.4919*/4920if (this->invariant) {4921assert(this->type == NULL);49224923if (state->current_function != NULL) {4924_mesa_glsl_error(& loc, state,4925"all uses of `invariant' keyword must be at global "4926"scope");4927}49284929foreach_list_typed (ast_declaration, decl, link, &this->declarations) {4930assert(decl->array_specifier == NULL);4931assert(decl->initializer == NULL);49324933ir_variable *const earlier =4934state->symbols->get_variable(decl->identifier);4935if (earlier == NULL) {4936_mesa_glsl_error(& loc, state,4937"undeclared variable `%s' cannot be marked "4938"invariant", decl->identifier);4939} else if (!is_allowed_invariant(earlier, state)) {4940_mesa_glsl_error(&loc, state,4941"`%s' cannot be marked invariant; interfaces between "4942"shader stages only.", decl->identifier);4943} else if (earlier->data.used) {4944_mesa_glsl_error(& loc, state,4945"variable `%s' may not be redeclared "4946"`invariant' after being used",4947earlier->name);4948} else {4949earlier->data.explicit_invariant = true;4950earlier->data.invariant = true;4951}4952}49534954/* Invariant redeclarations do not have r-values.4955*/4956return NULL;4957}49584959if (this->precise) {4960assert(this->type == NULL);49614962foreach_list_typed (ast_declaration, decl, link, &this->declarations) {4963assert(decl->array_specifier == NULL);4964assert(decl->initializer == NULL);49654966ir_variable *const earlier =4967state->symbols->get_variable(decl->identifier);4968if (earlier == NULL) {4969_mesa_glsl_error(& loc, state,4970"undeclared variable `%s' cannot be marked "4971"precise", decl->identifier);4972} else if (state->current_function != NULL &&4973!state->symbols->name_declared_this_scope(decl->identifier)) {4974/* Note: we have to check if we're in a function, since4975* builtins are treated as having come from another scope.4976*/4977_mesa_glsl_error(& loc, state,4978"variable `%s' from an outer scope may not be "4979"redeclared `precise' in this scope",4980earlier->name);4981} else if (earlier->data.used) {4982_mesa_glsl_error(& loc, state,4983"variable `%s' may not be redeclared "4984"`precise' after being used",4985earlier->name);4986} else {4987earlier->data.precise = true;4988}4989}49904991/* Precise redeclarations do not have r-values either. */4992return NULL;4993}49944995assert(this->type != NULL);4996assert(!this->invariant);4997assert(!this->precise);49984999/* GL_EXT_shader_image_load_store base type uses GLSL_TYPE_VOID as a special value to5000* indicate that it needs to be updated later (see glsl_parser.yy).5001* This is done here, based on the layout qualifier and the type of the image var5002*/5003if (this->type->qualifier.flags.q.explicit_image_format &&5004this->type->specifier->type->is_image() &&5005this->type->qualifier.image_base_type == GLSL_TYPE_VOID) {5006/* "The ARB_shader_image_load_store says:5007* If both extensions are enabled in the shading language, the "size*" layout5008* qualifiers are treated as format qualifiers, and are mapped to equivalent5009* format qualifiers in the table below, according to the type of image5010* variable.5011* image* iimage* uimage*5012* -------- -------- --------5013* size1x8 n/a r8i r8ui5014* size1x16 r16f r16i r16ui5015* size1x32 r32f r32i r32ui5016* size2x32 rg32f rg32i rg32ui5017* size4x32 rgba32f rgba32i rgba32ui"5018*/5019if (strncmp(this->type->specifier->type_name, "image", strlen("image")) == 0) {5020switch (this->type->qualifier.image_format) {5021case PIPE_FORMAT_R8_SINT:5022/* The GL_EXT_shader_image_load_store spec says:5023* A layout of "size1x8" is illegal for image variables associated5024* with floating-point data types.5025*/5026_mesa_glsl_error(& loc, state,5027"size1x8 is illegal for image variables "5028"with floating-point data types.");5029return NULL;5030case PIPE_FORMAT_R16_SINT:5031this->type->qualifier.image_format = PIPE_FORMAT_R16_FLOAT;5032break;5033case PIPE_FORMAT_R32_SINT:5034this->type->qualifier.image_format = PIPE_FORMAT_R32_FLOAT;5035break;5036case PIPE_FORMAT_R32G32_SINT:5037this->type->qualifier.image_format = PIPE_FORMAT_R32G32_FLOAT;5038break;5039case PIPE_FORMAT_R32G32B32A32_SINT:5040this->type->qualifier.image_format = PIPE_FORMAT_R32G32B32A32_FLOAT;5041break;5042default:5043unreachable("Unknown image format");5044}5045this->type->qualifier.image_base_type = GLSL_TYPE_FLOAT;5046} else if (strncmp(this->type->specifier->type_name, "uimage", strlen("uimage")) == 0) {5047switch (this->type->qualifier.image_format) {5048case PIPE_FORMAT_R8_SINT:5049this->type->qualifier.image_format = PIPE_FORMAT_R8_UINT;5050break;5051case PIPE_FORMAT_R16_SINT:5052this->type->qualifier.image_format = PIPE_FORMAT_R16_UINT;5053break;5054case PIPE_FORMAT_R32_SINT:5055this->type->qualifier.image_format = PIPE_FORMAT_R32_UINT;5056break;5057case PIPE_FORMAT_R32G32_SINT:5058this->type->qualifier.image_format = PIPE_FORMAT_R32G32_UINT;5059break;5060case PIPE_FORMAT_R32G32B32A32_SINT:5061this->type->qualifier.image_format = PIPE_FORMAT_R32G32B32A32_UINT;5062break;5063default:5064unreachable("Unknown image format");5065}5066this->type->qualifier.image_base_type = GLSL_TYPE_UINT;5067} else if (strncmp(this->type->specifier->type_name, "iimage", strlen("iimage")) == 0) {5068this->type->qualifier.image_base_type = GLSL_TYPE_INT;5069} else {5070assert(false);5071}5072}50735074/* The type specifier may contain a structure definition. Process that5075* before any of the variable declarations.5076*/5077(void) this->type->specifier->hir(instructions, state);50785079decl_type = this->type->glsl_type(& type_name, state);50805081/* Section 4.3.7 "Buffer Variables" of the GLSL 4.30 spec:5082* "Buffer variables may only be declared inside interface blocks5083* (section 4.3.9 “Interface Blocks”), which are then referred to as5084* shader storage blocks. It is a compile-time error to declare buffer5085* variables at global scope (outside a block)."5086*/5087if (type->qualifier.flags.q.buffer && !decl_type->is_interface()) {5088_mesa_glsl_error(&loc, state,5089"buffer variables cannot be declared outside "5090"interface blocks");5091}50925093/* An offset-qualified atomic counter declaration sets the default5094* offset for the next declaration within the same atomic counter5095* buffer.5096*/5097if (decl_type && decl_type->contains_atomic()) {5098if (type->qualifier.flags.q.explicit_binding &&5099type->qualifier.flags.q.explicit_offset) {5100unsigned qual_binding;5101unsigned qual_offset;5102if (process_qualifier_constant(state, &loc, "binding",5103type->qualifier.binding,5104&qual_binding)5105&& process_qualifier_constant(state, &loc, "offset",5106type->qualifier.offset,5107&qual_offset)) {5108if (qual_binding < ARRAY_SIZE(state->atomic_counter_offsets))5109state->atomic_counter_offsets[qual_binding] = qual_offset;5110}5111}51125113ast_type_qualifier allowed_atomic_qual_mask;5114allowed_atomic_qual_mask.flags.i = 0;5115allowed_atomic_qual_mask.flags.q.explicit_binding = 1;5116allowed_atomic_qual_mask.flags.q.explicit_offset = 1;5117allowed_atomic_qual_mask.flags.q.uniform = 1;51185119type->qualifier.validate_flags(&loc, state, allowed_atomic_qual_mask,5120"invalid layout qualifier for",5121"atomic_uint");5122}51235124if (this->declarations.is_empty()) {5125/* If there is no structure involved in the program text, there are two5126* possible scenarios:5127*5128* - The program text contained something like 'vec4;'. This is an5129* empty declaration. It is valid but weird. Emit a warning.5130*5131* - The program text contained something like 'S;' and 'S' is not the5132* name of a known structure type. This is both invalid and weird.5133* Emit an error.5134*5135* - The program text contained something like 'mediump float;'5136* when the programmer probably meant 'precision mediump5137* float;' Emit a warning with a description of what they5138* probably meant to do.5139*5140* Note that if decl_type is NULL and there is a structure involved,5141* there must have been some sort of error with the structure. In this5142* case we assume that an error was already generated on this line of5143* code for the structure. There is no need to generate an additional,5144* confusing error.5145*/5146assert(this->type->specifier->structure == NULL || decl_type != NULL5147|| state->error);51485149if (decl_type == NULL) {5150_mesa_glsl_error(&loc, state,5151"invalid type `%s' in empty declaration",5152type_name);5153} else {5154if (decl_type->is_array()) {5155/* From Section 13.22 (Array Declarations) of the GLSL ES 3.25156* spec:5157*5158* "... any declaration that leaves the size undefined is5159* disallowed as this would add complexity and there are no5160* use-cases."5161*/5162if (state->es_shader && decl_type->is_unsized_array()) {5163_mesa_glsl_error(&loc, state, "array size must be explicitly "5164"or implicitly defined");5165}51665167/* From Section 4.12 (Empty Declarations) of the GLSL 4.5 spec:5168*5169* "The combinations of types and qualifiers that cause5170* compile-time or link-time errors are the same whether or not5171* the declaration is empty."5172*/5173validate_array_dimensions(decl_type, state, &loc);5174}51755176if (decl_type->is_atomic_uint()) {5177/* Empty atomic counter declarations are allowed and useful5178* to set the default offset qualifier.5179*/5180return NULL;5181} else if (this->type->qualifier.precision != ast_precision_none) {5182if (this->type->specifier->structure != NULL) {5183_mesa_glsl_error(&loc, state,5184"precision qualifiers can't be applied "5185"to structures");5186} else {5187static const char *const precision_names[] = {5188"highp",5189"highp",5190"mediump",5191"lowp"5192};51935194_mesa_glsl_warning(&loc, state,5195"empty declaration with precision "5196"qualifier, to set the default precision, "5197"use `precision %s %s;'",5198precision_names[this->type->5199qualifier.precision],5200type_name);5201}5202} else if (this->type->specifier->structure == NULL) {5203_mesa_glsl_warning(&loc, state, "empty declaration");5204}5205}5206}52075208foreach_list_typed (ast_declaration, decl, link, &this->declarations) {5209const struct glsl_type *var_type;5210ir_variable *var;5211const char *identifier = decl->identifier;5212/* FINISHME: Emit a warning if a variable declaration shadows a5213* FINISHME: declaration at a higher scope.5214*/52155216if ((decl_type == NULL) || decl_type->is_void()) {5217if (type_name != NULL) {5218_mesa_glsl_error(& loc, state,5219"invalid type `%s' in declaration of `%s'",5220type_name, decl->identifier);5221} else {5222_mesa_glsl_error(& loc, state,5223"invalid type in declaration of `%s'",5224decl->identifier);5225}5226continue;5227}52285229if (this->type->qualifier.is_subroutine_decl()) {5230const glsl_type *t;5231const char *name;52325233t = state->symbols->get_type(this->type->specifier->type_name);5234if (!t)5235_mesa_glsl_error(& loc, state,5236"invalid type in declaration of `%s'",5237decl->identifier);5238name = ralloc_asprintf(ctx, "%s_%s", _mesa_shader_stage_to_subroutine_prefix(state->stage), decl->identifier);52395240identifier = name;52415242}5243var_type = process_array_type(&loc, decl_type, decl->array_specifier,5244state);52455246var = new(ctx) ir_variable(var_type, identifier, ir_var_auto);52475248/* The 'varying in' and 'varying out' qualifiers can only be used with5249* ARB_geometry_shader4 and EXT_geometry_shader4, which we don't support5250* yet.5251*/5252if (this->type->qualifier.flags.q.varying) {5253if (this->type->qualifier.flags.q.in) {5254_mesa_glsl_error(& loc, state,5255"`varying in' qualifier in declaration of "5256"`%s' only valid for geometry shaders using "5257"ARB_geometry_shader4 or EXT_geometry_shader4",5258decl->identifier);5259} else if (this->type->qualifier.flags.q.out) {5260_mesa_glsl_error(& loc, state,5261"`varying out' qualifier in declaration of "5262"`%s' only valid for geometry shaders using "5263"ARB_geometry_shader4 or EXT_geometry_shader4",5264decl->identifier);5265}5266}52675268/* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;5269*5270* "Global variables can only use the qualifiers const,5271* attribute, uniform, or varying. Only one may be5272* specified.5273*5274* Local variables can only use the qualifier const."5275*5276* This is relaxed in GLSL 1.30 and GLSL ES 3.00. It is also relaxed by5277* any extension that adds the 'layout' keyword.5278*/5279if (!state->is_version(130, 300)5280&& !state->has_explicit_attrib_location()5281&& !state->has_separate_shader_objects()5282&& !state->ARB_fragment_coord_conventions_enable) {5283/* GL_EXT_gpu_shader4 only allows "varying out" on fragment shader5284* outputs. (the varying flag is not set by the parser)5285*/5286if (this->type->qualifier.flags.q.out &&5287(!state->EXT_gpu_shader4_enable ||5288state->stage != MESA_SHADER_FRAGMENT)) {5289_mesa_glsl_error(& loc, state,5290"`out' qualifier in declaration of `%s' "5291"only valid for function parameters in %s",5292decl->identifier, state->get_version_string());5293}5294if (this->type->qualifier.flags.q.in) {5295_mesa_glsl_error(& loc, state,5296"`in' qualifier in declaration of `%s' "5297"only valid for function parameters in %s",5298decl->identifier, state->get_version_string());5299}5300/* FINISHME: Test for other invalid qualifiers. */5301}53025303apply_type_qualifier_to_variable(& this->type->qualifier, var, state,5304& loc, false);5305apply_layout_qualifier_to_variable(&this->type->qualifier, var, state,5306&loc);53075308if ((state->zero_init & (1u << var->data.mode)) &&5309(var->type->is_numeric() || var->type->is_boolean())) {5310const ir_constant_data data = { { 0 } };5311var->data.has_initializer = true;5312var->data.is_implicit_initializer = true;5313var->constant_initializer = new(var) ir_constant(var->type, &data);5314}53155316if (this->type->qualifier.flags.q.invariant) {5317if (!is_allowed_invariant(var, state)) {5318_mesa_glsl_error(&loc, state,5319"`%s' cannot be marked invariant; interfaces between "5320"shader stages only", var->name);5321}5322}53235324if (state->current_function != NULL) {5325const char *mode = NULL;5326const char *extra = "";53275328/* There is no need to check for 'inout' here because the parser will5329* only allow that in function parameter lists.5330*/5331if (this->type->qualifier.flags.q.attribute) {5332mode = "attribute";5333} else if (this->type->qualifier.is_subroutine_decl()) {5334mode = "subroutine uniform";5335} else if (this->type->qualifier.flags.q.uniform) {5336mode = "uniform";5337} else if (this->type->qualifier.flags.q.varying) {5338mode = "varying";5339} else if (this->type->qualifier.flags.q.in) {5340mode = "in";5341extra = " or in function parameter list";5342} else if (this->type->qualifier.flags.q.out) {5343mode = "out";5344extra = " or in function parameter list";5345}53465347if (mode) {5348_mesa_glsl_error(& loc, state,5349"%s variable `%s' must be declared at "5350"global scope%s",5351mode, var->name, extra);5352}5353} else if (var->data.mode == ir_var_shader_in) {5354var->data.read_only = true;53555356if (state->stage == MESA_SHADER_VERTEX) {5357/* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:5358*5359* "Vertex shader inputs can only be float, floating-point5360* vectors, matrices, signed and unsigned integers and integer5361* vectors. Vertex shader inputs can also form arrays of these5362* types, but not structures."5363*5364* From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:5365*5366* "Vertex shader inputs can only be float, floating-point5367* vectors, matrices, signed and unsigned integers and integer5368* vectors. They cannot be arrays or structures."5369*5370* From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:5371*5372* "The attribute qualifier can be used only with float,5373* floating-point vectors, and matrices. Attribute variables5374* cannot be declared as arrays or structures."5375*5376* From page 33 (page 39 of the PDF) of the GLSL ES 3.00 spec:5377*5378* "Vertex shader inputs can only be float, floating-point5379* vectors, matrices, signed and unsigned integers and integer5380* vectors. Vertex shader inputs cannot be arrays or5381* structures."5382*5383* From section 4.3.4 of the ARB_bindless_texture spec:5384*5385* "(modify third paragraph of the section to allow sampler and5386* image types) ... Vertex shader inputs can only be float,5387* single-precision floating-point scalars, single-precision5388* floating-point vectors, matrices, signed and unsigned5389* integers and integer vectors, sampler and image types."5390*/5391const glsl_type *check_type = var->type->without_array();53925393bool error = false;5394switch (check_type->base_type) {5395case GLSL_TYPE_FLOAT:5396break;5397case GLSL_TYPE_UINT64:5398case GLSL_TYPE_INT64:5399break;5400case GLSL_TYPE_UINT:5401case GLSL_TYPE_INT:5402error = !state->is_version(120, 300) && !state->EXT_gpu_shader4_enable;5403break;5404case GLSL_TYPE_DOUBLE:5405error = !state->is_version(410, 0) && !state->ARB_vertex_attrib_64bit_enable;5406break;5407case GLSL_TYPE_SAMPLER:5408case GLSL_TYPE_IMAGE:5409error = !state->has_bindless();5410break;5411default:5412error = true;5413}54145415if (error) {5416_mesa_glsl_error(& loc, state,5417"vertex shader input / attribute cannot have "5418"type %s`%s'",5419var->type->is_array() ? "array of " : "",5420check_type->name);5421} else if (var->type->is_array() &&5422!state->check_version(150, 0, &loc,5423"vertex shader input / attribute "5424"cannot have array type")) {5425}5426} else if (state->stage == MESA_SHADER_GEOMETRY) {5427/* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:5428*5429* Geometry shader input variables get the per-vertex values5430* written out by vertex shader output variables of the same5431* names. Since a geometry shader operates on a set of5432* vertices, each input varying variable (or input block, see5433* interface blocks below) needs to be declared as an array.5434*/5435if (!var->type->is_array()) {5436_mesa_glsl_error(&loc, state,5437"geometry shader inputs must be arrays");5438}54395440handle_geometry_shader_input_decl(state, loc, var);5441} else if (state->stage == MESA_SHADER_FRAGMENT) {5442/* From section 4.3.4 (Input Variables) of the GLSL ES 3.10 spec:5443*5444* It is a compile-time error to declare a fragment shader5445* input with, or that contains, any of the following types:5446*5447* * A boolean type5448* * An opaque type5449* * An array of arrays5450* * An array of structures5451* * A structure containing an array5452* * A structure containing a structure5453*/5454if (state->es_shader) {5455const glsl_type *check_type = var->type->without_array();5456if (check_type->is_boolean() ||5457check_type->contains_opaque()) {5458_mesa_glsl_error(&loc, state,5459"fragment shader input cannot have type %s",5460check_type->name);5461}5462if (var->type->is_array() &&5463var->type->fields.array->is_array()) {5464_mesa_glsl_error(&loc, state,5465"%s shader output "5466"cannot have an array of arrays",5467_mesa_shader_stage_to_string(state->stage));5468}5469if (var->type->is_array() &&5470var->type->fields.array->is_struct()) {5471_mesa_glsl_error(&loc, state,5472"fragment shader input "5473"cannot have an array of structs");5474}5475if (var->type->is_struct()) {5476for (unsigned i = 0; i < var->type->length; i++) {5477if (var->type->fields.structure[i].type->is_array() ||5478var->type->fields.structure[i].type->is_struct())5479_mesa_glsl_error(&loc, state,5480"fragment shader input cannot have "5481"a struct that contains an "5482"array or struct");5483}5484}5485}5486} else if (state->stage == MESA_SHADER_TESS_CTRL ||5487state->stage == MESA_SHADER_TESS_EVAL) {5488handle_tess_shader_input_decl(state, loc, var);5489}5490} else if (var->data.mode == ir_var_shader_out) {5491const glsl_type *check_type = var->type->without_array();54925493/* From section 4.3.6 (Output variables) of the GLSL 4.40 spec:5494*5495* It is a compile-time error to declare a fragment shader output5496* that contains any of the following:5497*5498* * A Boolean type (bool, bvec2 ...)5499* * A double-precision scalar or vector (double, dvec2 ...)5500* * An opaque type5501* * Any matrix type5502* * A structure5503*/5504if (state->stage == MESA_SHADER_FRAGMENT) {5505if (check_type->is_struct() || check_type->is_matrix())5506_mesa_glsl_error(&loc, state,5507"fragment shader output "5508"cannot have struct or matrix type");5509switch (check_type->base_type) {5510case GLSL_TYPE_UINT:5511case GLSL_TYPE_INT:5512case GLSL_TYPE_FLOAT:5513break;5514default:5515_mesa_glsl_error(&loc, state,5516"fragment shader output cannot have "5517"type %s", check_type->name);5518}5519}55205521/* From section 4.3.6 (Output Variables) of the GLSL ES 3.10 spec:5522*5523* It is a compile-time error to declare a vertex shader output5524* with, or that contains, any of the following types:5525*5526* * A boolean type5527* * An opaque type5528* * An array of arrays5529* * An array of structures5530* * A structure containing an array5531* * A structure containing a structure5532*5533* It is a compile-time error to declare a fragment shader output5534* with, or that contains, any of the following types:5535*5536* * A boolean type5537* * An opaque type5538* * A matrix5539* * A structure5540* * An array of array5541*5542* ES 3.20 updates this to apply to tessellation and geometry shaders5543* as well. Because there are per-vertex arrays in the new stages,5544* it strikes the "array of..." rules and replaces them with these:5545*5546* * For per-vertex-arrayed variables (applies to tessellation5547* control, tessellation evaluation and geometry shaders):5548*5549* * Per-vertex-arrayed arrays of arrays5550* * Per-vertex-arrayed arrays of structures5551*5552* * For non-per-vertex-arrayed variables:5553*5554* * An array of arrays5555* * An array of structures5556*5557* which basically says to unwrap the per-vertex aspect and apply5558* the old rules.5559*/5560if (state->es_shader) {5561if (var->type->is_array() &&5562var->type->fields.array->is_array()) {5563_mesa_glsl_error(&loc, state,5564"%s shader output "5565"cannot have an array of arrays",5566_mesa_shader_stage_to_string(state->stage));5567}5568if (state->stage <= MESA_SHADER_GEOMETRY) {5569const glsl_type *type = var->type;55705571if (state->stage == MESA_SHADER_TESS_CTRL &&5572!var->data.patch && var->type->is_array()) {5573type = var->type->fields.array;5574}55755576if (type->is_array() && type->fields.array->is_struct()) {5577_mesa_glsl_error(&loc, state,5578"%s shader output cannot have "5579"an array of structs",5580_mesa_shader_stage_to_string(state->stage));5581}5582if (type->is_struct()) {5583for (unsigned i = 0; i < type->length; i++) {5584if (type->fields.structure[i].type->is_array() ||5585type->fields.structure[i].type->is_struct())5586_mesa_glsl_error(&loc, state,5587"%s shader output cannot have a "5588"struct that contains an "5589"array or struct",5590_mesa_shader_stage_to_string(state->stage));5591}5592}5593}5594}55955596if (state->stage == MESA_SHADER_TESS_CTRL) {5597handle_tess_ctrl_shader_output_decl(state, loc, var);5598}5599} else if (var->type->contains_subroutine()) {5600/* declare subroutine uniforms as hidden */5601var->data.how_declared = ir_var_hidden;5602}56035604/* From section 4.3.4 of the GLSL 4.00 spec:5605* "Input variables may not be declared using the patch in qualifier5606* in tessellation control or geometry shaders."5607*5608* From section 4.3.6 of the GLSL 4.00 spec:5609* "It is an error to use patch out in a vertex, tessellation5610* evaluation, or geometry shader."5611*5612* This doesn't explicitly forbid using them in a fragment shader, but5613* that's probably just an oversight.5614*/5615if (state->stage != MESA_SHADER_TESS_EVAL5616&& this->type->qualifier.flags.q.patch5617&& this->type->qualifier.flags.q.in) {56185619_mesa_glsl_error(&loc, state, "'patch in' can only be used in a "5620"tessellation evaluation shader");5621}56225623if (state->stage != MESA_SHADER_TESS_CTRL5624&& this->type->qualifier.flags.q.patch5625&& this->type->qualifier.flags.q.out) {56265627_mesa_glsl_error(&loc, state, "'patch out' can only be used in a "5628"tessellation control shader");5629}56305631/* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.5632*/5633if (this->type->qualifier.precision != ast_precision_none) {5634state->check_precision_qualifiers_allowed(&loc);5635}56365637if (this->type->qualifier.precision != ast_precision_none &&5638!precision_qualifier_allowed(var->type)) {5639_mesa_glsl_error(&loc, state,5640"precision qualifiers apply only to floating point"5641", integer and opaque types");5642}56435644/* From section 4.1.7 of the GLSL 4.40 spec:5645*5646* "[Opaque types] can only be declared as function5647* parameters or uniform-qualified variables."5648*5649* From section 4.1.7 of the ARB_bindless_texture spec:5650*5651* "Samplers may be declared as shader inputs and outputs, as uniform5652* variables, as temporary variables, and as function parameters."5653*5654* From section 4.1.X of the ARB_bindless_texture spec:5655*5656* "Images may be declared as shader inputs and outputs, as uniform5657* variables, as temporary variables, and as function parameters."5658*/5659if (!this->type->qualifier.flags.q.uniform &&5660(var_type->contains_atomic() ||5661(!state->has_bindless() && var_type->contains_opaque()))) {5662_mesa_glsl_error(&loc, state,5663"%s variables must be declared uniform",5664state->has_bindless() ? "atomic" : "opaque");5665}56665667/* Process the initializer and add its instructions to a temporary5668* list. This list will be added to the instruction stream (below) after5669* the declaration is added. This is done because in some cases (such as5670* redeclarations) the declaration may not actually be added to the5671* instruction stream.5672*/5673exec_list initializer_instructions;56745675/* Examine var name here since var may get deleted in the next call */5676bool var_is_gl_id = is_gl_identifier(var->name);56775678bool is_redeclaration;5679var = get_variable_being_redeclared(&var, decl->get_location(), state,5680false /* allow_all_redeclarations */,5681&is_redeclaration);5682if (is_redeclaration) {5683if (var_is_gl_id &&5684var->data.how_declared == ir_var_declared_in_block) {5685_mesa_glsl_error(&loc, state,5686"`%s' has already been redeclared using "5687"gl_PerVertex", var->name);5688}5689var->data.how_declared = ir_var_declared_normally;5690}56915692if (decl->initializer != NULL) {5693result = process_initializer(var,5694decl, this->type,5695&initializer_instructions, state);5696} else {5697validate_array_dimensions(var_type, state, &loc);5698}56995700/* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:5701*5702* "It is an error to write to a const variable outside of5703* its declaration, so they must be initialized when5704* declared."5705*/5706if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {5707_mesa_glsl_error(& loc, state,5708"const declaration of `%s' must be initialized",5709decl->identifier);5710}57115712if (state->es_shader) {5713const glsl_type *const t = var->type;57145715/* Skip the unsized array check for TCS/TES/GS inputs & TCS outputs.5716*5717* The GL_OES_tessellation_shader spec says about inputs:5718*5719* "Declaring an array size is optional. If no size is specified,5720* it will be taken from the implementation-dependent maximum5721* patch size (gl_MaxPatchVertices)."5722*5723* and about TCS outputs:5724*5725* "If no size is specified, it will be taken from output patch5726* size declared in the shader."5727*5728* The GL_OES_geometry_shader spec says:5729*5730* "All geometry shader input unsized array declarations will be5731* sized by an earlier input primitive layout qualifier, when5732* present, as per the following table."5733*/5734const bool implicitly_sized =5735(var->data.mode == ir_var_shader_in &&5736state->stage >= MESA_SHADER_TESS_CTRL &&5737state->stage <= MESA_SHADER_GEOMETRY) ||5738(var->data.mode == ir_var_shader_out &&5739state->stage == MESA_SHADER_TESS_CTRL);57405741if (t->is_unsized_array() && !implicitly_sized)5742/* Section 10.17 of the GLSL ES 1.00 specification states that5743* unsized array declarations have been removed from the language.5744* Arrays that are sized using an initializer are still explicitly5745* sized. However, GLSL ES 1.00 does not allow array5746* initializers. That is only allowed in GLSL ES 3.00.5747*5748* Section 4.1.9 (Arrays) of the GLSL ES 3.00 spec says:5749*5750* "An array type can also be formed without specifying a size5751* if the definition includes an initializer:5752*5753* float x[] = float[2] (1.0, 2.0); // declares an array of size 25754* float y[] = float[] (1.0, 2.0, 3.0); // declares an array of size 35755*5756* float a[5];5757* float b[] = a;"5758*/5759_mesa_glsl_error(& loc, state,5760"unsized array declarations are not allowed in "5761"GLSL ES");5762}57635764/* Section 4.4.6.1 Atomic Counter Layout Qualifiers of the GLSL 4.60 spec:5765*5766* "It is a compile-time error to declare an unsized array of5767* atomic_uint"5768*/5769if (var->type->is_unsized_array() &&5770var->type->without_array()->base_type == GLSL_TYPE_ATOMIC_UINT) {5771_mesa_glsl_error(& loc, state,5772"Unsized array of atomic_uint is not allowed");5773}57745775/* If the declaration is not a redeclaration, there are a few additional5776* semantic checks that must be applied. In addition, variable that was5777* created for the declaration should be added to the IR stream.5778*/5779if (!is_redeclaration) {5780validate_identifier(decl->identifier, loc, state);57815782/* Add the variable to the symbol table. Note that the initializer's5783* IR was already processed earlier (though it hasn't been emitted5784* yet), without the variable in scope.5785*5786* This differs from most C-like languages, but it follows the GLSL5787* specification. From page 28 (page 34 of the PDF) of the GLSL 1.505788* spec:5789*5790* "Within a declaration, the scope of a name starts immediately5791* after the initializer if present or immediately after the name5792* being declared if not."5793*/5794if (!state->symbols->add_variable(var)) {5795YYLTYPE loc = this->get_location();5796_mesa_glsl_error(&loc, state, "name `%s' already taken in the "5797"current scope", decl->identifier);5798continue;5799}58005801/* Push the variable declaration to the top. It means that all the5802* variable declarations will appear in a funny last-to-first order,5803* but otherwise we run into trouble if a function is prototyped, a5804* global var is decled, then the function is defined with usage of5805* the global var. See glslparsertest's CorrectModule.frag.5806*/5807instructions->push_head(var);5808}58095810instructions->append_list(&initializer_instructions);5811}581258135814/* Generally, variable declarations do not have r-values. However,5815* one is used for the declaration in5816*5817* while (bool b = some_condition()) {5818* ...5819* }5820*5821* so we return the rvalue from the last seen declaration here.5822*/5823return result;5824}582558265827ir_rvalue *5828ast_parameter_declarator::hir(exec_list *instructions,5829struct _mesa_glsl_parse_state *state)5830{5831void *ctx = state;5832const struct glsl_type *type;5833const char *name = NULL;5834YYLTYPE loc = this->get_location();58355836type = this->type->glsl_type(& name, state);58375838if (type == NULL) {5839if (name != NULL) {5840_mesa_glsl_error(& loc, state,5841"invalid type `%s' in declaration of `%s'",5842name, this->identifier);5843} else {5844_mesa_glsl_error(& loc, state,5845"invalid type in declaration of `%s'",5846this->identifier);5847}58485849type = glsl_type::error_type;5850}58515852/* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:5853*5854* "Functions that accept no input arguments need not use void in the5855* argument list because prototypes (or definitions) are required and5856* therefore there is no ambiguity when an empty argument list "( )" is5857* declared. The idiom "(void)" as a parameter list is provided for5858* convenience."5859*5860* Placing this check here prevents a void parameter being set up5861* for a function, which avoids tripping up checks for main taking5862* parameters and lookups of an unnamed symbol.5863*/5864if (type->is_void()) {5865if (this->identifier != NULL)5866_mesa_glsl_error(& loc, state,5867"named parameter cannot have type `void'");58685869is_void = true;5870return NULL;5871}58725873if (formal_parameter && (this->identifier == NULL)) {5874_mesa_glsl_error(& loc, state, "formal parameter lacks a name");5875return NULL;5876}58775878/* This only handles "vec4 foo[..]". The earlier specifier->glsl_type(...)5879* call already handled the "vec4[..] foo" case.5880*/5881type = process_array_type(&loc, type, this->array_specifier, state);58825883if (!type->is_error() && type->is_unsized_array()) {5884_mesa_glsl_error(&loc, state, "arrays passed as parameters must have "5885"a declared size");5886type = glsl_type::error_type;5887}58885889is_void = false;5890ir_variable *var = new(ctx)5891ir_variable(type, this->identifier, ir_var_function_in);58925893/* Apply any specified qualifiers to the parameter declaration. Note that5894* for function parameters the default mode is 'in'.5895*/5896apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc,5897true);58985899if (((1u << var->data.mode) & state->zero_init) &&5900(var->type->is_numeric() || var->type->is_boolean())) {5901const ir_constant_data data = { { 0 } };5902var->data.has_initializer = true;5903var->data.is_implicit_initializer = true;5904var->constant_initializer = new(var) ir_constant(var->type, &data);5905}59065907/* From section 4.1.7 of the GLSL 4.40 spec:5908*5909* "Opaque variables cannot be treated as l-values; hence cannot5910* be used as out or inout function parameters, nor can they be5911* assigned into."5912*5913* From section 4.1.7 of the ARB_bindless_texture spec:5914*5915* "Samplers can be used as l-values, so can be assigned into and used5916* as "out" and "inout" function parameters."5917*5918* From section 4.1.X of the ARB_bindless_texture spec:5919*5920* "Images can be used as l-values, so can be assigned into and used as5921* "out" and "inout" function parameters."5922*/5923if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)5924&& (type->contains_atomic() ||5925(!state->has_bindless() && type->contains_opaque()))) {5926_mesa_glsl_error(&loc, state, "out and inout parameters cannot "5927"contain %s variables",5928state->has_bindless() ? "atomic" : "opaque");5929type = glsl_type::error_type;5930}59315932/* From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:5933*5934* "When calling a function, expressions that do not evaluate to5935* l-values cannot be passed to parameters declared as out or inout."5936*5937* From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:5938*5939* "Other binary or unary expressions, non-dereferenced arrays,5940* function names, swizzles with repeated fields, and constants5941* cannot be l-values."5942*5943* So for GLSL 1.10, passing an array as an out or inout parameter is not5944* allowed. This restriction is removed in GLSL 1.20, and in GLSL ES.5945*/5946if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)5947&& type->is_array()5948&& !state->check_version(120, 100, &loc,5949"arrays cannot be out or inout parameters")) {5950type = glsl_type::error_type;5951}59525953instructions->push_tail(var);59545955/* Parameter declarations do not have r-values.5956*/5957return NULL;5958}595959605961void5962ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,5963bool formal,5964exec_list *ir_parameters,5965_mesa_glsl_parse_state *state)5966{5967ast_parameter_declarator *void_param = NULL;5968unsigned count = 0;59695970foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {5971param->formal_parameter = formal;5972param->hir(ir_parameters, state);59735974if (param->is_void)5975void_param = param;59765977count++;5978}59795980if ((void_param != NULL) && (count > 1)) {5981YYLTYPE loc = void_param->get_location();59825983_mesa_glsl_error(& loc, state,5984"`void' parameter must be only parameter");5985}5986}598759885989void5990emit_function(_mesa_glsl_parse_state *state, ir_function *f)5991{5992/* IR invariants disallow function declarations or definitions5993* nested within other function definitions. But there is no5994* requirement about the relative order of function declarations5995* and definitions with respect to one another. So simply insert5996* the new ir_function block at the end of the toplevel instruction5997* list.5998*/5999state->toplevel_ir->push_tail(f);6000}600160026003ir_rvalue *6004ast_function::hir(exec_list *instructions,6005struct _mesa_glsl_parse_state *state)6006{6007void *ctx = state;6008ir_function *f = NULL;6009ir_function_signature *sig = NULL;6010exec_list hir_parameters;6011YYLTYPE loc = this->get_location();60126013const char *const name = identifier;60146015/* New functions are always added to the top-level IR instruction stream,6016* so this instruction list pointer is ignored. See also emit_function6017* (called below).6018*/6019(void) instructions;60206021/* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,6022*6023* "Function declarations (prototypes) cannot occur inside of functions;6024* they must be at global scope, or for the built-in functions, outside6025* the global scope."6026*6027* From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,6028*6029* "User defined functions may only be defined within the global scope."6030*6031* Note that this language does not appear in GLSL 1.10.6032*/6033if ((state->current_function != NULL) &&6034state->is_version(120, 100)) {6035YYLTYPE loc = this->get_location();6036_mesa_glsl_error(&loc, state,6037"declaration of function `%s' not allowed within "6038"function body", name);6039}60406041validate_identifier(name, this->get_location(), state);60426043/* Convert the list of function parameters to HIR now so that they can be6044* used below to compare this function's signature with previously seen6045* signatures for functions with the same name.6046*/6047ast_parameter_declarator::parameters_to_hir(& this->parameters,6048is_definition,6049& hir_parameters, state);60506051const char *return_type_name;6052const glsl_type *return_type =6053this->return_type->glsl_type(& return_type_name, state);60546055if (!return_type) {6056YYLTYPE loc = this->get_location();6057_mesa_glsl_error(&loc, state,6058"function `%s' has undeclared return type `%s'",6059name, return_type_name);6060return_type = glsl_type::error_type;6061}60626063/* ARB_shader_subroutine states:6064* "Subroutine declarations cannot be prototyped. It is an error to prepend6065* subroutine(...) to a function declaration."6066*/6067if (this->return_type->qualifier.subroutine_list && !is_definition) {6068YYLTYPE loc = this->get_location();6069_mesa_glsl_error(&loc, state,6070"function declaration `%s' cannot have subroutine prepended",6071name);6072}60736074/* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:6075* "No qualifier is allowed on the return type of a function."6076*/6077if (this->return_type->has_qualifiers(state)) {6078YYLTYPE loc = this->get_location();6079_mesa_glsl_error(& loc, state,6080"function `%s' return type has qualifiers", name);6081}60826083/* Section 6.1 (Function Definitions) of the GLSL 1.20 spec says:6084*6085* "Arrays are allowed as arguments and as the return type. In both6086* cases, the array must be explicitly sized."6087*/6088if (return_type->is_unsized_array()) {6089YYLTYPE loc = this->get_location();6090_mesa_glsl_error(& loc, state,6091"function `%s' return type array must be explicitly "6092"sized", name);6093}60946095/* From Section 6.1 (Function Definitions) of the GLSL 1.00 spec:6096*6097* "Arrays are allowed as arguments, but not as the return type. [...]6098* The return type can also be a structure if the structure does not6099* contain an array."6100*/6101if (state->language_version == 100 && return_type->contains_array()) {6102YYLTYPE loc = this->get_location();6103_mesa_glsl_error(& loc, state,6104"function `%s' return type contains an array", name);6105}61066107/* From section 4.1.7 of the GLSL 4.40 spec:6108*6109* "[Opaque types] can only be declared as function parameters6110* or uniform-qualified variables."6111*6112* The ARB_bindless_texture spec doesn't clearly state this, but as it says6113* "Replace Section 4.1.7 (Samplers), p. 25" and, "Replace Section 4.1.X,6114* (Images)", this should be allowed.6115*/6116if (return_type->contains_atomic() ||6117(!state->has_bindless() && return_type->contains_opaque())) {6118YYLTYPE loc = this->get_location();6119_mesa_glsl_error(&loc, state,6120"function `%s' return type can't contain an %s type",6121name, state->has_bindless() ? "atomic" : "opaque");6122}61236124/**/6125if (return_type->is_subroutine()) {6126YYLTYPE loc = this->get_location();6127_mesa_glsl_error(&loc, state,6128"function `%s' return type can't be a subroutine type",6129name);6130}61316132/* Get the precision for the return type */6133unsigned return_precision;61346135if (state->es_shader) {6136YYLTYPE loc = this->get_location();6137return_precision =6138select_gles_precision(this->return_type->qualifier.precision,6139return_type,6140state,6141&loc);6142} else {6143return_precision = GLSL_PRECISION_NONE;6144}61456146/* Create an ir_function if one doesn't already exist. */6147f = state->symbols->get_function(name);6148if (f == NULL) {6149f = new(ctx) ir_function(name);6150if (!this->return_type->qualifier.is_subroutine_decl()) {6151if (!state->symbols->add_function(f)) {6152/* This function name shadows a non-function use of the same name. */6153YYLTYPE loc = this->get_location();6154_mesa_glsl_error(&loc, state, "function name `%s' conflicts with "6155"non-function", name);6156return NULL;6157}6158}6159emit_function(state, f);6160}61616162/* From GLSL ES 3.0 spec, chapter 6.1 "Function Definitions", page 71:6163*6164* "A shader cannot redefine or overload built-in functions."6165*6166* While in GLSL ES 1.0 specification, chapter 8 "Built-in Functions":6167*6168* "User code can overload the built-in functions but cannot redefine6169* them."6170*/6171if (state->es_shader) {6172/* Local shader has no exact candidates; check the built-ins. */6173if (state->language_version >= 300 &&6174_mesa_glsl_has_builtin_function(state, name)) {6175YYLTYPE loc = this->get_location();6176_mesa_glsl_error(& loc, state,6177"A shader cannot redefine or overload built-in "6178"function `%s' in GLSL ES 3.00", name);6179return NULL;6180}61816182if (state->language_version == 100) {6183ir_function_signature *sig =6184_mesa_glsl_find_builtin_function(state, name, &hir_parameters);6185if (sig && sig->is_builtin()) {6186_mesa_glsl_error(& loc, state,6187"A shader cannot redefine built-in "6188"function `%s' in GLSL ES 1.00", name);6189}6190}6191}61926193/* Verify that this function's signature either doesn't match a previously6194* seen signature for a function with the same name, or, if a match is found,6195* that the previously seen signature does not have an associated definition.6196*/6197if (state->es_shader || f->has_user_signature()) {6198sig = f->exact_matching_signature(state, &hir_parameters);6199if (sig != NULL) {6200const char *badvar = sig->qualifiers_match(&hir_parameters);6201if (badvar != NULL) {6202YYLTYPE loc = this->get_location();62036204_mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "6205"qualifiers don't match prototype", name, badvar);6206}62076208if (sig->return_type != return_type) {6209YYLTYPE loc = this->get_location();62106211_mesa_glsl_error(&loc, state, "function `%s' return type doesn't "6212"match prototype", name);6213}62146215if (sig->return_precision != return_precision) {6216YYLTYPE loc = this->get_location();62176218_mesa_glsl_error(&loc, state, "function `%s' return type precision "6219"doesn't match prototype", name);6220}62216222if (sig->is_defined) {6223if (is_definition) {6224YYLTYPE loc = this->get_location();6225_mesa_glsl_error(& loc, state, "function `%s' redefined", name);6226} else {6227/* We just encountered a prototype that exactly matches a6228* function that's already been defined. This is redundant,6229* and we should ignore it.6230*/6231return NULL;6232}6233} else if (state->language_version == 100 && !is_definition) {6234/* From the GLSL 1.00 spec, section 4.2.7:6235*6236* "A particular variable, structure or function declaration6237* may occur at most once within a scope with the exception6238* that a single function prototype plus the corresponding6239* function definition are allowed."6240*/6241YYLTYPE loc = this->get_location();6242_mesa_glsl_error(&loc, state, "function `%s' redeclared", name);6243}6244}6245}62466247/* Verify the return type of main() */6248if (strcmp(name, "main") == 0) {6249if (! return_type->is_void()) {6250YYLTYPE loc = this->get_location();62516252_mesa_glsl_error(& loc, state, "main() must return void");6253}62546255if (!hir_parameters.is_empty()) {6256YYLTYPE loc = this->get_location();62576258_mesa_glsl_error(& loc, state, "main() must not take any parameters");6259}6260}62616262/* Finish storing the information about this new function in its signature.6263*/6264if (sig == NULL) {6265sig = new(ctx) ir_function_signature(return_type);6266sig->return_precision = return_precision;6267f->add_signature(sig);6268}62696270sig->replace_parameters(&hir_parameters);6271signature = sig;62726273if (this->return_type->qualifier.subroutine_list) {6274int idx;62756276if (this->return_type->qualifier.flags.q.explicit_index) {6277unsigned qual_index;6278if (process_qualifier_constant(state, &loc, "index",6279this->return_type->qualifier.index,6280&qual_index)) {6281if (!state->has_explicit_uniform_location()) {6282_mesa_glsl_error(&loc, state, "subroutine index requires "6283"GL_ARB_explicit_uniform_location or "6284"GLSL 4.30");6285} else if (qual_index >= MAX_SUBROUTINES) {6286_mesa_glsl_error(&loc, state,6287"invalid subroutine index (%d) index must "6288"be a number between 0 and "6289"GL_MAX_SUBROUTINES - 1 (%d)", qual_index,6290MAX_SUBROUTINES - 1);6291} else {6292f->subroutine_index = qual_index;6293}6294}6295}62966297f->num_subroutine_types = this->return_type->qualifier.subroutine_list->declarations.length();6298f->subroutine_types = ralloc_array(state, const struct glsl_type *,6299f->num_subroutine_types);6300idx = 0;6301foreach_list_typed(ast_declaration, decl, link, &this->return_type->qualifier.subroutine_list->declarations) {6302const struct glsl_type *type;6303/* the subroutine type must be already declared */6304type = state->symbols->get_type(decl->identifier);6305if (!type) {6306_mesa_glsl_error(& loc, state, "unknown type '%s' in subroutine function definition", decl->identifier);6307}63086309for (int i = 0; i < state->num_subroutine_types; i++) {6310ir_function *fn = state->subroutine_types[i];6311ir_function_signature *tsig = NULL;63126313if (strcmp(fn->name, decl->identifier))6314continue;63156316tsig = fn->matching_signature(state, &sig->parameters,6317false);6318if (!tsig) {6319_mesa_glsl_error(& loc, state, "subroutine type mismatch '%s' - signatures do not match\n", decl->identifier);6320} else {6321if (tsig->return_type != sig->return_type) {6322_mesa_glsl_error(& loc, state, "subroutine type mismatch '%s' - return types do not match\n", decl->identifier);6323}6324}6325}6326f->subroutine_types[idx++] = type;6327}6328state->subroutines = (ir_function **)reralloc(state, state->subroutines,6329ir_function *,6330state->num_subroutines + 1);6331state->subroutines[state->num_subroutines] = f;6332state->num_subroutines++;63336334}63356336if (this->return_type->qualifier.is_subroutine_decl()) {6337if (!state->symbols->add_type(this->identifier, glsl_type::get_subroutine_instance(this->identifier))) {6338_mesa_glsl_error(& loc, state, "type '%s' previously defined", this->identifier);6339return NULL;6340}6341state->subroutine_types = (ir_function **)reralloc(state, state->subroutine_types,6342ir_function *,6343state->num_subroutine_types + 1);6344state->subroutine_types[state->num_subroutine_types] = f;6345state->num_subroutine_types++;63466347f->is_subroutine = true;6348}63496350/* Function declarations (prototypes) do not have r-values.6351*/6352return NULL;6353}635463556356ir_rvalue *6357ast_function_definition::hir(exec_list *instructions,6358struct _mesa_glsl_parse_state *state)6359{6360prototype->is_definition = true;6361prototype->hir(instructions, state);63626363ir_function_signature *signature = prototype->signature;6364if (signature == NULL)6365return NULL;63666367assert(state->current_function == NULL);6368state->current_function = signature;6369state->found_return = false;6370state->found_begin_interlock = false;6371state->found_end_interlock = false;63726373/* Duplicate parameters declared in the prototype as concrete variables.6374* Add these to the symbol table.6375*/6376state->symbols->push_scope();6377foreach_in_list(ir_variable, var, &signature->parameters) {6378assert(var->as_variable() != NULL);63796380/* The only way a parameter would "exist" is if two parameters have6381* the same name.6382*/6383if (state->symbols->name_declared_this_scope(var->name)) {6384YYLTYPE loc = this->get_location();63856386_mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);6387} else {6388state->symbols->add_variable(var);6389}6390}63916392/* Convert the body of the function to HIR. */6393this->body->hir(&signature->body, state);6394signature->is_defined = true;63956396state->symbols->pop_scope();63976398assert(state->current_function == signature);6399state->current_function = NULL;64006401if (!signature->return_type->is_void() && !state->found_return) {6402YYLTYPE loc = this->get_location();6403_mesa_glsl_error(& loc, state, "function `%s' has non-void return type "6404"%s, but no return statement",6405signature->function_name(),6406signature->return_type->name);6407}64086409/* Function definitions do not have r-values.6410*/6411return NULL;6412}641364146415ir_rvalue *6416ast_jump_statement::hir(exec_list *instructions,6417struct _mesa_glsl_parse_state *state)6418{6419void *ctx = state;64206421switch (mode) {6422case ast_return: {6423ir_return *inst;6424assert(state->current_function);64256426if (opt_return_value) {6427ir_rvalue *ret = opt_return_value->hir(instructions, state);64286429/* The value of the return type can be NULL if the shader says6430* 'return foo();' and foo() is a function that returns void.6431*6432* NOTE: The GLSL spec doesn't say that this is an error. The type6433* of the return value is void. If the return type of the function is6434* also void, then this should compile without error. Seriously.6435*/6436const glsl_type *const ret_type =6437(ret == NULL) ? glsl_type::void_type : ret->type;64386439/* Implicit conversions are not allowed for return values prior to6440* ARB_shading_language_420pack.6441*/6442if (state->current_function->return_type != ret_type) {6443YYLTYPE loc = this->get_location();64446445if (state->has_420pack()) {6446if (!apply_implicit_conversion(state->current_function->return_type,6447ret, state)6448|| (ret->type != state->current_function->return_type)) {6449_mesa_glsl_error(& loc, state,6450"could not implicitly convert return value "6451"to %s, in function `%s'",6452state->current_function->return_type->name,6453state->current_function->function_name());6454}6455} else {6456_mesa_glsl_error(& loc, state,6457"`return' with wrong type %s, in function `%s' "6458"returning %s",6459ret_type->name,6460state->current_function->function_name(),6461state->current_function->return_type->name);6462}6463} else if (state->current_function->return_type->base_type ==6464GLSL_TYPE_VOID) {6465YYLTYPE loc = this->get_location();64666467/* The ARB_shading_language_420pack, GLSL ES 3.0, and GLSL 4.206468* specs add a clarification:6469*6470* "A void function can only use return without a return argument, even if6471* the return argument has void type. Return statements only accept values:6472*6473* void func1() { }6474* void func2() { return func1(); } // illegal return statement"6475*/6476_mesa_glsl_error(& loc, state,6477"void functions can only use `return' without a "6478"return argument");6479}64806481inst = new(ctx) ir_return(ret);6482} else {6483if (state->current_function->return_type->base_type !=6484GLSL_TYPE_VOID) {6485YYLTYPE loc = this->get_location();64866487_mesa_glsl_error(& loc, state,6488"`return' with no value, in function %s returning "6489"non-void",6490state->current_function->function_name());6491}6492inst = new(ctx) ir_return;6493}64946495state->found_return = true;6496instructions->push_tail(inst);6497break;6498}64996500case ast_discard:6501if (state->stage != MESA_SHADER_FRAGMENT) {6502YYLTYPE loc = this->get_location();65036504_mesa_glsl_error(& loc, state,6505"`discard' may only appear in a fragment shader");6506}6507instructions->push_tail(new(ctx) ir_discard);6508break;65096510case ast_break:6511case ast_continue:6512if (mode == ast_continue &&6513state->loop_nesting_ast == NULL) {6514YYLTYPE loc = this->get_location();65156516_mesa_glsl_error(& loc, state, "continue may only appear in a loop");6517} else if (mode == ast_break &&6518state->loop_nesting_ast == NULL &&6519state->switch_state.switch_nesting_ast == NULL) {6520YYLTYPE loc = this->get_location();65216522_mesa_glsl_error(& loc, state,6523"break may only appear in a loop or a switch");6524} else {6525/* For a loop, inline the for loop expression again, since we don't6526* know where near the end of the loop body the normal copy of it is6527* going to be placed. Same goes for the condition for a do-while6528* loop.6529*/6530if (state->loop_nesting_ast != NULL &&6531mode == ast_continue && !state->switch_state.is_switch_innermost) {6532if (state->loop_nesting_ast->rest_expression) {6533state->loop_nesting_ast->rest_expression->hir(instructions,6534state);6535}6536if (state->loop_nesting_ast->mode ==6537ast_iteration_statement::ast_do_while) {6538state->loop_nesting_ast->condition_to_hir(instructions, state);6539}6540}65416542if (state->switch_state.is_switch_innermost &&6543mode == ast_continue) {6544/* Set 'continue_inside' to true. */6545ir_rvalue *const true_val = new (ctx) ir_constant(true);6546ir_dereference_variable *deref_continue_inside_var =6547new(ctx) ir_dereference_variable(state->switch_state.continue_inside);6548instructions->push_tail(new(ctx) ir_assignment(deref_continue_inside_var,6549true_val));65506551/* Break out from the switch, continue for the loop will6552* be called right after switch. */6553ir_loop_jump *const jump =6554new(ctx) ir_loop_jump(ir_loop_jump::jump_break);6555instructions->push_tail(jump);65566557} else if (state->switch_state.is_switch_innermost &&6558mode == ast_break) {6559/* Force break out of switch by inserting a break. */6560ir_loop_jump *const jump =6561new(ctx) ir_loop_jump(ir_loop_jump::jump_break);6562instructions->push_tail(jump);6563} else {6564ir_loop_jump *const jump =6565new(ctx) ir_loop_jump((mode == ast_break)6566? ir_loop_jump::jump_break6567: ir_loop_jump::jump_continue);6568instructions->push_tail(jump);6569}6570}65716572break;6573}65746575/* Jump instructions do not have r-values.6576*/6577return NULL;6578}657965806581ir_rvalue *6582ast_demote_statement::hir(exec_list *instructions,6583struct _mesa_glsl_parse_state *state)6584{6585void *ctx = state;65866587if (state->stage != MESA_SHADER_FRAGMENT) {6588YYLTYPE loc = this->get_location();65896590_mesa_glsl_error(& loc, state,6591"`demote' may only appear in a fragment shader");6592}65936594instructions->push_tail(new(ctx) ir_demote);65956596return NULL;6597}659865996600ir_rvalue *6601ast_selection_statement::hir(exec_list *instructions,6602struct _mesa_glsl_parse_state *state)6603{6604void *ctx = state;66056606ir_rvalue *const condition = this->condition->hir(instructions, state);66076608/* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:6609*6610* "Any expression whose type evaluates to a Boolean can be used as the6611* conditional expression bool-expression. Vector types are not accepted6612* as the expression to if."6613*6614* The checks are separated so that higher quality diagnostics can be6615* generated for cases where both rules are violated.6616*/6617if (!condition->type->is_boolean() || !condition->type->is_scalar()) {6618YYLTYPE loc = this->condition->get_location();66196620_mesa_glsl_error(& loc, state, "if-statement condition must be scalar "6621"boolean");6622}66236624ir_if *const stmt = new(ctx) ir_if(condition);66256626if (then_statement != NULL) {6627state->symbols->push_scope();6628then_statement->hir(& stmt->then_instructions, state);6629state->symbols->pop_scope();6630}66316632if (else_statement != NULL) {6633state->symbols->push_scope();6634else_statement->hir(& stmt->else_instructions, state);6635state->symbols->pop_scope();6636}66376638instructions->push_tail(stmt);66396640/* if-statements do not have r-values.6641*/6642return NULL;6643}664466456646struct case_label {6647/** Value of the case label. */6648unsigned value;66496650/** Does this label occur after the default? */6651bool after_default;66526653/**6654* AST for the case label.6655*6656* This is only used to generate error messages for duplicate labels.6657*/6658ast_expression *ast;6659};66606661/* Used for detection of duplicate case values, compare6662* given contents directly.6663*/6664static bool6665compare_case_value(const void *a, const void *b)6666{6667return ((struct case_label *) a)->value == ((struct case_label *) b)->value;6668}666966706671/* Used for detection of duplicate case values, just6672* returns key contents as is.6673*/6674static unsigned6675key_contents(const void *key)6676{6677return ((struct case_label *) key)->value;6678}66796680void6681ast_switch_statement::eval_test_expression(exec_list *instructions,6682struct _mesa_glsl_parse_state *state)6683{6684if (test_val == NULL)6685test_val = this->test_expression->hir(instructions, state);6686}66876688ir_rvalue *6689ast_switch_statement::hir(exec_list *instructions,6690struct _mesa_glsl_parse_state *state)6691{6692void *ctx = state;66936694this->eval_test_expression(instructions, state);66956696/* From page 66 (page 55 of the PDF) of the GLSL 1.50 spec:6697*6698* "The type of init-expression in a switch statement must be a6699* scalar integer."6700*/6701if (!test_val->type->is_scalar() ||6702!test_val->type->is_integer_32()) {6703YYLTYPE loc = this->test_expression->get_location();67046705_mesa_glsl_error(& loc,6706state,6707"switch-statement expression must be scalar "6708"integer");6709return NULL;6710}67116712/* Track the switch-statement nesting in a stack-like manner.6713*/6714struct glsl_switch_state saved = state->switch_state;67156716state->switch_state.is_switch_innermost = true;6717state->switch_state.switch_nesting_ast = this;6718state->switch_state.labels_ht =6719_mesa_hash_table_create(NULL, key_contents,6720compare_case_value);6721state->switch_state.previous_default = NULL;67226723/* Initalize is_fallthru state to false.6724*/6725ir_rvalue *const is_fallthru_val = new (ctx) ir_constant(false);6726state->switch_state.is_fallthru_var =6727new(ctx) ir_variable(glsl_type::bool_type,6728"switch_is_fallthru_tmp",6729ir_var_temporary);6730instructions->push_tail(state->switch_state.is_fallthru_var);67316732ir_dereference_variable *deref_is_fallthru_var =6733new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);6734instructions->push_tail(new(ctx) ir_assignment(deref_is_fallthru_var,6735is_fallthru_val));67366737/* Initialize continue_inside state to false.6738*/6739state->switch_state.continue_inside =6740new(ctx) ir_variable(glsl_type::bool_type,6741"continue_inside_tmp",6742ir_var_temporary);6743instructions->push_tail(state->switch_state.continue_inside);67446745ir_rvalue *const false_val = new (ctx) ir_constant(false);6746ir_dereference_variable *deref_continue_inside_var =6747new(ctx) ir_dereference_variable(state->switch_state.continue_inside);6748instructions->push_tail(new(ctx) ir_assignment(deref_continue_inside_var,6749false_val));67506751state->switch_state.run_default =6752new(ctx) ir_variable(glsl_type::bool_type,6753"run_default_tmp",6754ir_var_temporary);6755instructions->push_tail(state->switch_state.run_default);67566757/* Loop around the switch is used for flow control. */6758ir_loop * loop = new(ctx) ir_loop();6759instructions->push_tail(loop);67606761/* Cache test expression.6762*/6763test_to_hir(&loop->body_instructions, state);67646765/* Emit code for body of switch stmt.6766*/6767body->hir(&loop->body_instructions, state);67686769/* Insert a break at the end to exit loop. */6770ir_loop_jump *jump = new(ctx) ir_loop_jump(ir_loop_jump::jump_break);6771loop->body_instructions.push_tail(jump);67726773/* If we are inside loop, check if continue got called inside switch. */6774if (state->loop_nesting_ast != NULL) {6775ir_dereference_variable *deref_continue_inside =6776new(ctx) ir_dereference_variable(state->switch_state.continue_inside);6777ir_if *irif = new(ctx) ir_if(deref_continue_inside);6778ir_loop_jump *jump = new(ctx) ir_loop_jump(ir_loop_jump::jump_continue);67796780if (state->loop_nesting_ast != NULL) {6781if (state->loop_nesting_ast->rest_expression) {6782state->loop_nesting_ast->rest_expression->hir(&irif->then_instructions,6783state);6784}6785if (state->loop_nesting_ast->mode ==6786ast_iteration_statement::ast_do_while) {6787state->loop_nesting_ast->condition_to_hir(&irif->then_instructions, state);6788}6789}6790irif->then_instructions.push_tail(jump);6791instructions->push_tail(irif);6792}67936794_mesa_hash_table_destroy(state->switch_state.labels_ht, NULL);67956796state->switch_state = saved;67976798/* Switch statements do not have r-values. */6799return NULL;6800}680168026803void6804ast_switch_statement::test_to_hir(exec_list *instructions,6805struct _mesa_glsl_parse_state *state)6806{6807void *ctx = state;68086809/* set to true to avoid a duplicate "use of uninitialized variable" warning6810* on the switch test case. The first one would be already raised when6811* getting the test_expression at ast_switch_statement::hir6812*/6813test_expression->set_is_lhs(true);6814/* Cache value of test expression. */6815this->eval_test_expression(instructions, state);68166817state->switch_state.test_var = new(ctx) ir_variable(test_val->type,6818"switch_test_tmp",6819ir_var_temporary);6820ir_dereference_variable *deref_test_var =6821new(ctx) ir_dereference_variable(state->switch_state.test_var);68226823instructions->push_tail(state->switch_state.test_var);6824instructions->push_tail(new(ctx) ir_assignment(deref_test_var, test_val));6825}682668276828ir_rvalue *6829ast_switch_body::hir(exec_list *instructions,6830struct _mesa_glsl_parse_state *state)6831{6832if (stmts != NULL)6833stmts->hir(instructions, state);68346835/* Switch bodies do not have r-values. */6836return NULL;6837}68386839ir_rvalue *6840ast_case_statement_list::hir(exec_list *instructions,6841struct _mesa_glsl_parse_state *state)6842{6843exec_list default_case, after_default, tmp;68446845foreach_list_typed (ast_case_statement, case_stmt, link, & this->cases) {6846case_stmt->hir(&tmp, state);68476848/* Default case. */6849if (state->switch_state.previous_default && default_case.is_empty()) {6850default_case.append_list(&tmp);6851continue;6852}68536854/* If default case found, append 'after_default' list. */6855if (!default_case.is_empty())6856after_default.append_list(&tmp);6857else6858instructions->append_list(&tmp);6859}68606861/* Handle the default case. This is done here because default might not be6862* the last case. We need to add checks against following cases first to see6863* if default should be chosen or not.6864*/6865if (!default_case.is_empty()) {6866ir_factory body(instructions, state);68676868ir_expression *cmp = NULL;68696870hash_table_foreach(state->switch_state.labels_ht, entry) {6871const struct case_label *const l = (struct case_label *) entry->data;68726873/* If the switch init-value is the value of one of the labels that6874* occurs after the default case, disable execution of the default6875* case.6876*/6877if (l->after_default) {6878ir_constant *const cnst =6879state->switch_state.test_var->type->base_type == GLSL_TYPE_UINT6880? body.constant(unsigned(l->value))6881: body.constant(int(l->value));68826883cmp = cmp == NULL6884? equal(cnst, state->switch_state.test_var)6885: logic_or(cmp, equal(cnst, state->switch_state.test_var));6886}6887}68886889if (cmp != NULL)6890body.emit(assign(state->switch_state.run_default, logic_not(cmp)));6891else6892body.emit(assign(state->switch_state.run_default, body.constant(true)));68936894/* Append default case and all cases after it. */6895instructions->append_list(&default_case);6896instructions->append_list(&after_default);6897}68986899/* Case statements do not have r-values. */6900return NULL;6901}69026903ir_rvalue *6904ast_case_statement::hir(exec_list *instructions,6905struct _mesa_glsl_parse_state *state)6906{6907labels->hir(instructions, state);69086909/* Guard case statements depending on fallthru state. */6910ir_dereference_variable *const deref_fallthru_guard =6911new(state) ir_dereference_variable(state->switch_state.is_fallthru_var);6912ir_if *const test_fallthru = new(state) ir_if(deref_fallthru_guard);69136914foreach_list_typed (ast_node, stmt, link, & this->stmts)6915stmt->hir(& test_fallthru->then_instructions, state);69166917instructions->push_tail(test_fallthru);69186919/* Case statements do not have r-values. */6920return NULL;6921}692269236924ir_rvalue *6925ast_case_label_list::hir(exec_list *instructions,6926struct _mesa_glsl_parse_state *state)6927{6928foreach_list_typed (ast_case_label, label, link, & this->labels)6929label->hir(instructions, state);69306931/* Case labels do not have r-values. */6932return NULL;6933}69346935ir_rvalue *6936ast_case_label::hir(exec_list *instructions,6937struct _mesa_glsl_parse_state *state)6938{6939ir_factory body(instructions, state);69406941ir_variable *const fallthru_var = state->switch_state.is_fallthru_var;69426943/* If not default case, ... */6944if (this->test_value != NULL) {6945/* Conditionally set fallthru state based on6946* comparison of cached test expression value to case label.6947*/6948ir_rvalue *const label_rval = this->test_value->hir(instructions, state);6949ir_constant *label_const =6950label_rval->constant_expression_value(body.mem_ctx);69516952if (!label_const) {6953YYLTYPE loc = this->test_value->get_location();69546955_mesa_glsl_error(& loc, state,6956"switch statement case label must be a "6957"constant expression");69586959/* Stuff a dummy value in to allow processing to continue. */6960label_const = body.constant(0);6961} else {6962hash_entry *entry =6963_mesa_hash_table_search(state->switch_state.labels_ht,6964&label_const->value.u[0]);69656966if (entry) {6967const struct case_label *const l =6968(struct case_label *) entry->data;6969const ast_expression *const previous_label = l->ast;6970YYLTYPE loc = this->test_value->get_location();69716972_mesa_glsl_error(& loc, state, "duplicate case value");69736974loc = previous_label->get_location();6975_mesa_glsl_error(& loc, state, "this is the previous case label");6976} else {6977struct case_label *l = ralloc(state->switch_state.labels_ht,6978struct case_label);69796980l->value = label_const->value.u[0];6981l->after_default = state->switch_state.previous_default != NULL;6982l->ast = this->test_value;69836984_mesa_hash_table_insert(state->switch_state.labels_ht,6985&label_const->value.u[0],6986l);6987}6988}69896990/* Create an r-value version of the ir_constant label here (after we may6991* have created a fake one in error cases) that can be passed to6992* apply_implicit_conversion below.6993*/6994ir_rvalue *label = label_const;69956996ir_rvalue *deref_test_var =6997new(body.mem_ctx) ir_dereference_variable(state->switch_state.test_var);69986999/*7000* From GLSL 4.40 specification section 6.2 ("Selection"):7001*7002* "The type of the init-expression value in a switch statement must7003* be a scalar int or uint. The type of the constant-expression value7004* in a case label also must be a scalar int or uint. When any pair7005* of these values is tested for "equal value" and the types do not7006* match, an implicit conversion will be done to convert the int to a7007* uint (see section 4.1.10 “Implicit Conversions”) before the compare7008* is done."7009*/7010if (label->type != state->switch_state.test_var->type) {7011YYLTYPE loc = this->test_value->get_location();70127013const glsl_type *type_a = label->type;7014const glsl_type *type_b = state->switch_state.test_var->type;70157016/* Check if int->uint implicit conversion is supported. */7017bool integer_conversion_supported =7018glsl_type::int_type->can_implicitly_convert_to(glsl_type::uint_type,7019state);70207021if ((!type_a->is_integer_32() || !type_b->is_integer_32()) ||7022!integer_conversion_supported) {7023_mesa_glsl_error(&loc, state, "type mismatch with switch "7024"init-expression and case label (%s != %s)",7025type_a->name, type_b->name);7026} else {7027/* Conversion of the case label. */7028if (type_a->base_type == GLSL_TYPE_INT) {7029if (!apply_implicit_conversion(glsl_type::uint_type,7030label, state))7031_mesa_glsl_error(&loc, state, "implicit type conversion error");7032} else {7033/* Conversion of the init-expression value. */7034if (!apply_implicit_conversion(glsl_type::uint_type,7035deref_test_var, state))7036_mesa_glsl_error(&loc, state, "implicit type conversion error");7037}7038}70397040/* If the implicit conversion was allowed, the types will already be7041* the same. If the implicit conversion wasn't allowed, smash the7042* type of the label anyway. This will prevent the expression7043* constructor (below) from failing an assertion.7044*/7045label->type = deref_test_var->type;7046}70477048body.emit(assign(fallthru_var,7049logic_or(fallthru_var, equal(label, deref_test_var))));7050} else { /* default case */7051if (state->switch_state.previous_default) {7052YYLTYPE loc = this->get_location();7053_mesa_glsl_error(& loc, state,7054"multiple default labels in one switch");70557056loc = state->switch_state.previous_default->get_location();7057_mesa_glsl_error(& loc, state, "this is the first default label");7058}7059state->switch_state.previous_default = this;70607061/* Set fallthru condition on 'run_default' bool. */7062body.emit(assign(fallthru_var,7063logic_or(fallthru_var,7064state->switch_state.run_default)));7065}70667067/* Case statements do not have r-values. */7068return NULL;7069}70707071void7072ast_iteration_statement::condition_to_hir(exec_list *instructions,7073struct _mesa_glsl_parse_state *state)7074{7075void *ctx = state;70767077if (condition != NULL) {7078ir_rvalue *const cond =7079condition->hir(instructions, state);70807081if ((cond == NULL)7082|| !cond->type->is_boolean() || !cond->type->is_scalar()) {7083YYLTYPE loc = condition->get_location();70847085_mesa_glsl_error(& loc, state,7086"loop condition must be scalar boolean");7087} else {7088/* As the first code in the loop body, generate a block that looks7089* like 'if (!condition) break;' as the loop termination condition.7090*/7091ir_rvalue *const not_cond =7092new(ctx) ir_expression(ir_unop_logic_not, cond);70937094ir_if *const if_stmt = new(ctx) ir_if(not_cond);70957096ir_jump *const break_stmt =7097new(ctx) ir_loop_jump(ir_loop_jump::jump_break);70987099if_stmt->then_instructions.push_tail(break_stmt);7100instructions->push_tail(if_stmt);7101}7102}7103}710471057106ir_rvalue *7107ast_iteration_statement::hir(exec_list *instructions,7108struct _mesa_glsl_parse_state *state)7109{7110void *ctx = state;71117112/* For-loops and while-loops start a new scope, but do-while loops do not.7113*/7114if (mode != ast_do_while)7115state->symbols->push_scope();71167117if (init_statement != NULL)7118init_statement->hir(instructions, state);71197120ir_loop *const stmt = new(ctx) ir_loop();7121instructions->push_tail(stmt);71227123/* Track the current loop nesting. */7124ast_iteration_statement *nesting_ast = state->loop_nesting_ast;71257126state->loop_nesting_ast = this;71277128/* Likewise, indicate that following code is closest to a loop,7129* NOT closest to a switch.7130*/7131bool saved_is_switch_innermost = state->switch_state.is_switch_innermost;7132state->switch_state.is_switch_innermost = false;71337134if (mode != ast_do_while)7135condition_to_hir(&stmt->body_instructions, state);71367137if (body != NULL)7138body->hir(& stmt->body_instructions, state);71397140if (rest_expression != NULL)7141rest_expression->hir(& stmt->body_instructions, state);71427143if (mode == ast_do_while)7144condition_to_hir(&stmt->body_instructions, state);71457146if (mode != ast_do_while)7147state->symbols->pop_scope();71487149/* Restore previous nesting before returning. */7150state->loop_nesting_ast = nesting_ast;7151state->switch_state.is_switch_innermost = saved_is_switch_innermost;71527153/* Loops do not have r-values.7154*/7155return NULL;7156}715771587159/**7160* Determine if the given type is valid for establishing a default precision7161* qualifier.7162*7163* From GLSL ES 3.00 section 4.5.4 ("Default Precision Qualifiers"):7164*7165* "The precision statement7166*7167* precision precision-qualifier type;7168*7169* can be used to establish a default precision qualifier. The type field7170* can be either int or float or any of the sampler types, and the7171* precision-qualifier can be lowp, mediump, or highp."7172*7173* GLSL ES 1.00 has similar language. GLSL 1.30 doesn't allow precision7174* qualifiers on sampler types, but this seems like an oversight (since the7175* intention of including these in GLSL 1.30 is to allow compatibility with ES7176* shaders). So we allow int, float, and all sampler types regardless of GLSL7177* version.7178*/7179static bool7180is_valid_default_precision_type(const struct glsl_type *const type)7181{7182if (type == NULL)7183return false;71847185switch (type->base_type) {7186case GLSL_TYPE_INT:7187case GLSL_TYPE_FLOAT:7188/* "int" and "float" are valid, but vectors and matrices are not. */7189return type->vector_elements == 1 && type->matrix_columns == 1;7190case GLSL_TYPE_SAMPLER:7191case GLSL_TYPE_IMAGE:7192case GLSL_TYPE_ATOMIC_UINT:7193return true;7194default:7195return false;7196}7197}719871997200ir_rvalue *7201ast_type_specifier::hir(exec_list *instructions,7202struct _mesa_glsl_parse_state *state)7203{7204if (this->default_precision == ast_precision_none && this->structure == NULL)7205return NULL;72067207YYLTYPE loc = this->get_location();72087209/* If this is a precision statement, check that the type to which it is7210* applied is either float or int.7211*7212* From section 4.5.3 of the GLSL 1.30 spec:7213* "The precision statement7214* precision precision-qualifier type;7215* can be used to establish a default precision qualifier. The type7216* field can be either int or float [...]. Any other types or7217* qualifiers will result in an error.7218*/7219if (this->default_precision != ast_precision_none) {7220if (!state->check_precision_qualifiers_allowed(&loc))7221return NULL;72227223if (this->structure != NULL) {7224_mesa_glsl_error(&loc, state,7225"precision qualifiers do not apply to structures");7226return NULL;7227}72287229if (this->array_specifier != NULL) {7230_mesa_glsl_error(&loc, state,7231"default precision statements do not apply to "7232"arrays");7233return NULL;7234}72357236const struct glsl_type *const type =7237state->symbols->get_type(this->type_name);7238if (!is_valid_default_precision_type(type)) {7239_mesa_glsl_error(&loc, state,7240"default precision statements apply only to "7241"float, int, and opaque types");7242return NULL;7243}72447245if (state->es_shader) {7246/* Section 4.5.3 (Default Precision Qualifiers) of the GLSL ES 1.007247* spec says:7248*7249* "Non-precision qualified declarations will use the precision7250* qualifier specified in the most recent precision statement7251* that is still in scope. The precision statement has the same7252* scoping rules as variable declarations. If it is declared7253* inside a compound statement, its effect stops at the end of7254* the innermost statement it was declared in. Precision7255* statements in nested scopes override precision statements in7256* outer scopes. Multiple precision statements for the same basic7257* type can appear inside the same scope, with later statements7258* overriding earlier statements within that scope."7259*7260* Default precision specifications follow the same scope rules as7261* variables. So, we can track the state of the default precision7262* qualifiers in the symbol table, and the rules will just work. This7263* is a slight abuse of the symbol table, but it has the semantics7264* that we want.7265*/7266state->symbols->add_default_precision_qualifier(this->type_name,7267this->default_precision);7268}72697270/* FINISHME: Translate precision statements into IR. */7271return NULL;7272}72737274/* _mesa_ast_set_aggregate_type() sets the <structure> field so that7275* process_record_constructor() can do type-checking on C-style initializer7276* expressions of structs, but ast_struct_specifier should only be translated7277* to HIR if it is declaring the type of a structure.7278*7279* The ->is_declaration field is false for initializers of variables7280* declared separately from the struct's type definition.7281*7282* struct S { ... }; (is_declaration = true)7283* struct T { ... } t = { ... }; (is_declaration = true)7284* S s = { ... }; (is_declaration = false)7285*/7286if (this->structure != NULL && this->structure->is_declaration)7287return this->structure->hir(instructions, state);72887289return NULL;7290}729172927293/**7294* Process a structure or interface block tree into an array of structure fields7295*7296* After parsing, where there are some syntax differnces, structures and7297* interface blocks are almost identical. They are similar enough that the7298* AST for each can be processed the same way into a set of7299* \c glsl_struct_field to describe the members.7300*7301* If we're processing an interface block, var_mode should be the type of the7302* interface block (ir_var_shader_in, ir_var_shader_out, ir_var_uniform or7303* ir_var_shader_storage). If we're processing a structure, var_mode should be7304* ir_var_auto.7305*7306* \return7307* The number of fields processed. A pointer to the array structure fields is7308* stored in \c *fields_ret.7309*/7310static unsigned7311ast_process_struct_or_iface_block_members(exec_list *instructions,7312struct _mesa_glsl_parse_state *state,7313exec_list *declarations,7314glsl_struct_field **fields_ret,7315bool is_interface,7316enum glsl_matrix_layout matrix_layout,7317bool allow_reserved_names,7318ir_variable_mode var_mode,7319ast_type_qualifier *layout,7320unsigned block_stream,7321unsigned block_xfb_buffer,7322unsigned block_xfb_offset,7323unsigned expl_location,7324unsigned expl_align)7325{7326unsigned decl_count = 0;7327unsigned next_offset = 0;73287329/* Make an initial pass over the list of fields to determine how7330* many there are. Each element in this list is an ast_declarator_list.7331* This means that we actually need to count the number of elements in the7332* 'declarations' list in each of the elements.7333*/7334foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {7335decl_count += decl_list->declarations.length();7336}73377338/* Allocate storage for the fields and process the field7339* declarations. As the declarations are processed, try to also convert7340* the types to HIR. This ensures that structure definitions embedded in7341* other structure definitions or in interface blocks are processed.7342*/7343glsl_struct_field *const fields = rzalloc_array(state, glsl_struct_field,7344decl_count);73457346bool first_member = true;7347bool first_member_has_explicit_location = false;73487349unsigned i = 0;7350foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {7351const char *type_name;7352YYLTYPE loc = decl_list->get_location();73537354decl_list->type->specifier->hir(instructions, state);73557356/* Section 4.1.8 (Structures) of the GLSL 1.10 spec says:7357*7358* "Anonymous structures are not supported; so embedded structures7359* must have a declarator. A name given to an embedded struct is7360* scoped at the same level as the struct it is embedded in."7361*7362* The same section of the GLSL 1.20 spec says:7363*7364* "Anonymous structures are not supported. Embedded structures are7365* not supported."7366*7367* The GLSL ES 1.00 and 3.00 specs have similar langauge. So, we allow7368* embedded structures in 1.10 only.7369*/7370if (state->language_version != 110 &&7371decl_list->type->specifier->structure != NULL)7372_mesa_glsl_error(&loc, state,7373"embedded structure declarations are not allowed");73747375const glsl_type *decl_type =7376decl_list->type->glsl_type(& type_name, state);73777378const struct ast_type_qualifier *const qual =7379&decl_list->type->qualifier;73807381/* From section 4.3.9 of the GLSL 4.40 spec:7382*7383* "[In interface blocks] opaque types are not allowed."7384*7385* It should be impossible for decl_type to be NULL here. Cases that7386* might naturally lead to decl_type being NULL, especially for the7387* is_interface case, will have resulted in compilation having7388* already halted due to a syntax error.7389*/7390assert(decl_type);73917392if (is_interface) {7393/* From section 4.3.7 of the ARB_bindless_texture spec:7394*7395* "(remove the following bullet from the last list on p. 39,7396* thereby permitting sampler types in interface blocks; image7397* types are also permitted in blocks by this extension)"7398*7399* * sampler types are not allowed7400*/7401if (decl_type->contains_atomic() ||7402(!state->has_bindless() && decl_type->contains_opaque())) {7403_mesa_glsl_error(&loc, state, "uniform/buffer in non-default "7404"interface block contains %s variable",7405state->has_bindless() ? "atomic" : "opaque");7406}7407} else {7408if (decl_type->contains_atomic()) {7409/* From section 4.1.7.3 of the GLSL 4.40 spec:7410*7411* "Members of structures cannot be declared as atomic counter7412* types."7413*/7414_mesa_glsl_error(&loc, state, "atomic counter in structure");7415}74167417if (!state->has_bindless() && decl_type->contains_image()) {7418/* FINISHME: Same problem as with atomic counters.7419* FINISHME: Request clarification from Khronos and add7420* FINISHME: spec quotation here.7421*/7422_mesa_glsl_error(&loc, state, "image in structure");7423}7424}74257426if (qual->flags.q.explicit_binding) {7427_mesa_glsl_error(&loc, state,7428"binding layout qualifier cannot be applied "7429"to struct or interface block members");7430}74317432if (is_interface) {7433if (!first_member) {7434if (!layout->flags.q.explicit_location &&7435((first_member_has_explicit_location &&7436!qual->flags.q.explicit_location) ||7437(!first_member_has_explicit_location &&7438qual->flags.q.explicit_location))) {7439_mesa_glsl_error(&loc, state,7440"when block-level location layout qualifier "7441"is not supplied either all members must "7442"have a location layout qualifier or all "7443"members must not have a location layout "7444"qualifier");7445}7446} else {7447first_member = false;7448first_member_has_explicit_location =7449qual->flags.q.explicit_location;7450}7451}74527453if (qual->flags.q.std140 ||7454qual->flags.q.std430 ||7455qual->flags.q.packed ||7456qual->flags.q.shared) {7457_mesa_glsl_error(&loc, state,7458"uniform/shader storage block layout qualifiers "7459"std140, std430, packed, and shared can only be "7460"applied to uniform/shader storage blocks, not "7461"members");7462}74637464if (qual->flags.q.constant) {7465_mesa_glsl_error(&loc, state,7466"const storage qualifier cannot be applied "7467"to struct or interface block members");7468}74697470validate_memory_qualifier_for_type(state, &loc, qual, decl_type);7471validate_image_format_qualifier_for_type(state, &loc, qual, decl_type);74727473/* From Section 4.4.2.3 (Geometry Outputs) of the GLSL 4.50 spec:7474*7475* "A block member may be declared with a stream identifier, but7476* the specified stream must match the stream associated with the7477* containing block."7478*/7479if (qual->flags.q.explicit_stream) {7480unsigned qual_stream;7481if (process_qualifier_constant(state, &loc, "stream",7482qual->stream, &qual_stream) &&7483qual_stream != block_stream) {7484_mesa_glsl_error(&loc, state, "stream layout qualifier on "7485"interface block member does not match "7486"the interface block (%u vs %u)", qual_stream,7487block_stream);7488}7489}74907491int xfb_buffer;7492unsigned explicit_xfb_buffer = 0;7493if (qual->flags.q.explicit_xfb_buffer) {7494unsigned qual_xfb_buffer;7495if (process_qualifier_constant(state, &loc, "xfb_buffer",7496qual->xfb_buffer, &qual_xfb_buffer)) {7497explicit_xfb_buffer = 1;7498if (qual_xfb_buffer != block_xfb_buffer)7499_mesa_glsl_error(&loc, state, "xfb_buffer layout qualifier on "7500"interface block member does not match "7501"the interface block (%u vs %u)",7502qual_xfb_buffer, block_xfb_buffer);7503}7504xfb_buffer = (int) qual_xfb_buffer;7505} else {7506if (layout)7507explicit_xfb_buffer = layout->flags.q.explicit_xfb_buffer;7508xfb_buffer = (int) block_xfb_buffer;7509}75107511int xfb_stride = -1;7512if (qual->flags.q.explicit_xfb_stride) {7513unsigned qual_xfb_stride;7514if (process_qualifier_constant(state, &loc, "xfb_stride",7515qual->xfb_stride, &qual_xfb_stride)) {7516xfb_stride = (int) qual_xfb_stride;7517}7518}75197520if (qual->flags.q.uniform && qual->has_interpolation()) {7521_mesa_glsl_error(&loc, state,7522"interpolation qualifiers cannot be used "7523"with uniform interface blocks");7524}75257526if ((qual->flags.q.uniform || !is_interface) &&7527qual->has_auxiliary_storage()) {7528_mesa_glsl_error(&loc, state,7529"auxiliary storage qualifiers cannot be used "7530"in uniform blocks or structures.");7531}75327533if (qual->flags.q.row_major || qual->flags.q.column_major) {7534if (!qual->flags.q.uniform && !qual->flags.q.buffer) {7535_mesa_glsl_error(&loc, state,7536"row_major and column_major can only be "7537"applied to interface blocks");7538} else7539validate_matrix_layout_for_type(state, &loc, decl_type, NULL);7540}75417542foreach_list_typed (ast_declaration, decl, link,7543&decl_list->declarations) {7544YYLTYPE loc = decl->get_location();75457546if (!allow_reserved_names)7547validate_identifier(decl->identifier, loc, state);75487549const struct glsl_type *field_type =7550process_array_type(&loc, decl_type, decl->array_specifier, state);7551validate_array_dimensions(field_type, state, &loc);7552fields[i].type = field_type;7553fields[i].name = decl->identifier;7554fields[i].interpolation =7555interpret_interpolation_qualifier(qual, field_type,7556var_mode, state, &loc);7557fields[i].centroid = qual->flags.q.centroid ? 1 : 0;7558fields[i].sample = qual->flags.q.sample ? 1 : 0;7559fields[i].patch = qual->flags.q.patch ? 1 : 0;7560fields[i].offset = -1;7561fields[i].explicit_xfb_buffer = explicit_xfb_buffer;7562fields[i].xfb_buffer = xfb_buffer;7563fields[i].xfb_stride = xfb_stride;75647565if (qual->flags.q.explicit_location) {7566unsigned qual_location;7567if (process_qualifier_constant(state, &loc, "location",7568qual->location, &qual_location)) {7569fields[i].location = qual_location +7570(fields[i].patch ? VARYING_SLOT_PATCH0 : VARYING_SLOT_VAR0);7571expl_location = fields[i].location +7572fields[i].type->count_attribute_slots(false);7573}7574} else {7575if (layout && layout->flags.q.explicit_location) {7576fields[i].location = expl_location;7577expl_location += fields[i].type->count_attribute_slots(false);7578} else {7579fields[i].location = -1;7580}7581}75827583if (qual->flags.q.explicit_component) {7584unsigned qual_component;7585if (process_qualifier_constant(state, &loc, "component",7586qual->component, &qual_component)) {7587validate_component_layout_for_type(state, &loc, fields[i].type,7588qual_component);7589fields[i].component = qual_component;7590}7591} else {7592fields[i].component = -1;7593}75947595/* Offset can only be used with std430 and std140 layouts an initial7596* value of 0 is used for error detection.7597*/7598unsigned align = 0;7599unsigned size = 0;7600if (layout) {7601bool row_major;7602if (qual->flags.q.row_major ||7603matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR) {7604row_major = true;7605} else {7606row_major = false;7607}76087609if(layout->flags.q.std140) {7610align = field_type->std140_base_alignment(row_major);7611size = field_type->std140_size(row_major);7612} else if (layout->flags.q.std430) {7613align = field_type->std430_base_alignment(row_major);7614size = field_type->std430_size(row_major);7615}7616}76177618if (qual->flags.q.explicit_offset) {7619unsigned qual_offset;7620if (process_qualifier_constant(state, &loc, "offset",7621qual->offset, &qual_offset)) {7622if (align != 0 && size != 0) {7623if (next_offset > qual_offset)7624_mesa_glsl_error(&loc, state, "layout qualifier "7625"offset overlaps previous member");76267627if (qual_offset % align) {7628_mesa_glsl_error(&loc, state, "layout qualifier offset "7629"must be a multiple of the base "7630"alignment of %s", field_type->name);7631}7632fields[i].offset = qual_offset;7633next_offset = qual_offset + size;7634} else {7635_mesa_glsl_error(&loc, state, "offset can only be used "7636"with std430 and std140 layouts");7637}7638}7639}76407641if (qual->flags.q.explicit_align || expl_align != 0) {7642unsigned offset = fields[i].offset != -1 ? fields[i].offset :7643next_offset;7644if (align == 0 || size == 0) {7645_mesa_glsl_error(&loc, state, "align can only be used with "7646"std430 and std140 layouts");7647} else if (qual->flags.q.explicit_align) {7648unsigned member_align;7649if (process_qualifier_constant(state, &loc, "align",7650qual->align, &member_align)) {7651if (member_align == 0 ||7652member_align & (member_align - 1)) {7653_mesa_glsl_error(&loc, state, "align layout qualifier "7654"is not a power of 2");7655} else {7656fields[i].offset = glsl_align(offset, member_align);7657next_offset = fields[i].offset + size;7658}7659}7660} else {7661fields[i].offset = glsl_align(offset, expl_align);7662next_offset = fields[i].offset + size;7663}7664} else if (!qual->flags.q.explicit_offset) {7665if (align != 0 && size != 0)7666next_offset = glsl_align(next_offset, align) + size;7667}76687669/* From the ARB_enhanced_layouts spec:7670*7671* "The given offset applies to the first component of the first7672* member of the qualified entity. Then, within the qualified7673* entity, subsequent components are each assigned, in order, to7674* the next available offset aligned to a multiple of that7675* component's size. Aggregate types are flattened down to the7676* component level to get this sequence of components."7677*/7678if (qual->flags.q.explicit_xfb_offset) {7679unsigned xfb_offset;7680if (process_qualifier_constant(state, &loc, "xfb_offset",7681qual->offset, &xfb_offset)) {7682fields[i].offset = xfb_offset;7683block_xfb_offset = fields[i].offset +76844 * field_type->component_slots();7685}7686} else {7687if (layout && layout->flags.q.explicit_xfb_offset) {7688unsigned align = field_type->is_64bit() ? 8 : 4;7689fields[i].offset = glsl_align(block_xfb_offset, align);7690block_xfb_offset += 4 * field_type->component_slots();7691}7692}76937694/* Propogate row- / column-major information down the fields of the7695* structure or interface block. Structures need this data because7696* the structure may contain a structure that contains ... a matrix7697* that need the proper layout.7698*/7699if (is_interface && layout &&7700(layout->flags.q.uniform || layout->flags.q.buffer) &&7701(field_type->without_array()->is_matrix()7702|| field_type->without_array()->is_struct())) {7703/* If no layout is specified for the field, inherit the layout7704* from the block.7705*/7706fields[i].matrix_layout = matrix_layout;77077708if (qual->flags.q.row_major)7709fields[i].matrix_layout = GLSL_MATRIX_LAYOUT_ROW_MAJOR;7710else if (qual->flags.q.column_major)7711fields[i].matrix_layout = GLSL_MATRIX_LAYOUT_COLUMN_MAJOR;77127713/* If we're processing an uniform or buffer block, the matrix7714* layout must be decided by this point.7715*/7716assert(fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR7717|| fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_COLUMN_MAJOR);7718}77197720/* Memory qualifiers are allowed on buffer and image variables, while7721* the format qualifier is only accepted for images.7722*/7723if (var_mode == ir_var_shader_storage ||7724field_type->without_array()->is_image()) {7725/* For readonly and writeonly qualifiers the field definition,7726* if set, overwrites the layout qualifier.7727*/7728if (qual->flags.q.read_only || qual->flags.q.write_only) {7729fields[i].memory_read_only = qual->flags.q.read_only;7730fields[i].memory_write_only = qual->flags.q.write_only;7731} else {7732fields[i].memory_read_only =7733layout ? layout->flags.q.read_only : 0;7734fields[i].memory_write_only =7735layout ? layout->flags.q.write_only : 0;7736}77377738/* For other qualifiers, we set the flag if either the layout7739* qualifier or the field qualifier are set7740*/7741fields[i].memory_coherent = qual->flags.q.coherent ||7742(layout && layout->flags.q.coherent);7743fields[i].memory_volatile = qual->flags.q._volatile ||7744(layout && layout->flags.q._volatile);7745fields[i].memory_restrict = qual->flags.q.restrict_flag ||7746(layout && layout->flags.q.restrict_flag);77477748if (field_type->without_array()->is_image()) {7749if (qual->flags.q.explicit_image_format) {7750if (qual->image_base_type !=7751field_type->without_array()->sampled_type) {7752_mesa_glsl_error(&loc, state, "format qualifier doesn't "7753"match the base data type of the image");7754}77557756fields[i].image_format = qual->image_format;7757} else {7758if (!qual->flags.q.write_only) {7759_mesa_glsl_error(&loc, state, "image not qualified with "7760"`writeonly' must have a format layout "7761"qualifier");7762}77637764fields[i].image_format = PIPE_FORMAT_NONE;7765}7766}7767}77687769/* Precision qualifiers do not hold any meaning in Desktop GLSL */7770if (state->es_shader) {7771fields[i].precision = select_gles_precision(qual->precision,7772field_type,7773state,7774&loc);7775} else {7776fields[i].precision = qual->precision;7777}77787779i++;7780}7781}77827783assert(i == decl_count);77847785*fields_ret = fields;7786return decl_count;7787}778877897790ir_rvalue *7791ast_struct_specifier::hir(exec_list *instructions,7792struct _mesa_glsl_parse_state *state)7793{7794YYLTYPE loc = this->get_location();77957796unsigned expl_location = 0;7797if (layout && layout->flags.q.explicit_location) {7798if (!process_qualifier_constant(state, &loc, "location",7799layout->location, &expl_location)) {7800return NULL;7801} else {7802expl_location = VARYING_SLOT_VAR0 + expl_location;7803}7804}78057806glsl_struct_field *fields;7807unsigned decl_count =7808ast_process_struct_or_iface_block_members(instructions,7809state,7810&this->declarations,7811&fields,7812false,7813GLSL_MATRIX_LAYOUT_INHERITED,7814false /* allow_reserved_names */,7815ir_var_auto,7816layout,78170, /* for interface only */78180, /* for interface only */78190, /* for interface only */7820expl_location,78210 /* for interface only */);78227823validate_identifier(this->name, loc, state);78247825type = glsl_type::get_struct_instance(fields, decl_count, this->name);78267827if (!type->is_anonymous() && !state->symbols->add_type(name, type)) {7828const glsl_type *match = state->symbols->get_type(name);7829/* allow struct matching for desktop GL - older UE4 does this */7830if (match != NULL && state->is_version(130, 0) && match->record_compare(type, true, false))7831_mesa_glsl_warning(& loc, state, "struct `%s' previously defined", name);7832else7833_mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);7834} else {7835const glsl_type **s = reralloc(state, state->user_structures,7836const glsl_type *,7837state->num_user_structures + 1);7838if (s != NULL) {7839s[state->num_user_structures] = type;7840state->user_structures = s;7841state->num_user_structures++;7842}7843}78447845/* Structure type definitions do not have r-values.7846*/7847return NULL;7848}784978507851/**7852* Visitor class which detects whether a given interface block has been used.7853*/7854class interface_block_usage_visitor : public ir_hierarchical_visitor7855{7856public:7857interface_block_usage_visitor(ir_variable_mode mode, const glsl_type *block)7858: mode(mode), block(block), found(false)7859{7860}78617862virtual ir_visitor_status visit(ir_dereference_variable *ir)7863{7864if (ir->var->data.mode == mode && ir->var->get_interface_type() == block) {7865found = true;7866return visit_stop;7867}7868return visit_continue;7869}78707871bool usage_found() const7872{7873return this->found;7874}78757876private:7877ir_variable_mode mode;7878const glsl_type *block;7879bool found;7880};78817882static bool7883is_unsized_array_last_element(ir_variable *v)7884{7885const glsl_type *interface_type = v->get_interface_type();7886int length = interface_type->length;78877888assert(v->type->is_unsized_array());78897890/* Check if it is the last element of the interface */7891if (strcmp(interface_type->fields.structure[length-1].name, v->name) == 0)7892return true;7893return false;7894}78957896static void7897apply_memory_qualifiers(ir_variable *var, glsl_struct_field field)7898{7899var->data.memory_read_only = field.memory_read_only;7900var->data.memory_write_only = field.memory_write_only;7901var->data.memory_coherent = field.memory_coherent;7902var->data.memory_volatile = field.memory_volatile;7903var->data.memory_restrict = field.memory_restrict;7904}79057906ir_rvalue *7907ast_interface_block::hir(exec_list *instructions,7908struct _mesa_glsl_parse_state *state)7909{7910YYLTYPE loc = this->get_location();79117912/* Interface blocks must be declared at global scope */7913if (state->current_function != NULL) {7914_mesa_glsl_error(&loc, state,7915"Interface block `%s' must be declared "7916"at global scope",7917this->block_name);7918}79197920/* Validate qualifiers:7921*7922* - Layout Qualifiers as per the table in Section 4.47923* ("Layout Qualifiers") of the GLSL 4.50 spec.7924*7925* - Memory Qualifiers as per Section 4.10 ("Memory Qualifiers") of the7926* GLSL 4.50 spec:7927*7928* "Additionally, memory qualifiers may also be used in the declaration7929* of shader storage blocks"7930*7931* Note the table in Section 4.4 says std430 is allowed on both uniform and7932* buffer blocks however Section 4.4.5 (Uniform and Shader Storage Block7933* Layout Qualifiers) of the GLSL 4.50 spec says:7934*7935* "The std430 qualifier is supported only for shader storage blocks;7936* using std430 on a uniform block will result in a compile-time error."7937*/7938ast_type_qualifier allowed_blk_qualifiers;7939allowed_blk_qualifiers.flags.i = 0;7940if (this->layout.flags.q.buffer || this->layout.flags.q.uniform) {7941allowed_blk_qualifiers.flags.q.shared = 1;7942allowed_blk_qualifiers.flags.q.packed = 1;7943allowed_blk_qualifiers.flags.q.std140 = 1;7944allowed_blk_qualifiers.flags.q.row_major = 1;7945allowed_blk_qualifiers.flags.q.column_major = 1;7946allowed_blk_qualifiers.flags.q.explicit_align = 1;7947allowed_blk_qualifiers.flags.q.explicit_binding = 1;7948if (this->layout.flags.q.buffer) {7949allowed_blk_qualifiers.flags.q.buffer = 1;7950allowed_blk_qualifiers.flags.q.std430 = 1;7951allowed_blk_qualifiers.flags.q.coherent = 1;7952allowed_blk_qualifiers.flags.q._volatile = 1;7953allowed_blk_qualifiers.flags.q.restrict_flag = 1;7954allowed_blk_qualifiers.flags.q.read_only = 1;7955allowed_blk_qualifiers.flags.q.write_only = 1;7956} else {7957allowed_blk_qualifiers.flags.q.uniform = 1;7958}7959} else {7960/* Interface block */7961assert(this->layout.flags.q.in || this->layout.flags.q.out);79627963allowed_blk_qualifiers.flags.q.explicit_location = 1;7964if (this->layout.flags.q.out) {7965allowed_blk_qualifiers.flags.q.out = 1;7966if (state->stage == MESA_SHADER_GEOMETRY ||7967state->stage == MESA_SHADER_TESS_CTRL ||7968state->stage == MESA_SHADER_TESS_EVAL ||7969state->stage == MESA_SHADER_VERTEX ) {7970allowed_blk_qualifiers.flags.q.explicit_xfb_offset = 1;7971allowed_blk_qualifiers.flags.q.explicit_xfb_buffer = 1;7972allowed_blk_qualifiers.flags.q.xfb_buffer = 1;7973allowed_blk_qualifiers.flags.q.explicit_xfb_stride = 1;7974allowed_blk_qualifiers.flags.q.xfb_stride = 1;7975if (state->stage == MESA_SHADER_GEOMETRY) {7976allowed_blk_qualifiers.flags.q.stream = 1;7977allowed_blk_qualifiers.flags.q.explicit_stream = 1;7978}7979if (state->stage == MESA_SHADER_TESS_CTRL) {7980allowed_blk_qualifiers.flags.q.patch = 1;7981}7982}7983} else {7984allowed_blk_qualifiers.flags.q.in = 1;7985if (state->stage == MESA_SHADER_TESS_EVAL) {7986allowed_blk_qualifiers.flags.q.patch = 1;7987}7988}7989}79907991this->layout.validate_flags(&loc, state, allowed_blk_qualifiers,7992"invalid qualifier for block",7993this->block_name);79947995enum glsl_interface_packing packing;7996if (this->layout.flags.q.std140) {7997packing = GLSL_INTERFACE_PACKING_STD140;7998} else if (this->layout.flags.q.packed) {7999packing = GLSL_INTERFACE_PACKING_PACKED;8000} else if (this->layout.flags.q.std430) {8001packing = GLSL_INTERFACE_PACKING_STD430;8002} else {8003/* The default layout is shared.8004*/8005packing = GLSL_INTERFACE_PACKING_SHARED;8006}80078008ir_variable_mode var_mode;8009const char *iface_type_name;8010if (this->layout.flags.q.in) {8011var_mode = ir_var_shader_in;8012iface_type_name = "in";8013} else if (this->layout.flags.q.out) {8014var_mode = ir_var_shader_out;8015iface_type_name = "out";8016} else if (this->layout.flags.q.uniform) {8017var_mode = ir_var_uniform;8018iface_type_name = "uniform";8019} else if (this->layout.flags.q.buffer) {8020var_mode = ir_var_shader_storage;8021iface_type_name = "buffer";8022} else {8023var_mode = ir_var_auto;8024iface_type_name = "UNKNOWN";8025assert(!"interface block layout qualifier not found!");8026}80278028enum glsl_matrix_layout matrix_layout = GLSL_MATRIX_LAYOUT_INHERITED;8029if (this->layout.flags.q.row_major)8030matrix_layout = GLSL_MATRIX_LAYOUT_ROW_MAJOR;8031else if (this->layout.flags.q.column_major)8032matrix_layout = GLSL_MATRIX_LAYOUT_COLUMN_MAJOR;80338034bool redeclaring_per_vertex = strcmp(this->block_name, "gl_PerVertex") == 0;8035exec_list declared_variables;8036glsl_struct_field *fields;80378038/* For blocks that accept memory qualifiers (i.e. shader storage), verify8039* that we don't have incompatible qualifiers8040*/8041if (this->layout.flags.q.read_only && this->layout.flags.q.write_only) {8042_mesa_glsl_error(&loc, state,8043"Interface block sets both readonly and writeonly");8044}80458046unsigned qual_stream;8047if (!process_qualifier_constant(state, &loc, "stream", this->layout.stream,8048&qual_stream) ||8049!validate_stream_qualifier(&loc, state, qual_stream)) {8050/* If the stream qualifier is invalid it doesn't make sense to continue8051* on and try to compare stream layouts on member variables against it8052* so just return early.8053*/8054return NULL;8055}80568057unsigned qual_xfb_buffer;8058if (!process_qualifier_constant(state, &loc, "xfb_buffer",8059layout.xfb_buffer, &qual_xfb_buffer) ||8060!validate_xfb_buffer_qualifier(&loc, state, qual_xfb_buffer)) {8061return NULL;8062}80638064unsigned qual_xfb_offset = 0;8065if (layout.flags.q.explicit_xfb_offset) {8066if (!process_qualifier_constant(state, &loc, "xfb_offset",8067layout.offset, &qual_xfb_offset)) {8068return NULL;8069}8070}80718072unsigned qual_xfb_stride = 0;8073if (layout.flags.q.explicit_xfb_stride) {8074if (!process_qualifier_constant(state, &loc, "xfb_stride",8075layout.xfb_stride, &qual_xfb_stride)) {8076return NULL;8077}8078}80798080unsigned expl_location = 0;8081if (layout.flags.q.explicit_location) {8082if (!process_qualifier_constant(state, &loc, "location",8083layout.location, &expl_location)) {8084return NULL;8085} else {8086expl_location += this->layout.flags.q.patch ? VARYING_SLOT_PATCH08087: VARYING_SLOT_VAR0;8088}8089}80908091unsigned expl_align = 0;8092if (layout.flags.q.explicit_align) {8093if (!process_qualifier_constant(state, &loc, "align",8094layout.align, &expl_align)) {8095return NULL;8096} else {8097if (expl_align == 0 || expl_align & (expl_align - 1)) {8098_mesa_glsl_error(&loc, state, "align layout qualifier is not a "8099"power of 2.");8100return NULL;8101}8102}8103}81048105unsigned int num_variables =8106ast_process_struct_or_iface_block_members(&declared_variables,8107state,8108&this->declarations,8109&fields,8110true,8111matrix_layout,8112redeclaring_per_vertex,8113var_mode,8114&this->layout,8115qual_stream,8116qual_xfb_buffer,8117qual_xfb_offset,8118expl_location,8119expl_align);81208121if (!redeclaring_per_vertex) {8122validate_identifier(this->block_name, loc, state);81238124/* From section 4.3.9 ("Interface Blocks") of the GLSL 4.50 spec:8125*8126* "Block names have no other use within a shader beyond interface8127* matching; it is a compile-time error to use a block name at global8128* scope for anything other than as a block name."8129*/8130ir_variable *var = state->symbols->get_variable(this->block_name);8131if (var && !var->type->is_interface()) {8132_mesa_glsl_error(&loc, state, "Block name `%s' is "8133"already used in the scope.",8134this->block_name);8135}8136}81378138const glsl_type *earlier_per_vertex = NULL;8139if (redeclaring_per_vertex) {8140/* Find the previous declaration of gl_PerVertex. If we're redeclaring8141* the named interface block gl_in, we can find it by looking at the8142* previous declaration of gl_in. Otherwise we can find it by looking8143* at the previous decalartion of any of the built-in outputs,8144* e.g. gl_Position.8145*8146* Also check that the instance name and array-ness of the redeclaration8147* are correct.8148*/8149switch (var_mode) {8150case ir_var_shader_in:8151if (ir_variable *earlier_gl_in =8152state->symbols->get_variable("gl_in")) {8153earlier_per_vertex = earlier_gl_in->get_interface_type();8154} else {8155_mesa_glsl_error(&loc, state,8156"redeclaration of gl_PerVertex input not allowed "8157"in the %s shader",8158_mesa_shader_stage_to_string(state->stage));8159}8160if (this->instance_name == NULL ||8161strcmp(this->instance_name, "gl_in") != 0 || this->array_specifier == NULL ||8162!this->array_specifier->is_single_dimension()) {8163_mesa_glsl_error(&loc, state,8164"gl_PerVertex input must be redeclared as "8165"gl_in[]");8166}8167break;8168case ir_var_shader_out:8169if (ir_variable *earlier_gl_Position =8170state->symbols->get_variable("gl_Position")) {8171earlier_per_vertex = earlier_gl_Position->get_interface_type();8172} else if (ir_variable *earlier_gl_out =8173state->symbols->get_variable("gl_out")) {8174earlier_per_vertex = earlier_gl_out->get_interface_type();8175} else {8176_mesa_glsl_error(&loc, state,8177"redeclaration of gl_PerVertex output not "8178"allowed in the %s shader",8179_mesa_shader_stage_to_string(state->stage));8180}8181if (state->stage == MESA_SHADER_TESS_CTRL) {8182if (this->instance_name == NULL ||8183strcmp(this->instance_name, "gl_out") != 0 || this->array_specifier == NULL) {8184_mesa_glsl_error(&loc, state,8185"gl_PerVertex output must be redeclared as "8186"gl_out[]");8187}8188} else {8189if (this->instance_name != NULL) {8190_mesa_glsl_error(&loc, state,8191"gl_PerVertex output may not be redeclared with "8192"an instance name");8193}8194}8195break;8196default:8197_mesa_glsl_error(&loc, state,8198"gl_PerVertex must be declared as an input or an "8199"output");8200break;8201}82028203if (earlier_per_vertex == NULL) {8204/* An error has already been reported. Bail out to avoid null8205* dereferences later in this function.8206*/8207return NULL;8208}82098210/* Copy locations from the old gl_PerVertex interface block. */8211for (unsigned i = 0; i < num_variables; i++) {8212int j = earlier_per_vertex->field_index(fields[i].name);8213if (j == -1) {8214_mesa_glsl_error(&loc, state,8215"redeclaration of gl_PerVertex must be a subset "8216"of the built-in members of gl_PerVertex");8217} else {8218fields[i].location =8219earlier_per_vertex->fields.structure[j].location;8220fields[i].offset =8221earlier_per_vertex->fields.structure[j].offset;8222fields[i].interpolation =8223earlier_per_vertex->fields.structure[j].interpolation;8224fields[i].centroid =8225earlier_per_vertex->fields.structure[j].centroid;8226fields[i].sample =8227earlier_per_vertex->fields.structure[j].sample;8228fields[i].patch =8229earlier_per_vertex->fields.structure[j].patch;8230fields[i].precision =8231earlier_per_vertex->fields.structure[j].precision;8232fields[i].explicit_xfb_buffer =8233earlier_per_vertex->fields.structure[j].explicit_xfb_buffer;8234fields[i].xfb_buffer =8235earlier_per_vertex->fields.structure[j].xfb_buffer;8236fields[i].xfb_stride =8237earlier_per_vertex->fields.structure[j].xfb_stride;8238}8239}82408241/* From section 7.1 ("Built-in Language Variables") of the GLSL 4.108242* spec:8243*8244* If a built-in interface block is redeclared, it must appear in8245* the shader before any use of any member included in the built-in8246* declaration, or a compilation error will result.8247*8248* This appears to be a clarification to the behaviour established for8249* gl_PerVertex by GLSL 1.50, therefore we implement this behaviour8250* regardless of GLSL version.8251*/8252interface_block_usage_visitor v(var_mode, earlier_per_vertex);8253v.run(instructions);8254if (v.usage_found()) {8255_mesa_glsl_error(&loc, state,8256"redeclaration of a built-in interface block must "8257"appear before any use of any member of the "8258"interface block");8259}8260}82618262const glsl_type *block_type =8263glsl_type::get_interface_instance(fields,8264num_variables,8265packing,8266matrix_layout ==8267GLSL_MATRIX_LAYOUT_ROW_MAJOR,8268this->block_name);82698270unsigned component_size = block_type->contains_double() ? 8 : 4;8271int xfb_offset =8272layout.flags.q.explicit_xfb_offset ? (int) qual_xfb_offset : -1;8273validate_xfb_offset_qualifier(&loc, state, xfb_offset, block_type,8274component_size);82758276if (!state->symbols->add_interface(block_type->name, block_type, var_mode)) {8277YYLTYPE loc = this->get_location();8278_mesa_glsl_error(&loc, state, "interface block `%s' with type `%s' "8279"already taken in the current scope",8280this->block_name, iface_type_name);8281}82828283/* Since interface blocks cannot contain statements, it should be8284* impossible for the block to generate any instructions.8285*/8286assert(declared_variables.is_empty());82878288/* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:8289*8290* Geometry shader input variables get the per-vertex values written8291* out by vertex shader output variables of the same names. Since a8292* geometry shader operates on a set of vertices, each input varying8293* variable (or input block, see interface blocks below) needs to be8294* declared as an array.8295*/8296if (state->stage == MESA_SHADER_GEOMETRY && this->array_specifier == NULL &&8297var_mode == ir_var_shader_in) {8298_mesa_glsl_error(&loc, state, "geometry shader inputs must be arrays");8299} else if ((state->stage == MESA_SHADER_TESS_CTRL ||8300state->stage == MESA_SHADER_TESS_EVAL) &&8301!this->layout.flags.q.patch &&8302this->array_specifier == NULL &&8303var_mode == ir_var_shader_in) {8304_mesa_glsl_error(&loc, state, "per-vertex tessellation shader inputs must be arrays");8305} else if (state->stage == MESA_SHADER_TESS_CTRL &&8306!this->layout.flags.q.patch &&8307this->array_specifier == NULL &&8308var_mode == ir_var_shader_out) {8309_mesa_glsl_error(&loc, state, "tessellation control shader outputs must be arrays");8310}831183128313/* Page 39 (page 45 of the PDF) of section 4.3.7 in the GLSL ES 3.00 spec8314* says:8315*8316* "If an instance name (instance-name) is used, then it puts all the8317* members inside a scope within its own name space, accessed with the8318* field selector ( . ) operator (analogously to structures)."8319*/8320if (this->instance_name) {8321if (redeclaring_per_vertex) {8322/* When a built-in in an unnamed interface block is redeclared,8323* get_variable_being_redeclared() calls8324* check_builtin_array_max_size() to make sure that built-in array8325* variables aren't redeclared to illegal sizes. But we're looking8326* at a redeclaration of a named built-in interface block. So we8327* have to manually call check_builtin_array_max_size() for all parts8328* of the interface that are arrays.8329*/8330for (unsigned i = 0; i < num_variables; i++) {8331if (fields[i].type->is_array()) {8332const unsigned size = fields[i].type->array_size();8333check_builtin_array_max_size(fields[i].name, size, loc, state);8334}8335}8336} else {8337validate_identifier(this->instance_name, loc, state);8338}83398340ir_variable *var;83418342if (this->array_specifier != NULL) {8343const glsl_type *block_array_type =8344process_array_type(&loc, block_type, this->array_specifier, state);83458346/* Section 4.3.7 (Interface Blocks) of the GLSL 1.50 spec says:8347*8348* For uniform blocks declared an array, each individual array8349* element corresponds to a separate buffer object backing one8350* instance of the block. As the array size indicates the number8351* of buffer objects needed, uniform block array declarations8352* must specify an array size.8353*8354* And a few paragraphs later:8355*8356* Geometry shader input blocks must be declared as arrays and8357* follow the array declaration and linking rules for all8358* geometry shader inputs. All other input and output block8359* arrays must specify an array size.8360*8361* The same applies to tessellation shaders.8362*8363* The upshot of this is that the only circumstance where an8364* interface array size *doesn't* need to be specified is on a8365* geometry shader input, tessellation control shader input,8366* tessellation control shader output, and tessellation evaluation8367* shader input.8368*/8369if (block_array_type->is_unsized_array()) {8370bool allow_inputs = state->stage == MESA_SHADER_GEOMETRY ||8371state->stage == MESA_SHADER_TESS_CTRL ||8372state->stage == MESA_SHADER_TESS_EVAL;8373bool allow_outputs = state->stage == MESA_SHADER_TESS_CTRL;83748375if (this->layout.flags.q.in) {8376if (!allow_inputs)8377_mesa_glsl_error(&loc, state,8378"unsized input block arrays not allowed in "8379"%s shader",8380_mesa_shader_stage_to_string(state->stage));8381} else if (this->layout.flags.q.out) {8382if (!allow_outputs)8383_mesa_glsl_error(&loc, state,8384"unsized output block arrays not allowed in "8385"%s shader",8386_mesa_shader_stage_to_string(state->stage));8387} else {8388/* by elimination, this is a uniform block array */8389_mesa_glsl_error(&loc, state,8390"unsized uniform block arrays not allowed in "8391"%s shader",8392_mesa_shader_stage_to_string(state->stage));8393}8394}83958396/* From section 4.3.9 (Interface Blocks) of the GLSL ES 3.10 spec:8397*8398* * Arrays of arrays of blocks are not allowed8399*/8400if (state->es_shader && block_array_type->is_array() &&8401block_array_type->fields.array->is_array()) {8402_mesa_glsl_error(&loc, state,8403"arrays of arrays interface blocks are "8404"not allowed");8405}84068407var = new(state) ir_variable(block_array_type,8408this->instance_name,8409var_mode);8410} else {8411var = new(state) ir_variable(block_type,8412this->instance_name,8413var_mode);8414}84158416var->data.matrix_layout = matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED8417? GLSL_MATRIX_LAYOUT_COLUMN_MAJOR : matrix_layout;84188419if (var_mode == ir_var_shader_in || var_mode == ir_var_uniform)8420var->data.read_only = true;84218422var->data.patch = this->layout.flags.q.patch;84238424if (state->stage == MESA_SHADER_GEOMETRY && var_mode == ir_var_shader_in)8425handle_geometry_shader_input_decl(state, loc, var);8426else if ((state->stage == MESA_SHADER_TESS_CTRL ||8427state->stage == MESA_SHADER_TESS_EVAL) && var_mode == ir_var_shader_in)8428handle_tess_shader_input_decl(state, loc, var);8429else if (state->stage == MESA_SHADER_TESS_CTRL && var_mode == ir_var_shader_out)8430handle_tess_ctrl_shader_output_decl(state, loc, var);84318432for (unsigned i = 0; i < num_variables; i++) {8433if (var->data.mode == ir_var_shader_storage)8434apply_memory_qualifiers(var, fields[i]);8435}84368437if (ir_variable *earlier =8438state->symbols->get_variable(this->instance_name)) {8439if (!redeclaring_per_vertex) {8440_mesa_glsl_error(&loc, state, "`%s' redeclared",8441this->instance_name);8442}8443earlier->data.how_declared = ir_var_declared_normally;8444earlier->type = var->type;8445earlier->reinit_interface_type(block_type);8446delete var;8447} else {8448if (this->layout.flags.q.explicit_binding) {8449apply_explicit_binding(state, &loc, var, var->type,8450&this->layout);8451}84528453var->data.stream = qual_stream;8454if (layout.flags.q.explicit_location) {8455var->data.location = expl_location;8456var->data.explicit_location = true;8457}84588459state->symbols->add_variable(var);8460instructions->push_tail(var);8461}8462} else {8463/* In order to have an array size, the block must also be declared with8464* an instance name.8465*/8466assert(this->array_specifier == NULL);84678468for (unsigned i = 0; i < num_variables; i++) {8469ir_variable *var =8470new(state) ir_variable(fields[i].type,8471ralloc_strdup(state, fields[i].name),8472var_mode);8473var->data.interpolation = fields[i].interpolation;8474var->data.centroid = fields[i].centroid;8475var->data.sample = fields[i].sample;8476var->data.patch = fields[i].patch;8477var->data.stream = qual_stream;8478var->data.location = fields[i].location;84798480if (fields[i].location != -1)8481var->data.explicit_location = true;84828483var->data.explicit_xfb_buffer = fields[i].explicit_xfb_buffer;8484var->data.xfb_buffer = fields[i].xfb_buffer;84858486if (fields[i].offset != -1)8487var->data.explicit_xfb_offset = true;8488var->data.offset = fields[i].offset;84898490var->init_interface_type(block_type);84918492if (var_mode == ir_var_shader_in || var_mode == ir_var_uniform)8493var->data.read_only = true;84948495/* Precision qualifiers do not have any meaning in Desktop GLSL */8496if (state->es_shader) {8497var->data.precision =8498select_gles_precision(fields[i].precision, fields[i].type,8499state, &loc);8500}85018502if (fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED) {8503var->data.matrix_layout = matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED8504? GLSL_MATRIX_LAYOUT_COLUMN_MAJOR : matrix_layout;8505} else {8506var->data.matrix_layout = fields[i].matrix_layout;8507}85088509if (var->data.mode == ir_var_shader_storage)8510apply_memory_qualifiers(var, fields[i]);85118512/* Examine var name here since var may get deleted in the next call */8513bool var_is_gl_id = is_gl_identifier(var->name);85148515if (redeclaring_per_vertex) {8516bool is_redeclaration;8517var =8518get_variable_being_redeclared(&var, loc, state,8519true /* allow_all_redeclarations */,8520&is_redeclaration);8521if (!var_is_gl_id || !is_redeclaration) {8522_mesa_glsl_error(&loc, state,8523"redeclaration of gl_PerVertex can only "8524"include built-in variables");8525} else if (var->data.how_declared == ir_var_declared_normally) {8526_mesa_glsl_error(&loc, state,8527"`%s' has already been redeclared",8528var->name);8529} else {8530var->data.how_declared = ir_var_declared_in_block;8531var->reinit_interface_type(block_type);8532}8533continue;8534}85358536if (state->symbols->get_variable(var->name) != NULL)8537_mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);85388539/* Propagate the "binding" keyword into this UBO/SSBO's fields.8540* The UBO declaration itself doesn't get an ir_variable unless it8541* has an instance name. This is ugly.8542*/8543if (this->layout.flags.q.explicit_binding) {8544apply_explicit_binding(state, &loc, var,8545var->get_interface_type(), &this->layout);8546}85478548if (var->type->is_unsized_array()) {8549if (var->is_in_shader_storage_block() &&8550is_unsized_array_last_element(var)) {8551var->data.from_ssbo_unsized_array = true;8552} else {8553/* From GLSL ES 3.10 spec, section 4.1.9 "Arrays":8554*8555* "If an array is declared as the last member of a shader storage8556* block and the size is not specified at compile-time, it is8557* sized at run-time. In all other cases, arrays are sized only8558* at compile-time."8559*8560* In desktop GLSL it is allowed to have unsized-arrays that are8561* not last, as long as we can determine that they are implicitly8562* sized.8563*/8564if (state->es_shader) {8565_mesa_glsl_error(&loc, state, "unsized array `%s' "8566"definition: only last member of a shader "8567"storage block can be defined as unsized "8568"array", fields[i].name);8569}8570}8571}85728573state->symbols->add_variable(var);8574instructions->push_tail(var);8575}85768577if (redeclaring_per_vertex && block_type != earlier_per_vertex) {8578/* From section 7.1 ("Built-in Language Variables") of the GLSL 4.10 spec:8579*8580* It is also a compilation error ... to redeclare a built-in8581* block and then use a member from that built-in block that was8582* not included in the redeclaration.8583*8584* This appears to be a clarification to the behaviour established8585* for gl_PerVertex by GLSL 1.50, therefore we implement this8586* behaviour regardless of GLSL version.8587*8588* To prevent the shader from using a member that was not included in8589* the redeclaration, we disable any ir_variables that are still8590* associated with the old declaration of gl_PerVertex (since we've8591* already updated all of the variables contained in the new8592* gl_PerVertex to point to it).8593*8594* As a side effect this will prevent8595* validate_intrastage_interface_blocks() from getting confused and8596* thinking there are conflicting definitions of gl_PerVertex in the8597* shader.8598*/8599foreach_in_list_safe(ir_instruction, node, instructions) {8600ir_variable *const var = node->as_variable();8601if (var != NULL &&8602var->get_interface_type() == earlier_per_vertex &&8603var->data.mode == var_mode) {8604if (var->data.how_declared == ir_var_declared_normally) {8605_mesa_glsl_error(&loc, state,8606"redeclaration of gl_PerVertex cannot "8607"follow a redeclaration of `%s'",8608var->name);8609}8610state->symbols->disable_variable(var->name);8611var->remove();8612}8613}8614}8615}86168617return NULL;8618}861986208621ir_rvalue *8622ast_tcs_output_layout::hir(exec_list *instructions,8623struct _mesa_glsl_parse_state *state)8624{8625YYLTYPE loc = this->get_location();86268627unsigned num_vertices;8628if (!state->out_qualifier->vertices->8629process_qualifier_constant(state, "vertices", &num_vertices,8630false)) {8631/* return here to stop cascading incorrect error messages */8632return NULL;8633}86348635/* If any shader outputs occurred before this declaration and specified an8636* array size, make sure the size they specified is consistent with the8637* primitive type.8638*/8639if (state->tcs_output_size != 0 && state->tcs_output_size != num_vertices) {8640_mesa_glsl_error(&loc, state,8641"this tessellation control shader output layout "8642"specifies %u vertices, but a previous output "8643"is declared with size %u",8644num_vertices, state->tcs_output_size);8645return NULL;8646}86478648state->tcs_output_vertices_specified = true;86498650/* If any shader outputs occurred before this declaration and did not8651* specify an array size, their size is determined now.8652*/8653foreach_in_list (ir_instruction, node, instructions) {8654ir_variable *var = node->as_variable();8655if (var == NULL || var->data.mode != ir_var_shader_out)8656continue;86578658/* Note: Not all tessellation control shader output are arrays. */8659if (!var->type->is_unsized_array() || var->data.patch)8660continue;86618662if (var->data.max_array_access >= (int)num_vertices) {8663_mesa_glsl_error(&loc, state,8664"this tessellation control shader output layout "8665"specifies %u vertices, but an access to element "8666"%u of output `%s' already exists", num_vertices,8667var->data.max_array_access, var->name);8668} else {8669var->type = glsl_type::get_array_instance(var->type->fields.array,8670num_vertices);8671}8672}86738674return NULL;8675}867686778678ir_rvalue *8679ast_gs_input_layout::hir(exec_list *instructions,8680struct _mesa_glsl_parse_state *state)8681{8682YYLTYPE loc = this->get_location();86838684/* Should have been prevented by the parser. */8685assert(!state->gs_input_prim_type_specified8686|| state->in_qualifier->prim_type == this->prim_type);86878688/* If any shader inputs occurred before this declaration and specified an8689* array size, make sure the size they specified is consistent with the8690* primitive type.8691*/8692unsigned num_vertices = vertices_per_prim(this->prim_type);8693if (state->gs_input_size != 0 && state->gs_input_size != num_vertices) {8694_mesa_glsl_error(&loc, state,8695"this geometry shader input layout implies %u vertices"8696" per primitive, but a previous input is declared"8697" with size %u", num_vertices, state->gs_input_size);8698return NULL;8699}87008701state->gs_input_prim_type_specified = true;87028703/* If any shader inputs occurred before this declaration and did not8704* specify an array size, their size is determined now.8705*/8706foreach_in_list(ir_instruction, node, instructions) {8707ir_variable *var = node->as_variable();8708if (var == NULL || var->data.mode != ir_var_shader_in)8709continue;87108711/* Note: gl_PrimitiveIDIn has mode ir_var_shader_in, but it's not an8712* array; skip it.8713*/87148715if (var->type->is_unsized_array()) {8716if (var->data.max_array_access >= (int)num_vertices) {8717_mesa_glsl_error(&loc, state,8718"this geometry shader input layout implies %u"8719" vertices, but an access to element %u of input"8720" `%s' already exists", num_vertices,8721var->data.max_array_access, var->name);8722} else {8723var->type = glsl_type::get_array_instance(var->type->fields.array,8724num_vertices);8725}8726}8727}87288729return NULL;8730}873187328733ir_rvalue *8734ast_cs_input_layout::hir(exec_list *instructions,8735struct _mesa_glsl_parse_state *state)8736{8737YYLTYPE loc = this->get_location();87388739/* From the ARB_compute_shader specification:8740*8741* If the local size of the shader in any dimension is greater8742* than the maximum size supported by the implementation for that8743* dimension, a compile-time error results.8744*8745* It is not clear from the spec how the error should be reported if8746* the total size of the work group exceeds8747* MAX_COMPUTE_WORK_GROUP_INVOCATIONS, but it seems reasonable to8748* report it at compile time as well.8749*/8750GLuint64 total_invocations = 1;8751unsigned qual_local_size[3];8752for (int i = 0; i < 3; i++) {87538754char *local_size_str = ralloc_asprintf(NULL, "invalid local_size_%c",8755'x' + i);8756/* Infer a local_size of 1 for unspecified dimensions */8757if (this->local_size[i] == NULL) {8758qual_local_size[i] = 1;8759} else if (!this->local_size[i]->8760process_qualifier_constant(state, local_size_str,8761&qual_local_size[i], false)) {8762ralloc_free(local_size_str);8763return NULL;8764}8765ralloc_free(local_size_str);87668767if (qual_local_size[i] > state->ctx->Const.MaxComputeWorkGroupSize[i]) {8768_mesa_glsl_error(&loc, state,8769"local_size_%c exceeds MAX_COMPUTE_WORK_GROUP_SIZE"8770" (%d)", 'x' + i,8771state->ctx->Const.MaxComputeWorkGroupSize[i]);8772break;8773}8774total_invocations *= qual_local_size[i];8775if (total_invocations >8776state->ctx->Const.MaxComputeWorkGroupInvocations) {8777_mesa_glsl_error(&loc, state,8778"product of local_sizes exceeds "8779"MAX_COMPUTE_WORK_GROUP_INVOCATIONS (%d)",8780state->ctx->Const.MaxComputeWorkGroupInvocations);8781break;8782}8783}87848785/* If any compute input layout declaration preceded this one, make sure it8786* was consistent with this one.8787*/8788if (state->cs_input_local_size_specified) {8789for (int i = 0; i < 3; i++) {8790if (state->cs_input_local_size[i] != qual_local_size[i]) {8791_mesa_glsl_error(&loc, state,8792"compute shader input layout does not match"8793" previous declaration");8794return NULL;8795}8796}8797}87988799/* The ARB_compute_variable_group_size spec says:8800*8801* If a compute shader including a *local_size_variable* qualifier also8802* declares a fixed local group size using the *local_size_x*,8803* *local_size_y*, or *local_size_z* qualifiers, a compile-time error8804* results8805*/8806if (state->cs_input_local_size_variable_specified) {8807_mesa_glsl_error(&loc, state,8808"compute shader can't include both a variable and a "8809"fixed local group size");8810return NULL;8811}88128813state->cs_input_local_size_specified = true;8814for (int i = 0; i < 3; i++)8815state->cs_input_local_size[i] = qual_local_size[i];88168817/* We may now declare the built-in constant gl_WorkGroupSize (see8818* builtin_variable_generator::generate_constants() for why we didn't8819* declare it earlier).8820*/8821ir_variable *var = new(state->symbols)8822ir_variable(glsl_type::uvec3_type, "gl_WorkGroupSize", ir_var_auto);8823var->data.how_declared = ir_var_declared_implicitly;8824var->data.read_only = true;8825instructions->push_tail(var);8826state->symbols->add_variable(var);8827ir_constant_data data;8828memset(&data, 0, sizeof(data));8829for (int i = 0; i < 3; i++)8830data.u[i] = qual_local_size[i];8831var->constant_value = new(var) ir_constant(glsl_type::uvec3_type, &data);8832var->constant_initializer =8833new(var) ir_constant(glsl_type::uvec3_type, &data);8834var->data.has_initializer = true;8835var->data.is_implicit_initializer = false;88368837return NULL;8838}883988408841static void8842detect_conflicting_assignments(struct _mesa_glsl_parse_state *state,8843exec_list *instructions)8844{8845bool gl_FragColor_assigned = false;8846bool gl_FragData_assigned = false;8847bool gl_FragSecondaryColor_assigned = false;8848bool gl_FragSecondaryData_assigned = false;8849bool user_defined_fs_output_assigned = false;8850ir_variable *user_defined_fs_output = NULL;88518852/* It would be nice to have proper location information. */8853YYLTYPE loc;8854memset(&loc, 0, sizeof(loc));88558856foreach_in_list(ir_instruction, node, instructions) {8857ir_variable *var = node->as_variable();88588859if (!var || !var->data.assigned)8860continue;88618862if (strcmp(var->name, "gl_FragColor") == 0) {8863gl_FragColor_assigned = true;8864if (!var->constant_initializer && state->zero_init) {8865const ir_constant_data data = { { 0 } };8866var->data.has_initializer = true;8867var->data.is_implicit_initializer = true;8868var->constant_initializer = new(var) ir_constant(var->type, &data);8869}8870}8871else if (strcmp(var->name, "gl_FragData") == 0)8872gl_FragData_assigned = true;8873else if (strcmp(var->name, "gl_SecondaryFragColorEXT") == 0)8874gl_FragSecondaryColor_assigned = true;8875else if (strcmp(var->name, "gl_SecondaryFragDataEXT") == 0)8876gl_FragSecondaryData_assigned = true;8877else if (!is_gl_identifier(var->name)) {8878if (state->stage == MESA_SHADER_FRAGMENT &&8879var->data.mode == ir_var_shader_out) {8880user_defined_fs_output_assigned = true;8881user_defined_fs_output = var;8882}8883}8884}88858886/* From the GLSL 1.30 spec:8887*8888* "If a shader statically assigns a value to gl_FragColor, it8889* may not assign a value to any element of gl_FragData. If a8890* shader statically writes a value to any element of8891* gl_FragData, it may not assign a value to8892* gl_FragColor. That is, a shader may assign values to either8893* gl_FragColor or gl_FragData, but not both. Multiple shaders8894* linked together must also consistently write just one of8895* these variables. Similarly, if user declared output8896* variables are in use (statically assigned to), then the8897* built-in variables gl_FragColor and gl_FragData may not be8898* assigned to. These incorrect usages all generate compile8899* time errors."8900*/8901if (gl_FragColor_assigned && gl_FragData_assigned) {8902_mesa_glsl_error(&loc, state, "fragment shader writes to both "8903"`gl_FragColor' and `gl_FragData'");8904} else if (gl_FragColor_assigned && user_defined_fs_output_assigned) {8905_mesa_glsl_error(&loc, state, "fragment shader writes to both "8906"`gl_FragColor' and `%s'",8907user_defined_fs_output->name);8908} else if (gl_FragSecondaryColor_assigned && gl_FragSecondaryData_assigned) {8909_mesa_glsl_error(&loc, state, "fragment shader writes to both "8910"`gl_FragSecondaryColorEXT' and"8911" `gl_FragSecondaryDataEXT'");8912} else if (gl_FragColor_assigned && gl_FragSecondaryData_assigned) {8913_mesa_glsl_error(&loc, state, "fragment shader writes to both "8914"`gl_FragColor' and"8915" `gl_FragSecondaryDataEXT'");8916} else if (gl_FragData_assigned && gl_FragSecondaryColor_assigned) {8917_mesa_glsl_error(&loc, state, "fragment shader writes to both "8918"`gl_FragData' and"8919" `gl_FragSecondaryColorEXT'");8920} else if (gl_FragData_assigned && user_defined_fs_output_assigned) {8921_mesa_glsl_error(&loc, state, "fragment shader writes to both "8922"`gl_FragData' and `%s'",8923user_defined_fs_output->name);8924}89258926if ((gl_FragSecondaryColor_assigned || gl_FragSecondaryData_assigned) &&8927!state->EXT_blend_func_extended_enable) {8928_mesa_glsl_error(&loc, state,8929"Dual source blending requires EXT_blend_func_extended");8930}8931}89328933static void8934verify_subroutine_associated_funcs(struct _mesa_glsl_parse_state *state)8935{8936YYLTYPE loc;8937memset(&loc, 0, sizeof(loc));89388939/* Section 6.1.2 (Subroutines) of the GLSL 4.00 spec says:8940*8941* "A program will fail to compile or link if any shader8942* or stage contains two or more functions with the same8943* name if the name is associated with a subroutine type."8944*/89458946for (int i = 0; i < state->num_subroutines; i++) {8947unsigned definitions = 0;8948ir_function *fn = state->subroutines[i];8949/* Calculate number of function definitions with the same name */8950foreach_in_list(ir_function_signature, sig, &fn->signatures) {8951if (sig->is_defined) {8952if (++definitions > 1) {8953_mesa_glsl_error(&loc, state,8954"%s shader contains two or more function "8955"definitions with name `%s', which is "8956"associated with a subroutine type.\n",8957_mesa_shader_stage_to_string(state->stage),8958fn->name);8959return;8960}8961}8962}8963}8964}89658966static void8967remove_per_vertex_blocks(exec_list *instructions,8968_mesa_glsl_parse_state *state, ir_variable_mode mode)8969{8970/* Find the gl_PerVertex interface block of the appropriate (in/out) mode,8971* if it exists in this shader type.8972*/8973const glsl_type *per_vertex = NULL;8974switch (mode) {8975case ir_var_shader_in:8976if (ir_variable *gl_in = state->symbols->get_variable("gl_in"))8977per_vertex = gl_in->get_interface_type();8978break;8979case ir_var_shader_out:8980if (ir_variable *gl_Position =8981state->symbols->get_variable("gl_Position")) {8982per_vertex = gl_Position->get_interface_type();8983}8984break;8985default:8986assert(!"Unexpected mode");8987break;8988}89898990/* If we didn't find a built-in gl_PerVertex interface block, then we don't8991* need to do anything.8992*/8993if (per_vertex == NULL)8994return;89958996/* If the interface block is used by the shader, then we don't need to do8997* anything.8998*/8999interface_block_usage_visitor v(mode, per_vertex);9000v.run(instructions);9001if (v.usage_found())9002return;90039004/* Remove any ir_variable declarations that refer to the interface block9005* we're removing.9006*/9007foreach_in_list_safe(ir_instruction, node, instructions) {9008ir_variable *const var = node->as_variable();9009if (var != NULL && var->get_interface_type() == per_vertex &&9010var->data.mode == mode) {9011state->symbols->disable_variable(var->name);9012var->remove();9013}9014}9015}90169017ir_rvalue *9018ast_warnings_toggle::hir(exec_list *,9019struct _mesa_glsl_parse_state *state)9020{9021state->warnings_enabled = enable;9022return NULL;9023}902490259026