mesa/src/compiler/glsl
Timothy Arceri c64ad299e4 glsl: fix validation of ES vertex attribs
From OpenGL ES 3.0 spec, page 56:

    "Binding more than one attribute name to the same location
     is referred to as aliasing, and is not permitted in OpenGL
     ES Shading Language 3.00 vertex shaders. LinkProgram will
     fail when this condition exists. However, aliasing is
     possible in OpenGL ES Shading Language 1.00 vertex shaders.
     This will only work if only one of the aliased attributes
     is active in the executable program, or if no path through
     the shader consumes more than one attribute of a set of
     attributes aliased to the same location. A link error can
     occur if the linker determines that every path through the
     shader consumes multiple aliased attributes, but implemen-
     tations are not required to generate an error in this case."

So here we make sure to allow the optimisations before validation
for earlier ES shader versions.

Reviewed-by: Marek Olšák <marek.olsak@amd.com>

Fixes: 80c001013c ("glsl: do vs attribute validation in NIR linker")
Closes: https://gitlab.freedesktop.org/mesa/mesa/-/issues/9342
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/24205>
2023-07-19 00:43:26 +00:00
..
glcpp glsl: Fix yylloc.source propagation in YYLLOC_DEFAULT 2023-07-05 20:22:27 +00:00
tests glsl: remove glsl ir optimisation loop from linker 2023-07-06 01:21:07 +00:00
ast.h glsl: handle scope correctly when inlining loop expression 2021-09-08 03:56:59 +00:00
ast_array_index.cpp
ast_expr.cpp
ast_function.cpp compiler: Move can_implicitly_convert_to helper to glsl module from glsl_types.h 2023-06-07 00:33:33 +00:00
ast_to_hir.cpp compiler: use align instead glsl_align and remove glsl_align 2023-06-08 06:41:21 +00:00
ast_type.cpp compiler/glsl: fix include for Android build 2021-04-10 20:33:52 +02:00
astc_decoder.glsl mesa: add astc decoder shader template (glsl es version) 2023-02-17 07:57:12 +00:00
bc1.glsl glsl: Modify the #includes in the DXT5 shaders 2023-02-10 01:40:47 +00:00
bc4.glsl glsl: Modify the #includes in the DXT5 shaders 2023-02-10 01:40:47 +00:00
builtin_functions.cpp glsl: Drop frontend lowering of 32-bit frexp. 2023-04-06 02:32:01 +00:00
builtin_functions.h glsl: Retire unused modes for lower_64bit_integer_instructions. 2021-12-20 14:56:35 -08:00
builtin_int64.h glsl: Retire unused modes for lower_64bit_integer_instructions. 2021-12-20 14:56:35 -08:00
builtin_types.cpp glsl: remove some deps on mtypes.h. 2022-01-20 00:20:06 +00:00
builtin_variables.cpp glsl: remove ir_state_slot::swizzle 2023-04-26 05:51:39 +00:00
CrossPlatformSettings_piece_all.glsl glsl: Add compute shaders to encode DXT5/BC3 2023-02-10 01:40:47 +00:00
etc2_rgba_stitch.glsl glsl: Modify the #includes in the DXT5 shaders 2023-02-10 01:40:47 +00:00
float64.glsl treewide: spelling fixes 2023-06-23 12:20:59 +00:00
generate_ir.cpp
gl_nir.h glsl: port lower_blend_equation_advanced() to nir 2023-06-30 04:08:18 +00:00
gl_nir_link_atomics.c mesa: #include "util/glheader.h" instead GL/gl.h in shared code 2022-11-03 16:07:31 +00:00
gl_nir_link_uniform_blocks.c compiler: use align instead glsl_align and remove glsl_align 2023-06-08 06:41:21 +00:00
gl_nir_link_uniform_initializers.c glsl: drop some more context.h/mtypes.h interactions 2022-01-20 00:20:06 +00:00
gl_nir_link_uniforms.c glsl: Remove the extra scope in gl_nir_link_uniforms.c 2023-06-29 11:29:54 +00:00
gl_nir_link_varyings.c glsl: move store_fragdepth_layout() to nir linker 2023-07-06 01:21:07 +00:00
gl_nir_link_varyings.h glsl: call assign_attribute_or_color_locations() in NIR linker 2023-07-06 01:21:06 +00:00
gl_nir_link_xfb.c nir: xfb_buffer_info::stride is in bytes 2022-06-02 14:06:31 +00:00
gl_nir_linker.c glsl: fix validation of ES vertex attribs 2023-07-19 00:43:26 +00:00
gl_nir_linker.h glsl: move lowering linker code out of st 2023-07-06 01:21:06 +00:00
gl_nir_lower_atomics.c nir: Add range_base to atomic_counter and an option to use it 2023-01-17 13:19:04 +00:00
gl_nir_lower_blend_equation_advanced.c treewide: Remove all usage of nir_builder_init with nir_builder_create and nir_builder_at 2023-07-10 19:20:17 +00:00
gl_nir_lower_buffers.c glsl: Switch to use nir_foreach_function_impl from nir_foreach_function 2023-06-29 11:29:54 +00:00
gl_nir_lower_images.c glsl/nir: Produce unified atomics 2023-05-16 22:36:21 +00:00
gl_nir_lower_packed_varyings.c treewide: Use nir_builder_create more 2023-06-27 18:13:02 +00:00
gl_nir_lower_samplers.c
gl_nir_lower_samplers_as_deref.c nir: use nir_intrinsic_get_var 2023-07-10 16:06:40 +02:00
gl_nir_lower_xfb_varying.c glsl: Use nir_builder_at 2023-07-03 15:21:37 +00:00
gl_nir_opt_dead_builtin_varyings.c nir: Use nir_builder_create 2023-06-27 18:13:02 +00:00
glsl_lexer.ll mesa/glsl: Add support for NV_shader_noperspective_interpolation 2022-09-09 07:22:20 +00:00
glsl_parser.yy glsl: fixes -Werror,-Wunused-but-set-variable for clang-15 in glcpp-parse.y and glsl_parser.yy 2022-12-16 19:02:17 +00:00
glsl_parser_extras.cpp glsl: drop the dce of global vars from GLSL IR linker 2023-07-06 01:21:06 +00:00
glsl_parser_extras.h glsl: Fix yylloc.source propagation in YYLLOC_DEFAULT 2023-07-05 20:22:27 +00:00
glsl_symbol_table.cpp
glsl_symbol_table.h
glsl_to_nir.cpp glsl: remove glsl ir optimisation loop from linker 2023-07-06 01:21:07 +00:00
glsl_to_nir.h glsl/nir: don't pass gl_context to the convertor routine. 2022-01-07 06:19:49 +00:00
hir_field_selection.cpp
int64.glsl glsl: Retire unused modes for lower_64bit_integer_instructions. 2021-12-20 14:56:35 -08:00
ir.cpp glsl: remove the always_active_io flag from GLSL IR 2023-07-06 01:21:06 +00:00
ir.h glsl: remove the always_active_io flag from GLSL IR 2023-07-06 01:21:06 +00:00
ir_array_refcount.cpp
ir_array_refcount.h
ir_basic_block.cpp
ir_basic_block.h
ir_builder.cpp glsl: Add ir_assignment constructor that takes just a write mask 2022-02-11 17:25:33 +00:00
ir_builder.h glsl/ir_builder: Eliminate unused conditional assignment builders 2022-02-11 17:25:33 +00:00
ir_builder_print_visitor.cpp glsl: Eliminate ir_assignment::condition 2022-02-11 17:25:33 +00:00
ir_builder_print_visitor.h
ir_clone.cpp glsl: Eliminate ir_assignment::condition 2022-02-11 17:25:33 +00:00
ir_constant_expression.cpp glsl: Eliminate ir_assignment::condition 2022-02-11 17:25:33 +00:00
ir_equals.cpp glsl: ir_texture add clamp field 2022-02-01 10:28:05 +00:00
ir_expression_flattening.cpp
ir_expression_flattening.h
ir_expression_operation.py glsl: Fix codegen for constant ir_binop_{l,r}shift with mixed types 2023-03-17 05:00:22 +00:00
ir_function.cpp compiler: Move can_implicitly_convert_to helper to glsl module from glsl_types.h 2023-06-07 00:33:33 +00:00
ir_function_can_inline.cpp
ir_function_detect_recursion.cpp
ir_function_inlining.h
ir_hierarchical_visitor.cpp
ir_hierarchical_visitor.h
ir_hv_accept.cpp glsl: Eliminate ir_assignment::condition 2022-02-11 17:25:33 +00:00
ir_optimization.h glsl: remove old lower_blend_equation_advanced() code 2023-06-30 04:08:18 +00:00
ir_print_visitor.cpp glsl: Eliminate ir_assignment::condition 2022-02-11 17:25:33 +00:00
ir_print_visitor.h
ir_reader.cpp glsl: Remove the ability to read text IR with conditional assignments 2022-02-11 17:25:33 +00:00
ir_reader.h
ir_rvalue_visitor.cpp glsl: Don't visit rvalues in the condition of an assignment 2022-02-11 17:25:33 +00:00
ir_rvalue_visitor.h
ir_uniform.h util: reinstate ENUM_PACKED 2023-06-21 21:51:59 +00:00
ir_validate.cpp glsl: Drop frontend lowering of 32-bit frexp. 2023-04-06 02:32:01 +00:00
ir_variable_refcount.cpp
ir_variable_refcount.h
ir_visitor.h
link_functions.cpp glsl: move off mtypes.h in lots of places. 2022-01-20 00:20:06 +00:00
link_interface_blocks.cpp mesa/st: fix possible crash related to arb invalid memory access 2023-02-10 04:45:29 +00:00
link_uniform_block_active_visitor.cpp
link_uniform_block_active_visitor.h
link_uniform_blocks.cpp compiler: use align instead glsl_align and remove glsl_align 2023-06-08 06:41:21 +00:00
link_uniforms.cpp compiler: use align instead glsl_align and remove glsl_align 2023-06-08 06:41:21 +00:00
link_varyings.cpp mesa/st: fix possible crash related to arb invalid memory access 2023-02-10 04:45:29 +00:00
link_varyings.h glsl: remove now unused GLSL IR varying linker code 2022-05-16 03:33:18 +00:00
linker.cpp glsl: do vs attribute validation in NIR linker 2023-07-10 12:48:01 +10:00
linker.h glsl: remove now unused GLSL IR varying linker code 2022-05-16 03:33:18 +00:00
linker_util.cpp glsl/mesa: move parse_program_resource_name() to common linker_util code 2022-05-16 03:33:18 +00:00
linker_util.h mesa: #include "util/glheader.h" instead GL/gl.h in shared code 2022-11-03 16:07:31 +00:00
list.h
lower_builtins.cpp
lower_discard.cpp
lower_discard_flow.cpp
lower_distance.cpp glsl: fix gl_CullDistance lowering from float[8] to vec4[2] 2023-03-20 04:19:23 +00:00
lower_instructions.cpp glsl: Drop PIPE_SHADER_CAP_DFRACEXP_DLDEXP_SUPPORTED. 2023-04-06 02:32:01 +00:00
lower_int64.cpp glsl: Retire unused modes for lower_64bit_integer_instructions. 2021-12-20 14:56:35 -08:00
lower_jumps.cpp treewide: spelling fixes 2023-06-23 12:20:59 +00:00
lower_mat_op_to_vec.cpp glsl: Fix mixed tabs and spaces in lower_mat_op_to_vec.cpp 2022-05-16 16:06:01 +00:00
lower_named_interface_blocks.cpp glsl: move off mtypes.h in lots of places. 2022-01-20 00:20:06 +00:00
lower_packing_builtins.cpp glsl: move rule inside lower_packing_builtins() 2022-10-19 03:52:20 +00:00
lower_precision.cpp glsl/lower_precision: Add actual spec quotes for "check_parameters" 2023-03-21 00:51:24 +00:00
lower_subroutine.cpp
lower_vec_index_to_cond_assign.cpp glsl: Delete lower_extracts code 2022-05-16 16:06:01 +00:00
lower_vector_derefs.cpp glsl/lower_vector_derefs: Don't emit conditional assignments 2022-02-11 17:25:33 +00:00
main.cpp
meson.build glsl: remove old lower_blend_equation_advanced() code 2023-06-30 04:08:18 +00:00
opt_add_neg_to_sub.h
opt_algebraic.cpp glsl/opt_algebraic: Drop the flrp recognizer. 2023-02-28 03:36:09 +00:00
opt_dead_builtin_variables.cpp
opt_dead_code.cpp glsl: remove the always_active_io flag from GLSL IR 2023-07-06 01:21:06 +00:00
opt_dead_code_local.cpp Re-indentation after the previous commit 2022-02-11 17:25:34 +00:00
opt_dead_functions.cpp
opt_flatten_nested_if_blocks.cpp
opt_flip_matrices.cpp
opt_function_inlining.cpp glsl: fix function inlining for images 2022-12-12 21:28:44 +00:00
opt_if_simplification.cpp
opt_minmax.cpp
opt_rebalance_tree.cpp
opt_tree_grafting.cpp glsl: Don't tree graft in the condition of an assignment 2022-02-11 17:25:33 +00:00
program.h glsl: remove now unused GLSL IR varying linker code 2022-05-16 03:33:18 +00:00
propagate_invariance.cpp compiler/glsl: Return progress from propagate_invariance() 2021-04-20 18:54:57 +00:00
README mesa: update or remove out of date references to ir_to_mesa 2021-12-06 10:15:08 +00:00
s_expression.cpp
s_expression.h
serialize.cpp mesa/st: fix possible crash related to arb invalid memory access 2023-02-10 04:45:29 +00:00
serialize.h
shader_cache.cpp mesa: rename gl_shader::sha1 to disk_cache_sha1 2021-11-26 11:58:27 +00:00
shader_cache.h
standalone.cpp glsl/standalone: Make all standalone contexts have NewProgram set. 2023-03-22 22:52:45 +00:00
standalone.h
standalone_scaffolding.cpp glsl/standalone: Make all standalone contexts have NewProgram set. 2023-03-22 22:52:45 +00:00
standalone_scaffolding.h glsl/standalone: Pull out a helper function for adding GLSL source shaders. 2023-03-22 22:52:45 +00:00
string_to_uint_map.cpp glsl: add some more c wrappers for string_to_uint_map 2023-07-06 01:21:06 +00:00
string_to_uint_map.h glsl: add some more c wrappers for string_to_uint_map 2023-07-06 01:21:06 +00:00
test.cpp
test_optpass.cpp glsl: Drop PIPE_SHADER_CAP_DFRACEXP_DLDEXP_SUPPORTED. 2023-04-06 02:32:01 +00:00
test_optpass.h
TODO

