John Doe
John Doe

Reputation: 101

Will GLSL compiler remove unnecessary variable initialization?

For example, I have a code like this (fragment shader):

Option 1

#version 330 core

uniform sampler2D baseImage;
in vec2 texCoord;
out vec3 fragColor;

void main() {
    fragColor = texture(baseImage, texCoord).rgb;

    // some calculations that don't use fragColor
    vec3 calcResult = ...

    fragColor = calcResult;
}

Will compiler remove fragColor = texture(baseImage, texCoord).rgb?

Option 2

#version 330 core

uniform sampler2D baseImage;
in vec2 texCoord;
out vec3 fragColor;

void init0() {
    fragColor = texture(baseImage, texCoord).rgb;
}

void init1() {
    fragColor = texture(baseImage, texCoord).rgb;
}

void main() {
    init0();
    init1();
}

Will compiler use code from init1()?

Upvotes: 1

Views: 139

Answers (1)

Rabbid76
Rabbid76

Reputation: 210877

What the compiler has to optimize is not specified in the specification.
The only thing what is specified is the behavior of active program resources. See OpenGL 4.6 Core Profile Specification - 7.3.1 Program Interfaces, page 102.

The glsl shader code is compiled by the graphics driver (except you generate SPIR-V), so it depends on. But a modern graphics driver will do such optimizations.

By default optimizations are switched on, but they can be switched off by

#pragma optimize(off)

See OpenGL Shading Language 4.60 Specification - 3.3. Preprocessor

Upvotes: 3

Related Questions