Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The probability of selected EFLAGS bits

We all know that when looking at source code it's a safe assumption that the direction flag will be clear. The probability of the direction flag is very low.

I wanted to find out about the probabilities of the other flags. That's why I wrote a test program that single steps some of my existing software, incrementing a counter for each of the first 12 EFLAGS bits.

Probability of x86 processor flags

Results confirm the assumption made about the direction flag (DF) and, not surprisingly, show that the probability of the overflow flag (OF) is very low.

But what about the other flags? The carry flag (CF), auxiliary flag (AF), zero flag (ZF), and sign flag (SF) seem to settle at 25%, but the parity flag (PF) jumps out at well over 50%.

I'd like to know why the probabilities of CF, AF, ZF, and SF are so low.

For the PF, my own two cents explanation tells me that, given the 50-50 distribution of parity even and parity odd in all possible 8-bit bitpatterns and realizing that a couple of the most frequently used numbers (0 and -1) have parity even, a more than 50% chance is reasonable.

like image 519
Sep Roland Avatar asked Jan 28 '18 19:01

Sep Roland


1 Answers

The fact that certain EFLAGS bits are getting changed often merely reflects the fact that early Intel 8086 instructions (and incidentally still very often used ones) were designed to update the flags unconditionally. That design decision did not pay out well, but it does not hurt modern x86 designs either until someone uses values of flags. Usage of a flag (as a predicate of a conditional branch) creates a dependency in the code stream and it may potentially affect performance.

If there are two (three, four…) instructions that consequently update the same flag bit but only the last value is used later by a third instruction, then all previous flag calculation can be omitted. Alternatively, the recalculation of EFLAGS can be delayed until something has requested its actual value.

Thus, it is a more interesting question how often individual EFLAG bits are used. And there are studies that answer it.

The following picture is taken from Yair Lifshitz et al. "Zsim: A Fast Architectural Simulator for ISA Design-Space Exploration" section 3.2.3 PDF:

EFLAGS use

As you can see, nobody cares about auxiliary flag, while carry and zero flags affect many decisions in code. Other authors came to similar conclusions, which are important in context of e.g. software simulation design, because they allow applying an important optimization of lazy flag evaluation in binary translators and interpreters.

like image 137
Grigory Rechistov Avatar answered Sep 20 '22 12:09

Grigory Rechistov