KhronosGroup / KhronosGroup/SPIRV-Tools

spirv-opt doesn't "kill" unneeded ALU ops in vectors

Open
#3,466 2 comments 1 reaction 0 assignees View on GitHub
component:optimization
Dominant language
C++
Stars
1.4k
Forks
709
Avg merge
1d 22h
Merged PRs (30d)
28

Description

It's common for a fragment shader to have to output to RGB or RGBA render targets, in the former case, it would be good to "kill" all ALU operations pertaining to the A component that is not needed. One way to attempt to do this is just to add something like `out.a = 1.0` at the end of the shader and hopping that the optimizer will do the rest. Unfortunately this doesn't seem to be the case, even for very simple programs. For e.g.

```
#version 310 es
precision mediump float;
precision mediump int;
layout(location = 0) uniform vec4 value;
layout(location = 0) out vec4 fragColor;

void main() {
vec4 x = smoothstep(0.0, 1.0, value);
x.a = 1.0;
fragColor = x;
}
```

Ideally this would not apply `smoothstep` on the `.a` component. Here I use `smoothstep` as a placeholder for potentially a very complex shader.

```
./glslangValidator --target-env opengl test.frag -o test.spv
./spirv-opt -O test.spv -o test.opt.spv
./spirv-cross --es test.opt.spv
```

Yields:

```
#version 310 es
precision mediump float;
precision highp int;
layout(location = 0) uniform vec4 value;
layout(location = 0) out vec4 fragColor;
void main()
{
vec4 _26 = smoothstep(vec4(0.0), vec4(1.0), value);
_26.w = 1.0;
fragColor = _26;
}
```

The alternative would be to write the shader twice, or to write all operations as a `vec3+float`.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the GLSL example with glslangValidator, spirv-opt -O, and spirv-cross, then inspect how spirv-opt handles vector components made dead by the final alpha assignment. Done means the optimized result no longer applies smoothstep to the unused alpha component while preserving the RGB output.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers, computer-graphics
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.