Welcome to Mesa's GLSL compiler.  A brief overview of how things flow:

1) lex and yacc-based preprocessor takes the incoming shader string
and produces a new string containing the preprocessed shader.  This
takes care of things like #if, #ifdef, #define, and preprocessor macro
invocations.  Note that #version, #extension, and some others are
passed straight through.  See glcpp/*

2) lex and yacc-based parser takes the preprocessed string and
generates the AST (abstract syntax tree).  Almost no checking is
performed in this stage.  See glsl_lexer.ll and glsl_parser.yy.

3) The AST is converted to "HIR".  This is the intermediate
representation of the compiler.  Constructors are generated, function
calls are resolved to particular function signatures, and all the
semantic checking is performed.  See ast_*.cpp for the conversion, and
ir.h for the IR structures.

4) The driver (Mesa, or main.cpp for the standalone binary) performs
optimizations.  These include copy propagation, dead code elimination,
constant folding, and others.  Generally the driver will call
optimizations in a loop, as each may open up opportunities for other
optimizations to do additional work.  See most files called ir_*.cpp

5) linking is performed.  This does checking to ensure that the
outputs of the vertex shader match the inputs of the fragment shader,
and assigns locations to uniforms, attributes, and varyings.  See
linker.cpp.

6) The driver may perform additional optimization at this point, as
for example dead code elimination previously couldn't remove functions
or global variable usage when we didn't know what other code would be
linked in.

7) The driver performs code generation out of the IR, taking a linked
shader program and producing a compiled program for each stage.  See
../mesa/program/ir_to_mesa.cpp for Mesa IR code generation.

FAQ:

Q: What is HIR versus IR versus LIR?

A: The idea behind the naming was that ast_to_hir would produce a
high-level IR ("HIR"), with things like matrix operations, structure
assignments, etc., present.  A series of lowering passes would occur
that do things like break matrix multiplication into a series of dot
products/MADs, make structure assignment be a series of assignment of
components, flatten if statements into conditional moves, and such,
producing a low level IR ("LIR").

However, it now appears that each driver will have different
requirements from a LIR.  A 915-generation chipset wants all functions
inlined, all loops unrolled, all ifs flattened, no variable array
accesses, and matrix multiplication broken down.  The Mesa IR backend
for swrast would like matrices and structure assignment broken down,
but it can support function calls and dynamic branching.  A 965 vertex
shader IR backend could potentially even handle some matrix operations
without breaking them down, but the 965 fragment shader IR backend
would want to break to have (almost) all operations down channel-wise
and perform optimization on that.  As a result, there's no single
low-level IR that will make everyone happy.  So that usage has fallen
out of favor, and each driver will perform a series of lowering passes
to take the HIR down to whatever restrictions it wants to impose
before doing codegen.

Q: How is the IR structured?

A: The best way to get started seeing it would be to run the
standalone compiler against a shader:

./glsl_compiler --dump-lir \
	~/src/piglit/tests/shaders/glsl-orangebook-ch06-bump.frag

So for example one of the ir_instructions in main() contains:

(assign (constant bool (1)) (var_ref litColor)  (expression vec3 * (var_ref Surf
aceColor) (var_ref __retval) ) )

Or more visually:
                     (assign)
                 /       |        \
        (var_ref)  (expression *)  (constant bool 1)
         /          /           \
(litColor)      (var_ref)    (var_ref)
                  /                  \
           (SurfaceColor)          (__retval)

which came from:

litColor = SurfaceColor * max(dot(normDelta, LightDir), 0.0);

(the max call is not represented in this expression tree, as it was a
function call that got inlined but not brought into this expression
tree)

Each of those nodes is a subclass of ir_instruction.  A particular
ir_instruction instance may only appear once in the whole IR tree with
the exception of ir_variables, which appear once as variable
declarations:

(declare () vec3 normDelta)

and multiple times as the targets of variable dereferences:
...
(assign (constant bool (1)) (var_ref __retval) (expression float dot
 (var_ref normDelta) (var_ref LightDir) ) )
...
(assign (constant bool (1)) (var_ref __retval) (expression vec3 -
 (var_ref LightDir) (expression vec3 * (constant float (2.000000))
 (expression vec3 * (expression float dot (var_ref normDelta) (var_ref
 LightDir) ) (var_ref normDelta) ) ) ) )
...

Each node has a type.  Expressions may involve several different types:
(declare (uniform ) mat4 gl_ModelViewMatrix)
((assign (constant bool (1)) (var_ref constructor_tmp) (expression
 vec4 * (var_ref gl_ModelViewMatrix) (var_ref gl_Vertex) ) )

An expression tree can be arbitrarily deep, and the compiler tries to
keep them structured like that so that things like algebraic
optimizations ((color * 1.0 == color) and ((mat1 * mat2) * vec == mat1
* (mat2 * vec))) or recognizing operation patterns for code generation
(vec1 * vec2 + vec3 == mad(vec1, vec2, vec3)) are easier.  This comes
at the expense of additional trickery in implementing some
optimizations like CSE where one must navigate an expression tree.

Q: Why no SSA representation?

A: Converting an IR tree to SSA form makes dead code elimination,
common subexpression elimination, and many other optimizations much
easier.  However, in our primarily vector-based language, there's some
major questions as to how it would work.  Do we do SSA on the scalar
or vector level?  If we do it at the vector level, we're going to end
up with many different versions of the variable when encountering code
like:

(assign (constant bool (1)) (swiz x (var_ref __retval) ) (var_ref a) )
(assign (constant bool (1)) (swiz y (var_ref __retval) ) (var_ref b) )
(assign (constant bool (1)) (swiz z (var_ref __retval) ) (var_ref c) )

If every masked update of a component relies on the previous value of
the variable, then we're probably going to be quite limited in our
dead code elimination wins, and recognizing common expressions may
just not happen.  On the other hand, if we operate channel-wise, then
we'll be prone to optimizing the operation on one of the channels at
the expense of making its instruction flow different from the other
channels, and a vector-based GPU would end up with worse code than if
we didn't optimize operations on that channel!

Once again, it appears that our optimization requirements are driven
significantly by the target architecture.  For now, targeting the Mesa
IR backend, SSA does not appear to be that important to producing
excellent code, but we do expect to do some SSA-based optimizations
for the 965 fragment shader backend when that is developed.

Q: How should I expand instructions that take multiple backend instructions?

Sometimes you'll have to do the expansion in your code generation.
However, in many cases you'll want to do a pass over the IR to convert
non-native instructions to a series of native instructions.  For
example, for the Mesa backend we have ir_div_to_mul_rcp.cpp because
Mesa IR (and many hardware backends) only have a reciprocal
instruction, not a divide.  Implementing non-native instructions this
way gives the chance for constant folding to occur, so (a / 2.0)
becomes (a * 0.5) after codegen instead of (a * (1.0 / 2.0))

Q: How shoud I handle my special hardware instructions with respect to IR?

Our current theory is that if multiple targets have an instruction for
some operation, then we should probably be able to represent that in
the IR.  Generally this is in the form of an ir_{bin,un}op expression
type.  For example, we initially implemented fract() using (a -
floor(a)), but both 945 and 965 have instructions to give that result,
and it would also simplify the implementation of mod(), so
ir_unop_fract was added.  The following areas need updating to add a
new expression type:

ir.h (new enum)
ir.cpp:operator_strs (used for ir_reader)
ir_constant_expression.cpp (you probably want to be able to constant fold)
ir_validate.cpp (check users have the right types)

You may also need to update the backends if they will see the new expr type:

../mesa/program/ir_to_mesa.cpp

You can then use the new expression from builtins (if all backends
would rather see it), or scan the IR and convert to use your new
expression type (see ir_mod_to_floor, for example).

Q: How is memory management handled in the compiler?

The hierarchical memory allocator "talloc" developed for the Samba
project is used, so that things like optimization passes don't have to
worry about their garbage collection so much.  It has a few nice
features, including low performance overhead and good debugging
support that's trivially available.

Generally, each stage of the compile creates a talloc context and
allocates its memory out of that or children of it.  At the end of the
stage, the pieces still live are stolen to a new context and the old
one freed, or the whole context is kept for use by the next stage.

For IR transformations, a temporary context is used, then at the end
of all transformations, reparent_ir reparents all live nodes under the
shader's IR list, and the old context full of dead nodes is freed.
When developing a single IR transformation pass, this means that you
want to allocate instruction nodes out of the temporary context, so if
it becomes dead it doesn't live on as the child of a live node.  At
the moment, optimization passes aren't passed that temporary context,
so they find it by calling talloc_parent() on a nearby IR node.  The
talloc_parent() call is expensive, so many passes will cache the
result of the first talloc_parent().  Cleaning up all the optimization
passes to take a context argument and not call talloc_parent() is left
as an exercise.

Q: What is the file naming convention in this directory?

Initially, there really wasn't one.  We have since adopted one:

 - Files that implement code lowering passes should be named lower_*
   (e.g., lower_builtins.cpp).
 - Files that implement optimization passes should be named opt_*.
 - Files that implement a class that is used throught the code should
   take the name of that class (e.g., ir_hierarchical_visitor.cpp).
 - Files that contain code not fitting in one of the previous
   categories should have a sensible name (e.g., glsl_parser.yy).