I have read that GLSL (specifically v1.0.17: my application is running under WebGL) compilers will optimize away redundant assignments such as:
gl_FragCoord = ProjectionMatrix * ModelViewMatrix * VertexPosition;
. . .
gl_FragCoord = ProjectionMatrix * ModelViewMatrix * VertexPosition;
Is the compiler also smart enough to perform the same optimization across function calls? For example:
void doSomething1(void) {
. . .
gl_FragCoord = ProjectionMatrix * ModelViewMatrix * VertexPosition;
}
void doSomething2(void) {
. . .
gl_FragCoord = ProjectionMatrix * ModelViewMatrix * VertexPosition;
}
void main(void) {
doSomething1();
doSomething2();
}
I downloaded the GPU ShaderAnalyzer from AMD and fed the following GLSL program into it:
This produced the following disassembly (or equivalent) on every card from Radeon HD 2400 to Radeon HD 6970:
Then I commented out the
doSomething2()function and its call in themainmethod. The result was exactly the same: every shader in AMD’s tool optimized out the redundant math. So the answer to this question is yes: in the general case, GLSL compilers will be smart enough to perform this optimization, with the caveat that @nicol-bolas pointed out in his comment: compiler optimizations are specific to each compiler, and there is no 100% guarantee that this will be true for all compilers. The safest bet is, of course, to perform such optimizations yourself whenever possible — but it’s nice to know that this is the case when for whatever reason you can’t.UPDATE: I compiled the same program, with and without commenting out the second function call, under Cg (one of NVIDIA’s compilers), and in both cases it produced the following:
So yes, NVIDIA optimizes it too — or at least, the Cg compiler does. I found claims that Cg-compiled code runs on Intel GPUs, but this is outside the realm of my expertise, so take that for what it is.
If anyone wants to add test cases to this, feel free, but at this point I feel the question has been answered suitably.