Re: Linux likely() unlikely() for PostgreSQL

From: John Naylor <johncnaylorls(at)gmail(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Matthias van de Meent <boekewurm+postgres(at)gmail(dot)com>, wenhui qiu <qiuwenhuifx(at)gmail(dot)com>, PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: Linux likely() unlikely() for PostgreSQL
Date: 2024-08-12 08:34:26
Message-ID: CANWCAZaKmXXNmiAtiAkcYuK68RsG6Crv9iiFnh1O0EScd9DN8Q@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Sun, Jun 30, 2024 at 10:24 PM Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> wrote:

> In general, we have a policy of using likely/unlikely very sparingly,
> and only in demonstrably hot code paths. This hook call certainly
> doesn't qualify as hot.

I just remembered an article I read a while back by a compiler
engineer who said that compilers have heuristics that treat NULL
pointers as "unlikely" since the most common reason to test that is so
we can actually dereference it and do something with it, and in that
case a NULL pointer is an exceptional condition. He also said it
wasn't documented so you can only see this by looking at the source
code. Instead of taking the time to verify that, I created some toy
examples and it seems to be true:

https://godbolt.org/z/dv6M5ecY5

This works all the way back to clang 3.1 and (at least, because
Compiler Explorer doesn't go back any further) gcc 3.4.6, so it's an
ancient heuristic. If we can rely on this, we could remove the handful
of statements of the form "if (unlikely(foo_ptr == NULL))" and
document it in c.h. It may be iffy to rely on an undocumented
heuristic, but it also seems silly to have a use-sparingly policy if
some of our current uses have zero effect on the emitted binary (I
haven't checked yet).

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Meftun Cincioğlu 2024-08-12 08:55:17 Enabling parallel execution for cursors
Previous Message cca5507 2024-08-12 08:34:25 Re: Historic snapshot doesn't track txns committed in BUILDING_SNAPSHOT state