plenty code is confused about function level static - Mailing list pgsql-hackers

From Andres Freund
Subject plenty code is confused about function level static
Date
Msg-id 20240417213953.zegcual4q3pyxmvw@awork3.anarazel.de
Whole thread Raw
Responses Re: plenty code is confused about function level static
Re: plenty code is confused about function level static
Re: plenty code is confused about function level static
List pgsql-hackers
Hi,

We have a fair amount of code that uses non-constant function level static
variables for read-only data. Which makes little sense - it prevents the
compiler from understanding

a) that the data is read only and can thus be put into a segment that's shared
   between all invocations of the program
b) the data will be the same on every invocation, and thus from optimizing
   based on that.

The most common example of this is that all our binaries use
  static struct option long_options[] = { ... };
which prevents long_options from being put into read-only memory.


Is there some reason we went for this pattern in a fair number of places? I
assume it's mostly copy-pasta, but...


In practice it often is useful to use 'static const' instead of just
'const'. At least gcc otherwise soemtimes fills the data on the stack, instead
of having a read-only data member that's already initialized. I'm not sure
why, tbh.


Attached are fixes for struct option and a few more occurrences I've found
with a bit of grepping.


There are lots of places that could benefit from adding 'static
const'.

E.g. most, if not all, HASHCTL's should be that, but that's more verbose to
change, so I didn't do that.

Greetings,

Andres Freund

Attachment

pgsql-hackers by date:

Previous
From: Robert Haas
Date:
Subject: fix tablespace handling in pg_combinebackup
Next
From: Andres Freund
Date:
Subject: Re: fix tablespace handling in pg_combinebackup