https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86604

            Bug ID: 86604
           Summary: Compiler can't think of smaller variable ranges
           Product: gcc
           Version: 9.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: mcccs at gmx dot com
  Target Milestone: ---

Summary: The compiler thinks variables as of the widest domain.
(32 bits for int, 64 bits for int64_t) It's possible to optimize
further by giving the compiler a hint about the domain. It can
be used to eliminate most of the branches.

For clarity, I'm going to define __builtin_guarantee first.

#define __builtin_guarantee(a) \
if (!(a)) {                    \
    __builtin_unreachable();   \
}

The optimization: We can tell the compiler about the range
of a parameter, and it'll be able to use this knowledge
to eliminate most of the branches.

void CreateChecksum(int isTestNet, int *t) {
    if (isTestNet == 0)
        *t += 1;
}

Output with `-Ofast -march=native`:

CreateChecksum:
  test edi, edi
  jne .L3
  inc DWORD PTR [rsi]
.L3:
  ret

But if we could do that:

void CreateChecksum(int isTestNet, int *t) {
    __builtin_guarantee(isTestNet == 0 || isTestNet == 1);
    if (isTestNet == 0)
        *t += 1;
}

It'd see that

*t += isTestNet ^ 1

But for some reason, Compiler doesn't limit the number of
possibilities of variables according to builtin unreachable.

Reply via email to