0

I was going to ask this on Electric Engineering, but decided it's more related to programming.

With digital logic, we can reduce truth tables to minimized functions using Karnaugh diagrams or Boolean algebra. On a CPU, these functions can of course be expressed using conditional statements, however, I'm curious if there's a standard approach for realizing them without branches, using only bit operations, whenever this is possible.

I don't know if this is ever interesting to be able to do nowadays, or if it would actually be more efficient with today's processors. Still, it might have been relevant in the past and would be interesting to know anyhow.

So, let's say I have f = !a*b + !b*!c, or any similar function: is there a system (like Karnaugh) for finding out whether there's a "smart" way to avoid branches, by using extra registers, calculating total bits, masking, anything? Or, is it just something you see if you see it and otherwise you don't?

Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44
Toerndev
  • 715
  • 1
  • 6
  • 21
  • not sure if this is related to your question, but the ARM instruction set has conditionals on each instruction, so for some if-then-else type sequences you dont actually have to branch, you set the conditionals right on the instructions and they run through the pipe. – old_timer May 08 '13 at 14:53
  • some sequences you can, yes. for example you can do some math that for one condition results in a register containing 0 another register containing 1, then compute both results the if and the else case, then multiply one by its register, the other by its register (only one of the two contains a one) then add the results a = aflag * aresult, b = bflag*bresult, result = a+b; only one of aflag and bflag is 1, the other is zero, nulling out that result – old_timer May 08 '13 at 14:56
  • you can use an and with all ones or all zeros as well to null out one of the conditions. – old_timer May 08 '13 at 14:57
  • The trivial approach of using a truth (lookup) table is also branchless, although probably not optimal due to index calculation and memory access. – Jester May 08 '13 at 14:58
  • In the absence of side-effects, you can merge the results of both sides of a branch by muxing the results. That's very general, but often not the best thing to do. – harold May 08 '13 at 16:17
  • That's a lot of interesting points just in the comments. @dwelch: I am aware of those instructions, by "run through the pipe" does it mean there is no branching, no downside, no effect on whatever look-ahead function or such that the CPU uses? I thought they were mostly syntactic sugar (still very nice) but in that case it's way more than that. – Toerndev May 08 '13 at 18:48
  • On a second though, the CPU must still wait until a value has been read before it can look past those instructions. Eh, I don't really know how this works do I. – Toerndev May 08 '13 at 19:30

0 Answers0