1

The 'select' instruction is used to choose one value based on a condition, without branching.

I want to know the differences between branching and select instructions (preferably for both x86 architectures and PTX). As far as I know, select is more optimal compared to branching instructions, but I don't have a clear picture.

Sayan
  • 2,662
  • 10
  • 41
  • 56
  • `x86` doesn't *have* a general select instruction that I'm aware of. Are you thinking `cmov`? – nneonneo Sep 27 '12 at 00:41
  • I'm afraid I have very limited knowledge about ISAs, but I am referring to an instruction that resolves conditionals without branching. does that make sense somehow? – Sayan Sep 27 '12 at 00:48

1 Answers1

2

Branching is a general-purpose mechanism used to redirect control flow. It is used to implement most forms of the if statement (when specific optimizations don't apply).

Selection is a specialized instruction available on some instruction sets which can implement some forms of the conditional expression

z = (cond) ? x : y;

or

if(cond) z = x;

provided that x and y are plain values (if they were expressions, they would both have to be computed before the select, which might incur performance penalties or incorrect side-effect evaluation). Such an instruction is necessarily more limited than branching, but has the distinct advantage that the instruction pointer doesn't change. As a result, the processor does not need to flush its pipeline on a branch misprediction (since there is no branch). Because of this, a select instruction (where available) is faster.

On some superscalar architectures, e.g. CUDA, branches are very expensive performance-wise because the parallel units must remain perfectly synchronized. On CUDA, for example, every execution unit in a block must take the same execution path; if one thread branches, then every unit steps through both branches (but will execute no-operations on the branch not taken). A select instruction, however, doesn't incur this kind of penalty.

Note that most compilers will, with suitable options, generate 'select'-style instructions like cmov if given a simple-enough if statement. Also, in some cases, it is possible to use bitwise manipulation or logical operations to combine a boolean conditional with expression values without performing a branch.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • Thank you. So, `select` would work for a single (or may be upto a limited number) condition, like `z = (cond) ? x : y;`; whereas, in case of multiple statements following the condition (like `if (cond) {...10 lines...} else {...10 lines...}`), there would be a jump to another part of memory? And then, there are cases like bitwise manipulation (which might be compiler specific) like `r = y ^ ((x ^ y) & -(x < y)); // min(x, y)` - (http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs). Am I correct? – Sayan Sep 27 '12 at 04:00