Clément Foucault 74e6d2c575 GPU: Shader: Add support for basic loop unrolling through preprocessor
This adds basic unrolling support for 2 syntax:
- `[[gpu::unroll]]` which does full loop unrolling
- `[[gpu::unroll(x)]]` which unrolls `x` iteration

Nesting is supported.

This change is motivated by the added cost in compilation
and execution time that some loops have even if they have
compile time defined iteration counts.

The syntax is inspired by `GL_EXT_control_flow_attributes`.
However, we might want to have our own prefix to show it is
a blender specific feature and that it differs from the standard.
I propose `[[gpu::unroll]]`.

In the future, we could extend this to support more directives that
can be expanded to backend specific extension / syntax. This would
avoid readability issue an error prone copy paste of large amount
of preprocessor directives.

Currently, given that GL's GLSL flavor doesn't support
any of these attributes, the preprocessor does some copy-pasting
that does the unrolling at the source level. Note that the added
`#line` allow for correct error logging.

For the `[[gpu::unroll]]` syntax, the `for` declaration
needs to follow a specific syntax to deduce the number
of loop iteration.
This variant removes the continue condition between iteration,
so all iterations are evaluated. This could be modified
using a special keyword.

For the `[[gpu::unroll(n)]]` syntax, the usercode needs
to make sure that `n` is large enough to cover all iterations
as the loop is completely removed.
We could add shader `assert` to make sure that there is
never a remaining iteration.
This behavior is usually different from what you see in other
implementation as we do not keep a loop at all. Usually, compilers
still keep the loop if it is not unrolled fully. But given we don't
have IR, this is the best we can do.

`break` and `continue` statement are forbidden at the unrolled loop
scope level. Nested loop and switch can contain these keywords.
This is accounted for by checks in the pre-processor.

Only `for` loops are supported for now. There are no real
incentive to add support for `while` given how rare it is
in the shader codebase.

Rel #137446

Pull Request: https://projects.blender.org/blender/blender/pulls/137444
2025-05-05 13:37:51 +02:00
2023-12-08 13:28:13 +11:00
2025-01-08 16:42:50 +01:00
2025-03-12 21:55:59 +11:00

Blender

Blender is the free and open source 3D creation suite. It supports the entirety of the 3D pipeline—modeling, rigging, animation, simulation, rendering, compositing, motion tracking and video editing.

Blender screenshot

Project Pages

Development

License

Blender as a whole is licensed under the GNU General Public License, Version 3. Individual files may have a different but compatible license.

See blender.org/about/license for details.

Description
No description provided
Readme 841 MiB
Languages
C++ 78%
Python 14.9%
C 2.9%
GLSL 1.9%
CMake 1.2%
Other 0.9%