1. 5
  1. 3

    I’m a little bit confused. The article starts with a long explanation of how common it is to try to avoid ‘if’s and how stupid that is… then goes on to prove that whether or not an ‘if’ is a branch is highly unpredictable and depends on the compiler and compiler settings. Seems a lot to me like I want to avoid ‘if’s where I don’t want a branch, unless I’m willing to go through every possible build of my program with every compiler and every optimization setting I’ll use and verify that none of them generate a branch. Even worse, for GLSL, I’m relying on the user’s compiler, so I can’t even inspect the compiled code which users will actually be running.

    My take-away is basically “avoid ‘if’s in code where you don’t want branches because there’s usually at least one commonly used compiler which generates a branch instead of a cmov”. But I somehow feel like that contradicts the entire message?

    The point that branches aren’t necessarily bad is important; always profile, always measure. I’ve significantly slowed down code while trying to optimize away branches before, because the branches I optimized away predictable branches and the branchless code I replaced it with was slower. If the article was just about how your branchless code might be slower than the branches it replaces I’d agree 100%. But most of the article isn’t about that.

    1. 1

      Is MSVC really so bad at instruction selection?

      1. 2

        No, it does a emit a cmov, on -O1 or -O2. But apparently -O is not an abbreviation for -O2: https://docs.microsoft.com/en-us/cpp/build/reference/o-options-optimize-code

        1. 1

          Can’t seem to get it to emit a cmov even with -O2 or -O1. You sure about msvc emitting a cmov?


          1. 1

            Oh, I was trying a different example: https://godbolt.org/z/W8dbP6 I also get different results with if vs ternary. I guess it is pretty fragile.

            1. 1

              Yeah it surprised me to be honest, that small example seems like an easy optimization but its interesting. Wonder what is tripping the optimizer up.