Search this blog

24 July, 2008

Quick shader tip

Don't use the const keyword. It's broken in some compilers (i.e. it leads to bad code) and it's not helping at all in optimizing the shader. Const is only helpful for the programmer, not for the compiler anyway (this is also true for C++). The compiler is smart enough to find what it really const and what not, at it has access to the whole sourcecode (no linking). The only exception of course are the global variables, that being by default uniform parameters, are always assumed non-const even if the shader does not change them.

3 comments:

Nick said...

I haven't experimented with const in shaders; what kind of bugs have you seen? Is it specific to a particular shader language?

BTW, thought it was worth mentioning that in C++ the usual reason to care about const pointers as parameters is for alias optimization.

http://www.compileroptimizations.com/category/alias_optimization_const_qualifier.htm

Despite being marked uncommon on that page, I have seen this optimization (although I haven't checked for it recently).

DEADC0DE said...

Some versions of the DirectX HLSL compiler do produce bad code (corrupted) with const. I could not really nail down when it happens, but I've seen it happening, more than once.

DEADC0DE said...

And by the way, const objects are good, in C++, the unuseful thing (optimization-wise) is passing non-const objects as const! And to avoid pointer aliasing, the best thing is to use the restrict keyword (even if it's not in the C++ standard yet, so you might want to wrap it into a macro defined depending on your compiler)