glsl4idea icon indicating copy to clipboard operation
glsl4idea copied to clipboard

Return in a preprocessor #ifdef directive marks the rest of the shader as unreachable code

Open Nehon opened this issue 8 years ago • 2 comments

Hello, I've just noticed an issue with this code :

void main(){    
    #ifdef TEXTURE
          gl_FragColor = texture2D(m_Texture, texCoord);
          return;
    #endif

    gl_FragColor = vec4(1.0);
}

The last line gl_FragColor = vec4(1.0); is marked as unreachable code.

Nehon avatar Mar 12 '16 12:03 Nehon

Defines are very problematic, because they don't create lexical scopes like normal blocks do and can begin in different block to where they end. So to handle them correctly, we would probably have to create alternate versions of the parse tree for each #ifdef block and parse them as separate alternate ~~universes~~ files. I don't have enough time to investigate other ways to do it or to implement this bruteforce one, so it is unlikely that this issue will ever be fixed (and many many other corner cases which exist because of preprocessor).

That said, in this exact case, the unreachable code inspection is actually semi-right, it will be unreachable if the TEXTURE is false :)

As a workaround, the code can be rewritten as:

#define TEXTURE true
// or
#define TEXTURE false

void main(){    
    if(TEXTURE){
          gl_FragColor = texture2D(m_Texture, texCoord);
          return;
    }

    gl_FragColor = vec4(1.0);
}

This should not trigger unreachable code marking and the compiler should produce identical machine code.

Darkyenus avatar Mar 12 '16 16:03 Darkyenus

I'm not sure how the compiler will treat that but if that end up in a dynamic branching it's not good. Anyway, no big deal, I just thought I'd mention it. I understand the issue is not simple to tackle. Also it's a pretty rare corner case, so it's not really a bother.

Thank you.

Nehon avatar Mar 12 '16 19:03 Nehon