Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are GLSL compilers well optimized

Are recent GLSL compilers smart/well optimized?

In other words, if I go brainless and write stuff like the following, would recent compilers save my day and optimize away the unnecessary code, or should I be always careful with what I write?

// All of the values are constants

if (3.7 == 3.7) // Will the condition be executed or removed at build time?
   x++;

// Will this whole block be entirely removed? (or should I use macros)
if (1 == 2)
    x++;

for (i = 0; i < 0; ++i) // Remove this
    x++;

for (i = 0; i < varA * varB; ++i) // Compute varA * varB once, outside the loop
    x++;

vec3 v = vec3(0);
if (length(v) > 0) // Remove
    x++;

float p = mix(varA, varB, 1); // p = varB

float p = 5;
p *= uniform * 0; // Just set a = 0 from the start

float p = 5;
p *= 1; // Remove that

There is a lot more things that I can't get out now, but you should have got the point.

Also, can recent compilers automatically detect less obvious optimizations, like the ones described there: http://www.opengl.org/wiki/GLSL_Optimizations

Is there a known trade off between "compilation time" versus "time spent optimizing", set up by the implementors or the specification?

like image 208
deck Avatar asked Mar 13 '14 13:03

deck


People also ask

Is Glsl compiled?

In OpenGL (prior to Vulkan), GLSL code is submitted to the driver as source code strings via a glShaderSource call. The driver is fully responsible for compilation, i.e. the driver must provide a built-in GLSL compiler for that GPU architecture.

Do compilers optimize code?

Compilers are free to optimize code so long as they can guarantee the semantics of the code are not changed.


1 Answers

GLSL compilers are very conservative on floating point optimizations. You cannot be sure for any particular optimization. The rule of thumb is: optimize whatever you can and don't hope for any help from a GLSL compiler.

Read Low-Level Thinking in High-Level Shading Languages by Emil Persson for interesting details and case-studies.

P.S: This answer may sound pessimistic. However, GLSL compilers still do a lot of great job optimizing your code. Just don't count on it and do your best.

like image 149
Sergey K. Avatar answered Oct 05 '22 08:10

Sergey K.